问:
Avoid table scan and use index instead in query
I am designing a new database and have noticed my queries are not scaling as well as they should be. When my aggregations involve hundreds of records I am seeing significant increases in response times. I am wondering if my query is deeply flawed or if I am just not using the right index.

I have done a lot of tweaking to my query but have not come up with a way to eliminate doing a full table scan and instead use an index. When I use a tool similar to EXPLAIN on my query I see the following:

Full table scans are generally inefficient, avoid using them.

Your query uses MySQL's 'filesort' operation. This tends to slow down queries.

Your query uses MySQL's temporary tables. This can require extra I/O and tends to slow down queries.

Table:

```<code>CREATE TABLE `indexTable` (
  `id` int(10) unsigned NOT NULL,
  `userId` int(10) unsigned NOT NULL,
  `col1` varbinary(320) NOT NULL,
  `col2` tinyint(3) unsigned NOT NULL,
  `col3` tinyint(3) unsigned NOT NULL,
  `createdAt` bigint(20) unsigned NOT NULL,
  `updatedAt` bigint(20) unsigned NOT NULL,
  `metadata` json NOT NULL,
  PRIMARY KEY (`id`,`userId`,`col1`,`col2`,`col3`),
  KEY `createdAt` (`createdAt`),
  KEY `id_userId_col1_col2_createdAt` (`id`,`userId`,`col1`,`col2`,`createdAt`),
  KEY `col1_col2_createdAt` (`col1`,`col2`,`createdAt`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=COMPRESSED KEY_BLOCK_SIZE=8
</code>```

Query:

```<code>SELECT t1.id, t1.userId, t1.col1, t1.col2, t1.col3, t1.metadata
FROM indexTable as t1
INNER JOIN(
    SELECT col1, col2, MAX(createdAt) AS maxCreatedAt
    FROM indexTable
    WHERE id = ? AND userId = ?
    GROUP BY col1, col2
    ORDER BY maxCreatedAt
    LIMIT 10 OFFSET 0) AS sub
ON t1.col1 = sub.col1
AND t1.col2 = sub.col2
AND t1.createdAt = sub.maxCreatedAt
WHERE t1.id = ? AND t1.userId = ?
ORDER BY t1.createdAt;
</code>```

PK: id, userId, col1, col2, col3
Index: createdAt

Explain:

```<code>{
  "query_block": {
    "select_id": 1,
    "cost_info": {
      "query_cost": "34.50"
    },
    "ordering_operation": {
      "using_temporary_table": true,
      "using_filesort": true,
      "cost_info": {
        "sort_cost": "10.00"
      },
      "nested_loop": [
        {
          "table": {
            "table_name": "sub",
            "access_type": "ALL",
            "rows_examined_per_scan": 10,
            "rows_produced_per_join": 10,
            "filtered": "100.00",
            "cost_info": {
              "read_cost": "10.50",
              "eval_cost": "2.00",
              "prefix_cost": "12.50",
              "data_read_per_join": "3K"
            },
            "used_columns": [
              "col1",
              "col2",
              "maxCreatedAt"
            ],
            "attached_condition": "(`sub`.`maxCreatedAt` is not null)",
            "materialized_from_subquery": {
              "using_temporary_table": true,
              "dependent": false,
              "cacheable": true,
              "query_block": {
                "select_id": 2,
                "cost_info": {
                  "query_cost": "10.27"
                },
                "ordering_operation": {
                  "using_filesort": true,
                  "grouping_operation": {
                    "using_temporary_table": true,
                    "using_filesort": false,
                    "table": {
                      "table_name": "indexTable",
                      "access_type": "ref",
                      "possible_keys": [
                        "PRIMARY",
                        "createdAt",
                        "id_userId_col1_col2_createdAt",
                        "col1_col2_createdAt"
                      ],
                      "key": "PRIMARY",
                      "used_key_parts": [
                        "id",
                        "userId"
                      ],
                      "key_length": "8",
                      "ref": [
                        "const",
                        "const"
                      ],
                      "rows_examined_per_scan": 46,
                      "rows_produced_per_join": 46,
                      "filtered": "100.00",
                      "cost_info": {
                        "read_cost": "1.07",
                        "eval_cost": "9.20",
                        "prefix_cost": "10.27",
                        "data_read_per_join": "16K"
                      },
                      "used_columns": [
                        "id",
                        "userId",
                        "createdAt",
                        "col1",
                        "col2",
                        "col3"
                      ],
                      "attached_condition": "((`MyDB`.`indexTable`.`id` <=> 53) and (`MyDB`.`indexTable`.`userId` <=> 549814))"
                    }
                  }
                }
              }
            }
          }
        },
        {
          "table": {
            "table_name": "t1",
            "access_type": "ref",
            "possible_keys": [
              "PRIMARY",
              "createdAt",
              "id_userId_col1_col2_createdAt",
              "col1_col2_createdAt"
            ],
            "key": "id_userId_col1_col2_createdAt",
            "used_key_parts": [
              "id",
              "userId",
              "col1",
              "col2",
              "createdAt"
            ],
            "key_length": "339",
            "ref": [
              "const",
              "const",
              "sub.col1",
              "sub.col2",
              "sub.maxCreatedAt"
            ],
            "rows_examined_per_scan": 1,
            "rows_produced_per_join": 10,
            "filtered": "100.00",
            "cost_info": {
              "read_cost": "10.00",
              "eval_cost": "2.00",
              "prefix_cost": "24.50",
              "data_read_per_join": "3K"
            },
            "used_columns": [
              "id",
              "userId",
              "createdAt",
              "updatedAt",
              "col1",
              "col2",
              "col3",
              "metadata",
            ]
          }
        }
      ]
    }
  }
}
</code>```

This query finds the most recent record in the grouping of col1 and col2, orders by createdAt, and limits the entries to 10.

答:
The "derived" table (subquery) needs this composite index:

```<code>INDEX(id, userid,  -- in either order
      col1, col2,  -- in this order
      createdAt)   -- to make it "covering"
</code>```

With that index, is probably will not do a full table scan.  However, it will involve a filesort.  This is because the ORDER BY is not the same as the GROUP BY and it is an aggregate.

t1 needs

```<code>INDEX(col1, col2,  -- in either order
      createdAt)
</code>```

sub,maxCreatedAt -- typo??

ORDER BY t1.createdAt -- another necessary filesort.

Do not beware of filesorts.  Especially when there are only 10 rows (as in the second case).

Without seeing SHOW CREATE TABLE, I cannot say whether the "filesort" and the "temporary table" touched the disk at all, or was done in RAM.

FORCE INDEX is almost always a bad idea -- even if it helps today, it may hurt tomorrow.

The Optimizer will deliberately (and rightly) use a table scan if too much of the table needs to be looked at -- it is faster than bouncing between the index and the data.

Body:
I am designing a new database and have noticed my queries are not scaling as well as they should be. When my aggregations involve hundreds of records I am seeing significant increases in response times. I am wondering if my query is deeply flawed or if I am just not using the right index.

I have done a lot of tweaking to my query but have not come up with a way to eliminate doing a full table scan and instead use an index. When I use a tool similar to EXPLAIN on my query I see the following:

Full table scans are generally inefficient, avoid using them.

Your query uses MySQL's 'filesort' operation. This tends to slow down queries.

Your query uses MySQL's temporary tables. This can require extra I/O and tends to slow down queries.

Table:

CREATE TABLE `indexTable` (
  `id` int(10) unsigned NOT NULL,
  `userId` int(10) unsigned NOT NULL,
  `col1` varbinary(320) NOT NULL,
  `col2` tinyint(3) unsigned NOT NULL,
  `col3` tinyint(3) unsigned NOT NULL,
  `createdAt` bigint(20) unsigned NOT NULL,
  `updatedAt` bigint(20) unsigned NOT NULL,
  `metadata` json NOT NULL,
  PRIMARY KEY (`id`,`userId`,`col1`,`col2`,`col3`),
  KEY `createdAt` (`createdAt`),
  KEY `id_userId_col1_col2_createdAt` (`id`,`userId`,`col1`,`col2`,`createdAt`),
  KEY `col1_col2_createdAt` (`col1`,`col2`,`createdAt`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=COMPRESSED KEY_BLOCK_SIZE=8

Query:

SELECT t1.id, t1.userId, t1.col1, t1.col2, t1.col3, t1.metadata
FROM indexTable as t1
INNER JOIN(
    SELECT col1, col2, MAX(createdAt) AS maxCreatedAt
    FROM indexTable
    WHERE id = ? AND userId = ?
    GROUP BY col1, col2
    ORDER BY maxCreatedAt
    LIMIT 10 OFFSET 0) AS sub
ON t1.col1 = sub.col1
AND t1.col2 = sub.col2
AND t1.createdAt = sub.maxCreatedAt
WHERE t1.id = ? AND t1.userId = ?
ORDER BY t1.createdAt;

PK: id, userId, col1, col2, col3
Index: createdAt

Explain:

{
  "query_block": {
    "select_id": 1,
    "cost_info": {
      "query_cost": "34.50"
    },
    "ordering_operation": {
      "using_temporary_table": true,
      "using_filesort": true,
      "cost_info": {
        "sort_cost": "10.00"
      },
      "nested_loop": [
        {
          "table": {
            "table_name": "sub",
            "access_type": "ALL",
            "rows_examined_per_scan": 10,
            "rows_produced_per_join": 10,
            "filtered": "100.00",
            "cost_info": {
              "read_cost": "10.50",
              "eval_cost": "2.00",
              "prefix_cost": "12.50",
              "data_read_per_join": "3K"
            },
            "used_columns": [
              "col1",
              "col2",
              "maxCreatedAt"
            ],
            "attached_condition": "(`sub`.`maxCreatedAt` is not null)",
            "materialized_from_subquery": {
              "using_temporary_table": true,
              "dependent": false,
              "cacheable": true,
              "query_block": {
                "select_id": 2,
                "cost_info": {
                  "query_cost": "10.27"
                },
                "ordering_operation": {
                  "using_filesort": true,
                  "grouping_operation": {
                    "using_temporary_table": true,
                    "using_filesort": false,
                    "table": {
                      "table_name": "indexTable",
                      "access_type": "ref",
                      "possible_keys": [
                        "PRIMARY",
                        "createdAt",
                        "id_userId_col1_col2_createdAt",
                        "col1_col2_createdAt"
                      ],
                      "key": "PRIMARY",
                      "used_key_parts": [
                        "id",
                        "userId"
                      ],
                      "key_length": "8",
                      "ref": [
                        "const",
                        "const"
                      ],
                      "rows_examined_per_scan": 46,
                      "rows_produced_per_join": 46,
                      "filtered": "100.00",
                      "cost_info": {
                        "read_cost": "1.07",
                        "eval_cost": "9.20",
                        "prefix_cost": "10.27",
                        "data_read_per_join": "16K"
                      },
                      "used_columns": [
                        "id",
                        "userId",
                        "createdAt",
                        "col1",
                        "col2",
                        "col3"
                      ],
                      "attached_condition": "((`MyDB`.`indexTable`.`id` <=> 53) and (`MyDB`.`indexTable`.`userId` <=> 549814))"
                    }
                  }
                }
              }
            }
          }
        },
        {
          "table": {
            "table_name": "t1",
            "access_type": "ref",
            "possible_keys": [
              "PRIMARY",
              "createdAt",
              "id_userId_col1_col2_createdAt",
              "col1_col2_createdAt"
            ],
            "key": "id_userId_col1_col2_createdAt",
            "used_key_parts": [
              "id",
              "userId",
              "col1",
              "col2",
              "createdAt"
            ],
            "key_length": "339",
            "ref": [
              "const",
              "const",
              "sub.col1",
              "sub.col2",
              "sub.maxCreatedAt"
            ],
            "rows_examined_per_scan": 1,
            "rows_produced_per_join": 10,
            "filtered": "100.00",
            "cost_info": {
              "read_cost": "10.00",
              "eval_cost": "2.00",
              "prefix_cost": "24.50",
              "data_read_per_join": "3K"
            },
            "used_columns": [
              "id",
              "userId",
              "createdAt",
              "updatedAt",
              "col1",
              "col2",
              "col3",
              "metadata",
            ]
          }
        }
      ]
    }
  }
}

This query finds the most recent record in the grouping of col1 and col2, orders by createdAt, and limits the entries to 10.

Body:
The "derived" table (subquery) needs this composite index:

INDEX(id, userid,  -- in either order
      col1, col2,  -- in this order
      createdAt)   -- to make it "covering"

With that index, is probably will not do a full table scan.  However, it will involve a filesort.  This is because the ORDER BY is not the same as the GROUP BY and it is an aggregate.

t1 needs

INDEX(col1, col2,  -- in either order
      createdAt)

sub,maxCreatedAt -- typo??

ORDER BY t1.createdAt -- another necessary filesort.

Do not beware of filesorts.  Especially when there are only 10 rows (as in the second case).

Without seeing SHOW CREATE TABLE, I cannot say whether the "filesort" and the "temporary table" touched the disk at all, or was done in RAM.

FORCE INDEX is almost always a bad idea -- even if it helps today, it may hurt tomorrow.

The Optimizer will deliberately (and rightly) use a table scan if too much of the table needs to be looked at -- it is faster than bouncing between the index and the data.


来源: stackexchange

问:
React - How to resolve: "JSX expression must have parent and expression expected" error in vs code
I have a simple App.js file which is rendering fine in the browser but I am getting some problems or errors in the VS code editor.

I am getting these errors -

My App.js:

```<code>import React, { Component } from "react";
import css from "./App.less";
import DonutChart from "./DonutChart";
import TimeLineChart from "./TimeLineChart";
import DataTable from "./DataTable";
import SidebarSample from "./SidebarSample";

class App extends Component {
  constructor(props) {
    super(props);
  }
  render() {
    let panelLeftCss = css.panel;
    panelLeftCss += " " + css.leftPanel;

    let panelRightCss = css.panel;
    panelRightCss += " " + css.rightPanel;
    return (
        <div>
          <div className="header">
            <div>
              <h1>Welcome Admin, My Dashboard</h1>
            </div>
          </div>
          <div>
            <SidebarSample />
          </div>

          <div className={css.main}>
            <div className={panelLeftCss}>
              <div className={css.panelHeader}>Donut Chart</div>
              <div className={css.panelBody}>
                <div>
                  <DonutChart />
                </div>
              </div>
            </div>

            <div className={panelRightCss}>
              <div className={css.panelHeader}>Line Chart</div>
              <div className={css.panelBody}>
                <div>
                  <TimeLineChart />
                </div>
              </div>
            </div>
          </div>

          <div>
            <div className={css.panelHeader}>Data Table</div>
            <div>
              <DataTable />
            </div>
          </div>
        </div>
    );
  }
}

export default App;
</code>```

I have tried to add a <React.Fragment> also but it's not resolving the errors in the VS code editor.

Is there any tool that I can use which solves this automatically, like prettier etc?

Please guide me.

答:
Check your file extension its .ts
It must be .tsx(if you're using TypeScript)
Same for App.js change it to App.jsx (if you're using JavaScript)
then,

try this,
all your code must be in single parent tag, like i did inside

as when render method returns only single parent, so you must careful while writing elements having only one parent or you wrap your code inside parent

```<code>import React, { Component } from "react";
import css from "./App.less";
import DonutChart from "./DonutChart";
import TimeLineChart from "./TimeLineChart";
import DataTable from "./DataTable";
import SidebarSample from "./SidebarSample";

class App extends Component {
  constructor(props) {
    super(props);
  }
  render() {
    let panelLeftCss = css.panel;
    panelLeftCss += " " + css.leftPanel;

    let panelRightCss = css.panel;
    panelRightCss += " " + css.rightPanel;
    return (
    <div>
    <div className="header">
        <div>
            <h1>Welcome Admin, My Dashboard</h1>
        </div>
    </div>
    <div>
        <SidebarSample />
    </div>

    <div className={css.main}>
        <div className={panelLeftCss}>
            <div className={css.panelHeader}>Donut Chart</div>
            <div className={css.panelBody}>
                <div>
                    <DonutChart />
                </div>
            </div>
        </div>

        <div className={panelRightCss}>
            <div className={css.panelHeader}>Line Chart</div>
            <div className={css.panelBody}>
                <div>
                    <TimeLineChart />
                </div>
            </div>
        </div>

        <div>
            <div className={css.panelHeader}>Data Table</div>
            <div>
                <DataTable />
            </div>
        </div>
    </div>
    </div>
    );
  }
}

export default App;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a simple App.js file which is rendering fine in the browser but I am getting some problems or errors in the VS code editor.

I am getting these errors -

My App.js:

import React, { Component } from "react";
import css from "./App.less";
import DonutChart from "./DonutChart";
import TimeLineChart from "./TimeLineChart";
import DataTable from "./DataTable";
import SidebarSample from "./SidebarSample";

class App extends Component {
  constructor(props) {
    super(props);
  }
  render() {
    let panelLeftCss = css.panel;
    panelLeftCss += " " + css.leftPanel;

    let panelRightCss = css.panel;
    panelRightCss += " " + css.rightPanel;
    return (

Welcome Admin, My Dashboard

            <SidebarSample />

Donut Chart

                  <DonutChart />

Line Chart

                  <TimeLineChart />

Data Table

              <DataTable />

    );
  }
}

export default App;

I have tried to add a <React.Fragment> also but it's not resolving the errors in the VS code editor.

Is there any tool that I can use which solves this automatically, like prettier etc?

Please guide me.

Body:
Check your file extension its .ts
It must be .tsx(if you're using TypeScript)
Same for App.js change it to App.jsx (if you're using JavaScript)
then,

try this,
all your code must be in single parent tag, like i did inside <div>
as when render method returns only single parent, so you must careful while writing elements having only one parent or you wrap your code inside parent <div>

import React, { Component } from "react";
import css from "./App.less";
import DonutChart from "./DonutChart";
import TimeLineChart from "./TimeLineChart";
import DataTable from "./DataTable";
import SidebarSample from "./SidebarSample";

class App extends Component {
  constructor(props) {
    super(props);
  }
  render() {
    let panelLeftCss = css.panel;
    panelLeftCss += " " + css.leftPanel;

    let panelRightCss = css.panel;
    panelRightCss += " " + css.rightPanel;
    return (
    <div>
    <div className="header">
        <div>
            <h1>Welcome Admin, My Dashboard</h1>
        </div>
    </div>
    <div>
        <SidebarSample />
    </div>

    <div className={css.main}>
        <div className={panelLeftCss}>
            <div className={css.panelHeader}>Donut Chart</div>
            <div className={css.panelBody}>
                <div>
                    <DonutChart />
                </div>
            </div>
        </div>

        <div className={panelRightCss}>
            <div className={css.panelHeader}>Line Chart</div>
            <div className={css.panelBody}>
                <div>
                    <TimeLineChart />
                </div>
            </div>
        </div>

        <div>
            <div className={css.panelHeader}>Data Table</div>
            <div>
                <DataTable />
            </div>
        </div>
    </div>
    </div>
    );
  }
}

export default App;


问:
How to find start(min) and end(max) date in xml file?
I have an XML file. I should find for same field2 start(min) date and End(max) date from field3. Maybe xsl have some function to find it.Because I try do it trying to find min month and min day and max month, max day.
XML:

```<code><document>
    <line id="0">
        <field id="2">X111</field>
        <field id="3">2011-03-31</field>
    </line>
    <line id="1">
        <field id="2">X111</field>
        <field id="3">2011-04-04</field>
    </line>
    <line id="2">
        <field id="2">X111</field>
        <field id="3">2011-04-02</field>
    </line>
    <line id="3">
        <field id="2">X222</field>
        <field id="3">2011-04-04</field>
    </line>
    <line id="4">
        <field id="2">X222</field>
        <field id="3">2011-04-01</field>
    </line>
    <line id="4">
        <field id="2">X333</field>
        <field id="3">2011-04-01</field>
    </line>
</document>
</code>```

Output:

```<code><document>
<Message>
    <ID>X111</ID>
    <dateStart>2011-03-31</dateStart>
    <dateEnd>2011-04-04</dateEnd>
</Message>
<Message>
    <ID>X222</ID>
    <dateStart>2011-04-01</dateStart>
    <dateEnd>2011-04-04</dateEnd>
</Message>
<Message>
    <ID>X333</ID>
    <dateStart>2011-04-01</dateStart>
    <dateEnd>2011-04-01</dateEnd>
</Message>
</document>
</code>```

Please help to solve it. I'm working with stylesheet version="1.0".

答:
This transformation shows how to find the wanted minimum and maximum:

```<code><xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="/*">
     <xsl:apply-templates select="line">
       <xsl:sort select="field[@id=3]"/>
     </xsl:apply-templates>
 </xsl:template>

 <xsl:template match="line">
  <xsl:if test="position()=1">
   Earliest:
   <xsl:copy-of select="."/>
  </xsl:if>
  <xsl:if test="position()=last()">
   Latest:
   <xsl:copy-of select="."/>
  </xsl:if>
 </xsl:template>
</xsl:stylesheet>
</code>```

when applied on the provided XML document:

```<code><document>
    <line id="0">
        <field id="2">X111</field>
        <field id="3">2011-03-31</field>
    </line>
    <line id="1">
        <field id="2">X111</field>
        <field id="3">2011-04-04</field>
    </line>
    <line id="2">
        <field id="2">X111</field>
        <field id="3">2011-04-02</field>
    </line>
    <line id="3">
        <field id="2">X222</field>
        <field id="3">2011-04-04</field>
    </line>
    <line id="4">
        <field id="2">X222</field>
        <field id="3">2011-04-01</field>
    </line>
    <line id="4">
        <field id="2">X333</field>
        <field id="3">2011-04-01</field>
    </line>
</document>
</code>```

produces:

```<code>   Earliest:
   <line id="0">
   <field id="2">X111</field>
   <field id="3">2011-03-31</field>
</line>
   Latest:
   <line id="3">
   <field id="2">X222</field>
   <field id="3">2011-04-04</field>
</line>
</code>```

Explanation:

Choosing the first and last element from the sorted node-list. The dates are in a "good" format, so they are sorted just as strings.

ContentLicense: CC BY-SA 3.0

Body:
I have an XML file. I should find for same field2 start(min) date and End(max) date from field3. Maybe xsl have some function to find it.Because I try do it trying to find min month and min day and max month, max day.
XML:

<document>
    <line id="0">
        <field id="2">X111</field>
        <field id="3">2011-03-31</field>
    </line>
    <line id="1">
        <field id="2">X111</field>
        <field id="3">2011-04-04</field>
    </line>
    <line id="2">
        <field id="2">X111</field>
        <field id="3">2011-04-02</field>
    </line>
    <line id="3">
        <field id="2">X222</field>
        <field id="3">2011-04-04</field>
    </line>
    <line id="4">
        <field id="2">X222</field>
        <field id="3">2011-04-01</field>
    </line>
    <line id="4">
        <field id="2">X333</field>
        <field id="3">2011-04-01</field>
    </line>
</document>

Output:

<document>
<Message>
    <ID>X111</ID>
    <dateStart>2011-03-31</dateStart>
    <dateEnd>2011-04-04</dateEnd>
</Message>
<Message>
    <ID>X222</ID>
    <dateStart>2011-04-01</dateStart>
    <dateEnd>2011-04-04</dateEnd>
</Message>
<Message>
    <ID>X333</ID>
    <dateStart>2011-04-01</dateStart>
    <dateEnd>2011-04-01</dateEnd>
</Message>
</document>

Please help to solve it. I'm working with stylesheet version="1.0".

Body:
This transformation shows how to find the wanted minimum and maximum:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="/*">
     <xsl:apply-templates select="line">
       <xsl:sort select="field[@id=3]"/>
     </xsl:apply-templates>
 </xsl:template>

 <xsl:template match="line">
  <xsl:if test="position()=1">
   Earliest:
   <xsl:copy-of select="."/>
  </xsl:if>
  <xsl:if test="position()=last()">
   Latest:
   <xsl:copy-of select="."/>
  </xsl:if>
 </xsl:template>
</xsl:stylesheet>

when applied on the provided XML document:

<document>
    <line id="0">
        <field id="2">X111</field>
        <field id="3">2011-03-31</field>
    </line>
    <line id="1">
        <field id="2">X111</field>
        <field id="3">2011-04-04</field>
    </line>
    <line id="2">
        <field id="2">X111</field>
        <field id="3">2011-04-02</field>
    </line>
    <line id="3">
        <field id="2">X222</field>
        <field id="3">2011-04-04</field>
    </line>
    <line id="4">
        <field id="2">X222</field>
        <field id="3">2011-04-01</field>
    </line>
    <line id="4">
        <field id="2">X333</field>
        <field id="3">2011-04-01</field>
    </line>
</document>

produces:

   Earliest:
   <line id="0">
   <field id="2">X111</field>
   <field id="3">2011-03-31</field>
</line>
   Latest:
   <line id="3">
   <field id="2">X222</field>
   <field id="3">2011-04-04</field>
</line>

Explanation:

Choosing the first and last element from the sorted node-list. The dates are in a "good" format, so they are sorted just as strings.


问:
BULK API2.0 of Salesforce does not update the records when uploading via CSV to the api
I am new to Salesforce. I was trying to integrate bulk api 2.0 to one of our internal php application. I was able to upload the csv file to Sales force and process it. But it returns records updated as 0 every time. There is no failures or nothing in the debug log. Can somebody advise what I am doing wrong here?

I hav tried calling the api, passing the same data in the csv as string and it gets updated successfully. Only when I upload the csv itself have problem.

Here is my code:

```<code>//code for creating the job id

$url = "$instance_url/services/data/v42.0/jobs/ingest";
    $content = json_encode(array("object" => 'Account', "externalIdFieldName" => "Id","contentType"=>'CSV',"operation" => 'update',"lineEnding" => "LF"));

    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_HTTPHEADER,
            array("Authorization: OAuth $access_token",
                    "Content-type: application/json; charset=UTF-8",
                    "Accept: text/csv"
            ));
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");

            curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
            $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

//code for uploading the csv for bulk update

     $url = "$instance_url/services/data/v42.0/jobs/ingest/7509D0000008eSuQAI/batches";

    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_HTTPHEADER,
            array("Authorization: OAuth $access_token",
                    "Content-type: text/csv",
                    "Accept: application/json"

            ));

    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");

    $file = "test-3.csv";

curl_setopt($curl, CURLOPT_POSTFIELDS, $file);
    curl_exec($curl);

    $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
</code>```

答: Looks like you don't close the job, SF "thinks" you might want to upload more files. Pass this self-training course: https://trailhead.salesforce.com/en/content/learn/modules/api_basics/api_basics_bulk, especially check out the update of state field?

Body:
I am new to Salesforce. I was trying to integrate bulk api 2.0 to one of our internal php application. I was able to upload the csv file to Sales force and process it. But it returns records updated as 0 every time. There is no failures or nothing in the debug log. Can somebody advise what I am doing wrong here?

I hav tried calling the api, passing the same data in the csv as string and it gets updated successfully. Only when I upload the csv itself have problem.

Here is my code:

//code for creating the job id

$url = "$instance_url/services/data/v42.0/jobs/ingest";
    $content = json_encode(array("object" => 'Account', "externalIdFieldName" => "Id","contentType"=>'CSV',"operation" => 'update',"lineEnding" => "LF"));

    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_HTTPHEADER,
            array("Authorization: OAuth $access_token",
                    "Content-type: application/json; charset=UTF-8",
                    "Accept: text/csv"
            ));
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");

            curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
            $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

//code for uploading the csv for bulk update

     $url = "$instance_url/services/data/v42.0/jobs/ingest/7509D0000008eSuQAI/batches";

    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_HTTPHEADER,
            array("Authorization: OAuth $access_token",
                    "Content-type: text/csv",
                    "Accept: application/json"

            ));

    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");

    $file = "test-3.csv";

curl_setopt($curl, CURLOPT_POSTFIELDS, $file);
    curl_exec($curl);

    $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);


问:
How to Make Custom HashPassword function in Feathersjs Authentication
I notice in feathersjs documentation

hashPassword This hook is used to hash plain text passwords before
  they are saved to the database. It uses the bcrypt algorithm by
  default but can be customized by passing your own options.hash
  function.

How do I apply this custom function in feathers js hook, hashPassword hook?

```<code>const { authenticate } = require('@feathersjs/authentication').hooks;

const {
  hashPassword, protect
} = require('@feathersjs/authentication-local').hooks;

module.exports = {
  before: {
    all: [],
    find: [ authenticate('jwt') ],
    get: [ authenticate('jwt') ],
    create: [ hashPassword() ],
    update: [ hashPassword(),  authenticate('jwt') ],
    patch: [ hashPassword(),  authenticate('jwt') ],
    remove: [ authenticate('jwt') ]
  },

  after: {
    all: [
      // Make sure the password field is never sent to the client
      // Always must be the last hook
      protect('password')
    ],
    find: [],
    get: [],
    create: [],
    update: [],
    patch: [],
    remove: []
  },

  error: {
    all: [],
    find: [],
    get: [],
    create: [],
    update: [],
    patch: [],
    remove: []
  }
};
</code>```

Does anyone have the answer?

Thanks

答:
Use the library of feathers itself. It's the easiest and most reliable one for now.</p>

```<code>const hash = require("@feathersjs/authentication-local/lib/utils/hash");

await hash(req.body.password).then(result => { // Do anything });
</code>```

Body:
I notice in feathersjs documentation

hashPassword This hook is used to hash plain text passwords before
  they are saved to the database. It uses the bcrypt algorithm by
  default but can be customized by passing your own options.hash
  function.

How do I apply this custom function in feathers js hook, hashPassword hook?

const { authenticate } = require('@feathersjs/authentication').hooks;

const {
  hashPassword, protect
} = require('@feathersjs/authentication-local').hooks;

module.exports = {
  before: {
    all: [],
    find: [ authenticate('jwt') ],
    get: [ authenticate('jwt') ],
    create: [ hashPassword() ],
    update: [ hashPassword(),  authenticate('jwt') ],
    patch: [ hashPassword(),  authenticate('jwt') ],
    remove: [ authenticate('jwt') ]
  },

  after: {
    all: [
      // Make sure the password field is never sent to the client
      // Always must be the last hook
      protect('password')
    ],
    find: [],
    get: [],
    create: [],
    update: [],
    patch: [],
    remove: []
  },

  error: {
    all: [],
    find: [],
    get: [],
    create: [],
    update: [],
    patch: [],
    remove: []
  }
};

Does anyone have the answer?

Thanks

Body:
Use the library of feathers itself. It's the easiest and most reliable one for now.

const hash = require("@feathersjs/authentication-local/lib/utils/hash");

await hash(req.body.password).then(result => { // Do anything });


问:
How To 'Read From .csv and Write To excel' In The Same Loop
I'm attempting to read from a .csv file and paste that data onto a 3270 terminal screen while writing the result of those attempts to a corresponding excel file that mirrors the .csv exactly

I've created the code that reads from the .csv file and pastes the value onto the 3270 screen.  But having difficultly referencing the exact line/row in excel to write the result

Here is my Loop:

```<code>  strLine = objFile.ReadLine
  Do Until objFile.AtEndOfStream
     arrFields = Split(strLine,",")
     subDoWork (strLine)
  strLine = strLine + 1
  Loop
</code>```

subDoWork then reads the .csv and pastes the data:

```<code>Sub subDoWork(strLine)

    ColumnA = arrFields(0)
    ColumnB = arrFields(1)

     subMoveCursor 1, 10
     subEnterData ColumnA

    If (funcReadScreen(12,27,1) <> "0") Then

      oExcelObject.Cells(3).Value = "Skipped SAF1"
      oExcelObject.DisplayAlerts = False
      ExcelWorkbook.Save
    End If
End Sub
</code>```

I'm creating the objects here and setting the variables when getting the extenal file:

```<code>Set oExcelObject = CreateObject("Excel.Application")
Set oFileObject  = CreateObject("Scripting.FileSystemObject")

 Sub subExternalFile
   rw = 2
   strFilter = ""
   strExternalFilePath = funcSolicitFile(strFilter)
   strExternalFilePath1 =
     "\\DAYFS02\mortvc$\_Scripts_Custom\DisasterScript_OutPut.xlsx"
       Set objFile  = oFileObject.OpenTextFile(strExternalFilePath)
       Set oExcelFile   = oFileObject.GetFile(strExternalFilePath1)
       strExcelFileName = oExcelFile.Name
       Set oExcelObject = GetObject("","Excel.Application")
       Set ExcelWorkbook =
       oExcelObject.Workbooks.Open(strExternalFilePath1)
       Set oExcelSheet   = ExcelWorkbook.Sheets(1)
   oExcelObject.Application.Visible = False
 End Sub
</code>```

I'm expecting to read from line 1 of the text file.  To read arrfields(0) and arrfields(1), only two columns, then paste that data onto the 3270 screen. And if the screen reads something specifically, to write to line 1 of the excel file in column C (3).  Then move to Line 2 and do the same, read the .csv file and then write to column (3) of the corresponding line number in the excel file.

When it tries to write to the excel file, I get the error that the object can't be found.  Although I am creating the object.  I also get a "Type mismatch" error when trying to count strLine so that I can move to the next line/row.

--------Edit 05/29/2019----------
I got that working.  I'm able to move from line to line within the .csv file and paste to the screen.  However, when writing to excel, it overwrites column C (row 2, the first row is headers) every time.  I can't get it to write into row 3 column C of excel based off the result in line 3 of the .csv.  I'm also not identifying the first line of the .csv as headers, in fact I removed the header from the .csv, but still have the header in the excel file (row 1). So technically, line 1 in the .csv is row 2 in excel.  I'm not sure if I need to place a Loop within my first Loop in order to count the rows in excel and ensure I'm writing to the correct row in excel based of the line in the .csv.  your assistance is appreciated.

答:
You are getting a type mismatch because you are trying to add an integer (1) to a string in this line.

```<code>strLine = strLine + 1
</code>```

If you want to keep track of which line you are working on you need to dim a new line counter variable.
You also need to read the line inside of the loop, or you'll end up with an endless loop.

Something like this:

```<code>dim i
i = 0
Do Until objFile.AtEndOfStream
   strLine = objFile.ReadLine
   arrFields = Split(strLine,",")
   subDoWork  strLine
   i = i + 1
Loop
</code>```

Body:
I'm attempting to read from a .csv file and paste that data onto a 3270 terminal screen while writing the result of those attempts to a corresponding excel file that mirrors the .csv exactly

I've created the code that reads from the .csv file and pastes the value onto the 3270 screen.  But having difficultly referencing the exact line/row in excel to write the result

Here is my Loop:

  strLine = objFile.ReadLine
  Do Until objFile.AtEndOfStream
     arrFields = Split(strLine,",")
     subDoWork (strLine)
  strLine = strLine + 1
  Loop

subDoWork then reads the .csv and pastes the data:

Sub subDoWork(strLine)

    ColumnA = arrFields(0)
    ColumnB = arrFields(1)

     subMoveCursor 1, 10
     subEnterData ColumnA

    If (funcReadScreen(12,27,1) <> "0") Then

      oExcelObject.Cells(3).Value = "Skipped SAF1"
      oExcelObject.DisplayAlerts = False
      ExcelWorkbook.Save
    End If
End Sub

I'm creating the objects here and setting the variables when getting the extenal file:

Set oExcelObject = CreateObject("Excel.Application")
Set oFileObject  = CreateObject("Scripting.FileSystemObject")

 Sub subExternalFile
   rw = 2
   strFilter = ""
   strExternalFilePath = funcSolicitFile(strFilter)
   strExternalFilePath1 =
     "\\DAYFS02\mortvc$\_Scripts_Custom\DisasterScript_OutPut.xlsx"
       Set objFile  = oFileObject.OpenTextFile(strExternalFilePath)
       Set oExcelFile   = oFileObject.GetFile(strExternalFilePath1)
       strExcelFileName = oExcelFile.Name
       Set oExcelObject = GetObject("","Excel.Application")
       Set ExcelWorkbook =
       oExcelObject.Workbooks.Open(strExternalFilePath1)
       Set oExcelSheet   = ExcelWorkbook.Sheets(1)
   oExcelObject.Application.Visible = False
 End Sub

I'm expecting to read from line 1 of the text file.  To read arrfields(0) and arrfields(1), only two columns, then paste that data onto the 3270 screen. And if the screen reads something specifically, to write to line 1 of the excel file in column C (3).  Then move to Line 2 and do the same, read the .csv file and then write to column (3) of the corresponding line number in the excel file.

When it tries to write to the excel file, I get the error that the object can't be found.  Although I am creating the object.  I also get a "Type mismatch" error when trying to count strLine so that I can move to the next line/row.

--------Edit 05/29/2019----------
I got that working.  I'm able to move from line to line within the .csv file and paste to the screen.  However, when writing to excel, it overwrites column C (row 2, the first row is headers) every time.  I can't get it to write into row 3 column C of excel based off the result in line 3 of the .csv.  I'm also not identifying the first line of the .csv as headers, in fact I removed the header from the .csv, but still have the header in the excel file (row 1). So technically, line 1 in the .csv is row 2 in excel.  I'm not sure if I need to place a Loop within my first Loop in order to count the rows in excel and ensure I'm writing to the correct row in excel based of the line in the .csv.  your assistance is appreciated.

Body:
You are getting a type mismatch because you are trying to add an integer (1) to a string in this line.

strLine = strLine + 1

If you want to keep track of which line you are working on you need to dim a new line counter variable.
You also need to read the line inside of the loop, or you'll end up with an endless loop.

Something like this:

dim i
i = 0
Do Until objFile.AtEndOfStream
   strLine = objFile.ReadLine
   arrFields = Split(strLine,",")
   subDoWork  strLine
   i = i + 1
Loop


问:
Google Maps JavaScript API RefererNotAllowedMapError
We're trying to develop an geoplacement app for one of our clients, and we want first to test it in out own domain.

We have signed for Google Maps JavaScript API, and we have a valid browser key and our domain, www.grupocamaleon.com, has been authorized to use that key.

But we can't make even the easiest example to run without error.

We have, in our domain and with our key, the following demo:

(1) http://www.grupocamaleon.com/boceto/aerial-simple.html

But it doesn't work, and Firebug console says:

"Google Maps API error: Google Maps API error: RefererNotAllowedMapError (link to Google documentation on RefererNotAllowedMapError) Your site URL to be authorized: (1)"

My credential page is missing the possibility of adding referrers to accept, so solutions involving adding referrers are not possible right now.

My credential Page:

Why do we get that error? How can we fix it?

答:
This is another sh1tty Google product with a terrible implemenation.

The problem I have found with this is that if you restrict an API key by IP address, it wont work... BUT far be it from Google to make this point clear... It wasn't until troubleshooting and researching I found:

API keys with an IP addresses restriction can only be used with web
  services that are intended for use from the server side (such as the
  Geocoding API and other Web Service APIs). Most of these web services
  have equivalent services within the Maps JavaScript API (for example,
  see the Geocoding Service). To use the Maps JavaScript API client side
  services, you will need to create a separate API key which can be
  secured with an HTTP referrers restriction (see Restricting an API
  key).

https://developers.google.com/maps/documentation/javascript/error-messages

FFS Google... Pretty important piece of information that would be good to clarify on setup...


问:
How to automateTalend Job2Docker jobs to Kubernetes
Can someone give me some guidance on best practice to bring multiple Talend jobs dynamically into Kubernetes?

I am using Talend Open Studio for Big Data

I have a listener server for Job2Docker

How do I change the scripts to automate a push to Docker Hub?

Is it possible to have a dynamic CronJob K8s type that can run jobs based on a configuration file.

答:
I ended up not using Job2Docker in favour of a simple docker process.

Build the Talend Standalone job.

Unzip the build into a folder called jobs.

Use the below Dockerfile example to build and push your docker image.

Dockerfile

```<code>FROM java
WORKDIR /talend
COPY ./jobs /talend
</code>```

Create a CronJob type for K8s

```<code>apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: etl-edw-cronjob
spec:
  schedule: "0 * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          restartPolicy: Never
          containers:
            - name: etl-edw-job
              image: dockerhubrepo/your-etl
              command: ["sh",  "./process_data_warehouse_0.1/process_data_warehouse/process_data_warehouse_run.sh"]
              env:
                - name: PGHOST
                  value: postgres-cluster-ip-service
                - name: PGPORT
                  value: "5432"
                - name: PGDATABASE
                  value: infohub
                - name: PGUSER
                  value: postgres
                - name: PGPASSWORD
                  valueFrom:
                    secretKeyRef:
                      name: pgpassword
                      key: PGPASSWORD
                - name: MONGOSERVER
                  value: mongo-service
                - name: MONGOPORT
                  value: "27017"
                - name: MONGODB
                  value: hearth
</code>```

Body:
I ended up not using Job2Docker in favour of a simple docker process.

Build the Talend Standalone job.

Unzip the build into a folder called jobs.

Use the below Dockerfile example to build and push your docker image.

Dockerfile

FROM java
WORKDIR /talend
COPY ./jobs /talend

Create a CronJob type for K8s

apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: etl-edw-cronjob
spec:
  schedule: "0 * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          restartPolicy: Never
          containers:
            - name: etl-edw-job
              image: dockerhubrepo/your-etl
              command: ["sh",  "./process_data_warehouse_0.1/process_data_warehouse/process_data_warehouse_run.sh"]
              env:
                - name: PGHOST
                  value: postgres-cluster-ip-service
                - name: PGPORT
                  value: "5432"
                - name: PGDATABASE
                  value: infohub
                - name: PGUSER
                  value: postgres
                - name: PGPASSWORD
                  valueFrom:
                    secretKeyRef:
                      name: pgpassword
                      key: PGPASSWORD
                - name: MONGOSERVER
                  value: mongo-service
                - name: MONGOPORT
                  value: "27017"
                - name: MONGODB
                  value: hearth


问:
What's the best way of parsing strings?
We've got a scenario that requires us to parse lots of e-mail (plain text), each e-mail 'type' is the result of a script being run against various platforms. Some are tab delimited, some are space delimited, some we simply don't know yet.

We'll need to support more 'formats' in the future too.

Do we go for a solution using:

Regex

Simply string searching (using string.IndexOf etc)

Lex/ Yacc

Other

The overall solution will be developed in C# 2.0 (hopefully 3.5)

答: You probably should have a pluggable system regardless of which type of string parsing you use. So, this system calls upon the right 'plugin' depending on the type of email to parse it.</p>

ContentLicense: CC BY-SA 2.5

Title: What's the best way of parsing strings?

LastEditorDisplayName: Torsten Marek

OwnerDisplayName: Vaibhav


问:
FileProvider.getUriForFile returns NullPointerException
I'm trying to write my first android app, which will involve taking a picture and doing stuff with it.

I've put together some code after looking at several tutorials online but am getting the following NullPointerException whenever the button is clicked:

```<code>10-03 14:48:00.284 26310-26310/org.broadinstitute.jsnap E/MainActivity: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.XmlResourceParser android.content.pm.ProviderInfo.loadXmlMetaData(android.content.pm.PackageManager, java.lang.String)' on a null object reference
10-03 14:48:00.293 26310-26310/org.broadinstitute.jsnap E/MYAPP: exception
                                                                 java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.XmlResourceParser android.content.pm.ProviderInfo.loadXmlMetaData(android.content.pm.PackageManager, java.lang.String)' on a null object reference
                                                                     at android.support.v4.content.FileProvider.parsePathStrategy(FileProvider.java:583)
                                                                     at android.support.v4.content.FileProvider.getPathStrategy(FileProvider.java:557)
                                                                     at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:399)
                                                                     at org.broadinstitute.jsnap.MainActivity.takePhoto(MainActivity.java:54)
                                                                     at org.broadinstitute.jsnap.MainActivity.access$000(MainActivity.java:24)
                                                                     at org.broadinstitute.jsnap.MainActivity$1.onClick(MainActivity.java:43)
                                                                     at android.view.View.performClick(View.java:6205)
                                                                     at android.widget.TextView.performClick(TextView.java:11103)
                                                                     at android.view.View$PerformClick.run(View.java:23653)
                                                                     at android.os.Handler.handleCallback(Handler.java:751)
                                                                     at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                     at android.os.Looper.loop(Looper.java:154)
                                                                     at android.app.ActivityThread.main(ActivityThread.java:6682)
                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
</code>```

I'm not quite sure how to resolve. Here's my relevant code:

manifest:

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

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera" android:required="true"/>
    <uses-feature android:name="android.hardware.camera.autofocus" />
    <uses-feature android:name="android.hardware.camera.flash" android:required="false"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        >
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths"></meta-data>
        </provider>
    </application>

</manifest>
</code>```

file_paths.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="jsnap_images" path="Android/data/org.broadinstitute.jsnap/files/Pictures" />
</paths>
</code>```

And MainActivity:

```<code>package org.broadinstitute.jsnap;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.util.jar.Manifest;

public class MainActivity extends Activity {
    private static String logtag = "MainActivity";
    private static int TAKE_PICTURE = 1;
    private static final String AUTHORITY = "org.broadinstitute.jsnap.provider";
    private static final String PHOTOS="photos";
    private static final String FILENAME="jsnap_test.jpeg";
    Uri imageURI;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button cameraButton = (Button)(findViewById(R.id.cam_button));
        cameraButton.setOnClickListener(cameraListener);

    }
    private View.OnClickListener cameraListener = new View.OnClickListener() {
        public void onClick(View v) {
            try {
                takePhoto(v);
            } catch (Exception e) {
                Log.e(logtag, e.toString());
            }
        }
    };
    private void takePhoto(View v){
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        File photo = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), FILENAME);
        imageURI=FileProvider.getUriForFile(this, AUTHORITY, photo);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageURI);
        // TAKE_PICTURE is a request code saying we want to use the rear-facing camera.
        startActivityForResult(intent, TAKE_PICTURE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);

        if(resultCode == Activity.RESULT_OK) {
            Uri selectedImage = imageURI;
            getContentResolver().notifyChange(selectedImage, null);

            ImageView imageView = (ImageView)findViewById(R.id.image_camera);
            ContentResolver cr = getContentResolver();
            Bitmap bitmap;

            try {
                bitmap = MediaStore.Images.Media.getBitmap(cr, selectedImage);
                imageView.setImageBitmap(bitmap);
                Toast.makeText(MainActivity.this, selectedImage.toString(), Toast.LENGTH_SHORT).show();
            } catch(Exception e) {
                Log.e(logtag, e.toString());
            }
        }
    }
}
</code>```

Any help is greatly appreciated.

答:
I know this is a pretty old question but this answer is for future viewers. So I've encountered a similar problem and after researching, I've found an alternative to this approach.

Your Intent here
for eg: To view your image from your path

```<code> val intent = Intent()
 intent.setAction(Intent.ACTION_VIEW)
 val file = File(currentUri)
 intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
 val contentURI = getContentUri(context!!, file.absolutePath)
 intent.setDataAndType(contentURI,"image/*")
 startActivity(intent)
</code>```

Main Function below

```<code>private fun getContentUri(context:Context, absPath:String):Uri? {
        val cursor = context.getContentResolver().query(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            arrayOf<String>(MediaStore.Images.Media._ID),
            MediaStore.Images.Media.DATA + "=? ",
            arrayOf<String>(absPath), null)
        if (cursor != null && cursor.moveToFirst())
        {
            val id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID))
            return Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, Integer.toString(id))
        }
        else if (!absPath.isEmpty())
        {
            val values = ContentValues()
            values.put(MediaStore.Images.Media.DATA, absPath)
            return context.getContentResolver().insert(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
        }
        else
        {
            return null
        }
    }
</code>```

Body:
I'm trying to write my first android app, which will involve taking a picture and doing stuff with it.

I've put together some code after looking at several tutorials online but am getting the following NullPointerException whenever the button is clicked:

10-03 14:48:00.284 26310-26310/org.broadinstitute.jsnap E/MainActivity: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.XmlResourceParser android.content.pm.ProviderInfo.loadXmlMetaData(android.content.pm.PackageManager, java.lang.String)' on a null object reference
10-03 14:48:00.293 26310-26310/org.broadinstitute.jsnap E/MYAPP: exception
                                                                 java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.XmlResourceParser android.content.pm.ProviderInfo.loadXmlMetaData(android.content.pm.PackageManager, java.lang.String)' on a null object reference
                                                                     at android.support.v4.content.FileProvider.parsePathStrategy(FileProvider.java:583)
                                                                     at android.support.v4.content.FileProvider.getPathStrategy(FileProvider.java:557)
                                                                     at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:399)
                                                                     at org.broadinstitute.jsnap.MainActivity.takePhoto(MainActivity.java:54)
                                                                     at org.broadinstitute.jsnap.MainActivity.access$000(MainActivity.java:24)
                                                                     at org.broadinstitute.jsnap.MainActivity$1.onClick(MainActivity.java:43)
                                                                     at android.view.View.performClick(View.java:6205)
                                                                     at android.widget.TextView.performClick(TextView.java:11103)
                                                                     at android.view.View$PerformClick.run(View.java:23653)
                                                                     at android.os.Handler.handleCallback(Handler.java:751)
                                                                     at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                     at android.os.Looper.loop(Looper.java:154)
                                                                     at android.app.ActivityThread.main(ActivityThread.java:6682)
                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)

I'm not quite sure how to resolve. Here's my relevant code:

manifest:

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

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera" android:required="true"/>
    <uses-feature android:name="android.hardware.camera.autofocus" />
    <uses-feature android:name="android.hardware.camera.flash" android:required="false"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        >
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths"></meta-data>
        </provider>
    </application>

</manifest>

file_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="jsnap_images" path="Android/data/org.broadinstitute.jsnap/files/Pictures" />
</paths>

And MainActivity:

package org.broadinstitute.jsnap;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.util.jar.Manifest;

public class MainActivity extends Activity {
    private static String logtag = "MainActivity";
    private static int TAKE_PICTURE = 1;
    private static final String AUTHORITY = "org.broadinstitute.jsnap.provider";
    private static final String PHOTOS="photos";
    private static final String FILENAME="jsnap_test.jpeg";
    Uri imageURI;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button cameraButton = (Button)(findViewById(R.id.cam_button));
        cameraButton.setOnClickListener(cameraListener);

    }
    private View.OnClickListener cameraListener = new View.OnClickListener() {
        public void onClick(View v) {
            try {
                takePhoto(v);
            } catch (Exception e) {
                Log.e(logtag, e.toString());
            }
        }
    };
    private void takePhoto(View v){
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        File photo = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), FILENAME);
        imageURI=FileProvider.getUriForFile(this, AUTHORITY, photo);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageURI);
        // TAKE_PICTURE is a request code saying we want to use the rear-facing camera.
        startActivityForResult(intent, TAKE_PICTURE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);

        if(resultCode == Activity.RESULT_OK) {
            Uri selectedImage = imageURI;
            getContentResolver().notifyChange(selectedImage, null);

            ImageView imageView = (ImageView)findViewById(R.id.image_camera);
            ContentResolver cr = getContentResolver();
            Bitmap bitmap;

            try {
                bitmap = MediaStore.Images.Media.getBitmap(cr, selectedImage);
                imageView.setImageBitmap(bitmap);
                Toast.makeText(MainActivity.this, selectedImage.toString(), Toast.LENGTH_SHORT).show();
            } catch(Exception e) {
                Log.e(logtag, e.toString());
            }
        }
    }
}

Any help is greatly appreciated.

Body:
I know this is a pretty old question but this answer is for future viewers. So I've encountered a similar problem and after researching, I've found an alternative to this approach.

Your Intent here
for eg: To view your image from your path

 val intent = Intent()
 intent.setAction(Intent.ACTION_VIEW)
 val file = File(currentUri)
 intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
 val contentURI = getContentUri(context!!, file.absolutePath)
 intent.setDataAndType(contentURI,"image/*")
 startActivity(intent)

Main Function below

private fun getContentUri(context:Context, absPath:String):Uri? {
        val cursor = context.getContentResolver().query(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            arrayOf<String>(MediaStore.Images.Media._ID),
            MediaStore.Images.Media.DATA + "=? ",
            arrayOf<String>(absPath), null)
        if (cursor != null && cursor.moveToFirst())
        {
            val id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID))
            return Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, Integer.toString(id))
        }
        else if (!absPath.isEmpty())
        {
            val values = ContentValues()
            values.put(MediaStore.Images.Media.DATA, absPath)
            return context.getContentResolver().insert(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
        }
        else
        {
            return null
        }
    }


答:
Prettier or any other code formatting tools won't help you if you do not enclose your div with tags properly.
You forgot your closing
 tag at the end of your code.
Also you have an extra
 tag near your <TimeLineChart> there.
Check the formatted codes here as below. It should work.
You just need to be more careful in placing the tags.

```<code><div>
    <div className="header">
        <div>
            <h1>Welcome Admin, My Dashboard</h1>
        </div>
    </div>
    <div>
        <SidebarSample />
    </div>

    <div className={css.main}>
        <div className={panelLeftCss}>
            <div className={css.panelHeader}>Donut Chart</div>
            <div className={css.panelBody}>
                <div>
                    <DonutChart />
                </div>
            </div>
        </div>

        <div className={panelRightCss}>
            <div className={css.panelHeader}>Line Chart</div>
            <div className={css.panelBody}>
                <div>
                    <TimeLineChart />
                </div>
            </div>
        </div>

        <div>
            <div className={css.panelHeader}>Data Table</div>
            <div>
                <DataTable />
            </div>
        </div>
    </div>
</div>

</code>```

Title: React - How to resolve: "JSX expression must have parent and expression expected" error in vs code

Body:
Prettier or any other code formatting tools won't help you if you do not enclose your div with tags properly.
You forgot your closing </div> tag at the end of your code.
Also you have an extra </div> tag near your <TimeLineChart> there.
Check the formatted codes here as below. It should work.
You just need to be more careful in placing the tags.

<div>
    <div className="header">
        <div>
            <h1>Welcome Admin, My Dashboard</h1>
        </div>
    </div>
    <div>
        <SidebarSample />
    </div>

    <div className={css.main}>
        <div className={panelLeftCss}>
            <div className={css.panelHeader}>Donut Chart</div>
            <div className={css.panelBody}>
                <div>
                    <DonutChart />
                </div>
            </div>
        </div>

        <div className={panelRightCss}>
            <div className={css.panelHeader}>Line Chart</div>
            <div className={css.panelBody}>
                <div>
                    <TimeLineChart />
                </div>
            </div>
        </div>

        <div>
            <div className={css.panelHeader}>Data Table</div>
            <div>
                <DataTable />
            </div>
        </div>
    </div>
</div>


问:
How to add a unique icon to each list item with JavaScript
I have a list on my website, and each list item has a unique class name. Now I would like to assign a certain font-awesome icon to each class. Here is my html:

```<code><ul>
    <li class="item-1"></li>
    <li class="item-2"></li>
    <li class="item-3"></li>
    <li class="item-4"></li>
</ul>
</code>```

What I would like to do is using javascript, write some code to assign a font awesome icon to each unique class, so that it would end up looking like this:

```<code><ul>
    <i class="far fa-route"></i><li class="item-1"></li>
    <i class="far fa-map"></i><li class="item-2"></li>
    <i class="far fa-clock"></i><li class="item-3"></li>
    <i class="far fa-calendar"></i><li class="item-4"></li>
</ul>
</code>```

So as you can see, I would like to give each unique class a different icon. How would I go about doing this? Also I am very new to javascript so please let me know if you need any more information.

答:
Create the array of font-awesome classes. Get all the lis and then you can use insertBefore on it.

const awesomeIcons = ["fa-route", "fa-map", "fa-clock", "fa-calendar"];

const ul = document.querySelector('ul');
const lis = ul.querySelectorAll('li');

const newlis = [...lis].forEach((li, idx) => {
  const i = document.createElement('i');
  i.className = "far " + awesomeIcons[idx];
  ul.insertBefore(i, li);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li class="item-1">Item 1</li>
  <li class="item-2">Item 2</li>
  <li class="item-3">Item 3</li>
  <li class="item-4">Item 4</li>
</ul></code>```

Body:
I have a list on my website, and each list item has a unique class name. Now I would like to assign a certain font-awesome icon to each class. Here is my html:

What I would like to do is using javascript, write some code to assign a font awesome icon to each unique class, so that it would end up looking like this:

So as you can see, I would like to give each unique class a different icon. How would I go about doing this? Also I am very new to javascript so please let me know if you need any more information.

Body:
Create the array of font-awesome classes. Get all the lis and then you can use insertBefore on it.

const awesomeIcons = ["fa-route", "fa-map", "fa-clock", "fa-calendar"];

const ul = document.querySelector('ul');
const lis = ul.querySelectorAll('li');

const newlis = [...lis].forEach((li, idx) => {
  const i = document.createElement('i');
  i.className = "far " + awesomeIcons[idx];
  ul.insertBefore(i, li);
});

<ul>
  <li class="item-1">Item 1</li>
  <li class="item-2">Item 2</li>
  <li class="item-3">Item 3</li>
  <li class="item-4">Item 4</li>
</ul>


问:
VBA - How to call SQL database connection from separate module
I have been digging on this but I couldn't find the solution related to it. I have a SQL database connection in a separate module (Module 5) that I wanted to call whenever I need to connect to my database from the other Module/form. This is for simplicity and single update so I don't need to go through every function to update the connection.

Database connection (Module5)

Function dbconnection()
Dim cnn As New ADODB.connection
Dim rst As New ADODB.Recordset

cnn.Open = "Driver={SQL Server};Server=HOLAP-
IST9985\CASETRACKER;Database=casetracker; Trusted_Connection=Yes"

cnn.Close
Set cnn = Nothing

End Function
```

<p>And this is where I need to call the connection (Module2) - sends query to the database and displays result to my list box.</p>

<pre class="lang-vb prettyprint-override"><code>Function po_maintenance()

Dim cnn As New ADODB.connection
Dim rst As New ADODB.Recordset
Set rst = New ADODB.Recordset

rst.Open "SELECT * FROM po_numberstbl ORDER BY [PO_Number];", cnn,
adOpenStatic
If rst.EOF = False Then
i = 0

With maintenance_frm.maintenance_list
.Clear
Do
    .AddItem
    .List(i, 0) = rst![po_number]
    .List(i, 1) = rst![purpose]
    .List(i, 2) = rst![Vendor]
    .List(i, 3) = rst![id]

    i = i + 1
    rst.MoveNext
Loop Until rst.EOF
End With
Else
End If

End Function
</code>```

答:
So here's what I have came up with to solve the connection problem..

dbconnection:

Public sqlt As String
Function dbconnection() As ADODB.connection
Dim cnn As New ADODB.connection
Dim rst As New ADODB.Recordset

sqlt = "Driver={SQL Server};Server=HOLAP-
IST9985\CASETRACKER;Database=storecons; Trusted_Connection=Yes"
End Function
```

<p>Calling dbconnection:</p>

<pre class="lang-vb prettyprint-override"><code>Function po_maintenance()

Dim cnn As New ADODB.connection
Dim rst As New ADODB.Recordset
Set rst = New ADODB.Recordset

Set cnn = Module5.dbconnection()
cnn.Open sqlt

rst.Open "SELECT * FROM po_numberstbl ORDER BY [PO_Number];", cnn,
adOpenStatic
If rst.EOF = False Then
i = 0

With maintenance_frm.maintenance_list
.Clear
Do
    .AddItem
    .List(i, 0) = rst![po_number]
    .List(i, 1) = rst![purpose]
    .List(i, 2) = rst![Vendor]
    .List(i, 3) = rst![id]

    i = i + 1
    rst.MoveNext
Loop Until rst.EOF
End With
Else
End If
End Function
</code>```

Body:
I have been digging on this but I couldn't find the solution related to it. I have a SQL database connection in a separate module (Module 5) that I wanted to call whenever I need to connect to my database from the other Module/form. This is for simplicity and single update so I don't need to go through every function to update the connection.

Database connection (Module5)

Function dbconnection()
Dim cnn As New ADODB.connection
Dim rst As New ADODB.Recordset

cnn.Open = "Driver={SQL Server};Server=HOLAP-
IST9985\CASETRACKER;Database=casetracker; Trusted_Connection=Yes"

cnn.Close
Set cnn = Nothing

End Function

And this is where I need to call the connection (Module2) - sends query to the database and displays result to my list box.

Function po_maintenance()

Dim cnn As New ADODB.connection
Dim rst As New ADODB.Recordset
Set rst = New ADODB.Recordset

rst.Open "SELECT * FROM po_numberstbl ORDER BY [PO_Number];", cnn,
adOpenStatic
If rst.EOF = False Then
i = 0

With maintenance_frm.maintenance_list
.Clear
Do
    .AddItem
    .List(i, 0) = rst![po_number]
    .List(i, 1) = rst![purpose]
    .List(i, 2) = rst![Vendor]
    .List(i, 3) = rst![id]

    i = i + 1
    rst.MoveNext
Loop Until rst.EOF
End With
Else
End If

End Function

Body:
So here's what I have came up with to solve the connection problem..

dbconnection:

Public sqlt As String
Function dbconnection() As ADODB.connection
Dim cnn As New ADODB.connection
Dim rst As New ADODB.Recordset

sqlt = "Driver={SQL Server};Server=HOLAP-
IST9985\CASETRACKER;Database=storecons; Trusted_Connection=Yes"
End Function

Calling dbconnection:

Function po_maintenance()

Dim cnn As New ADODB.connection
Dim rst As New ADODB.Recordset
Set rst = New ADODB.Recordset

Set cnn = Module5.dbconnection()
cnn.Open sqlt

rst.Open "SELECT * FROM po_numberstbl ORDER BY [PO_Number];", cnn,
adOpenStatic
If rst.EOF = False Then
i = 0

With maintenance_frm.maintenance_list
.Clear
Do
    .AddItem
    .List(i, 0) = rst![po_number]
    .List(i, 1) = rst![purpose]
    .List(i, 2) = rst![Vendor]
    .List(i, 3) = rst![id]

    i = i + 1
    rst.MoveNext
Loop Until rst.EOF
End With
Else
End If
End Function


问:
AudioRecord.StartRecording() is Throwing Java.Lang.IllegalException saying that Uninitialized AudioRecorder
I am trying to read audio as 16 bit integers in my android app. I have written this app using Xamarin.android . I am using AudioRecord low level Library for this because i need to read raw bytes from phones mic and not a high level operation .

At StartRecording() function there is an Exception from Java , saying that the Uninitialized AudioRecord.

```<code>AudioRecord au = new AudioRecord(AudioSource.Mic, 44100, ChannelIn.Mono, Android.Media.Encoding.Pcm16bit, buffer.Length);
au.StartRecording(); //<-- Here
                     //(Java.Lang.IllegalStateException: startRecording()
                     // called on an uninitialized AudioRecord.)
</code>```

I went throw some qns in stack overflow and i tried releasing any prior allocation in a try catch block . The problem still persists .

```<code>AudioRecord au = new AudioRecord(AudioSource.Mic, 44100, ChannelIn.Mono, Android.Media.Encoding.Pcm16bit, buffer.Length);
            try {
                au.StartRecording();
                au.Read(buffer, 0, buffer.Length);
            }
            catch (Java.Lang.IllegalStateException e ) {
                au.Release();
                au = new AudioRecord(AudioSource.Mic, 44100, ChannelIn.Mono, Android.Media.Encoding.Pcm16bit, buffer.Length);
                au.StartRecording();
                au.Read(buffer, 0, buffer.Length);
            }
</code>```

This is my compleate code in a separate code file .

```<code>using System;
using System.Text;
using System.Collections.Generic;
using Android.Media;
namespace core
{
    public static class RawAudioInput
    {
        public static List<short> Listen()
        {
            int bufferSizeInBytes = AudioRecord
            .GetMinBufferSize(44100, ChannelIn.Mono,
                    Android.Media.Encoding.Pcm16bit);
            byte[] buffer = new byte[bufferSizeInBytes];
            AudioRecord au = new AudioRecord(AudioSource.Mic, 44100, ChannelIn.Mono, Android.Media.Encoding.Pcm16bit, buffer.Length);
            try {
                au.StartRecording();
                au.Read(buffer, 0, buffer.Length);
            }
            catch (Java.Lang.IllegalStateException e ) {
                au.Release();
                au = new AudioRecord(AudioSource.Mic, 44100, ChannelIn.Mono, Android.Media.Encoding.Pcm16bit, buffer.Length);
                au.StartRecording();//<-- (Java.Lang.IllegalStateException: startRecording() called on an uninitialized AudioRecord.)
                au.Read(buffer, 0, buffer.Length);
            }
            au.Stop();
            List<short> result = new List<short>();
            for (int i = 0; i < buffer.Length; i += 2)
            {
                result.Add(BitConverter.ToInt16(buffer, i));
            }
            au.Release();
            return result;
        }
    }

}
</code>```

I dont understand where i am doing things wrong .Please help me solve this issue.

Edit
I managed to get the full stack trace of the exception from System.Diagnostics.Debug.WriteLine()
Here it is :

```<code>[0:] Java.Lang.IllegalStateException: startRecording() called on an uninitialized AudioRecord.
  at Java.Interop.JniEnvironment+InstanceMethods.CallVoidMethod (Java.Interop.JniObjectReference instance, Java.Interop.JniMethodInfo method, Java.Interop.JniArgumentValue* args) [0x00069] in <286213b9e14c442ba8d8d94cc9dbec8e>:0
  at Java.Interop.JniPeerMembers+JniInstanceMethods.InvokeVirtualVoidMethod (System.String encodedMember, Java.Interop.IJavaPeerable self, Java.Interop.JniArgumentValue* parameters) [0x0002a] in <286213b9e14c442ba8d8d94cc9dbec8e>:0
  at Android.Media.AudioRecord.StartRecording () [0x0000a] in <b781ed64f1d743e7881ac038e0fbdf85>:0
  at core.RawAudioInput.Listen () [0x00028] in C:\Users\aditya_nadig\source\repos\RawAudio\RawAudio\RawAudioInput.cs:17
  at RawAudio.MainActivity.OnRecordButtonClick (System.Object sender, System.EventArgs e) [0x00004] in C:\Users\aditya_nadig\source\repos\RawAudio\RawAudio\MainActivity.cs:31
  --- End of managed Java.Lang.IllegalStateException stack trace ---
java.lang.IllegalStateException: startRecording() called on an uninitialized AudioRecord.
    at android.media.AudioRecord.startRecording(AudioRecord.java:1011)
    at mono.android.view.View_OnClickListenerImplementor.n_onClick(Native Method)
    at mono.android.view.View_OnClickListenerImplementor.onClick(View_OnClickListenerImplementor.java:30)
    at android.view.View.performClick(View.java:6993)
    at android.widget.TextView.performClick(TextView.java:12752)
    at android.view.View$PerformClick.run(View.java:26512)
    at android.os.Handler.handleCallback(Handler.java:790)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:7025)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:441)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
</code>```

答:
StartRecording should be called in a separate thread. You should use Async Task.it ,and achieve AudioManagerin your code, Here is simple demo, you could refer to it.
https://developer.xamarin.com/samples/monodroid/Example_WorkingWithAudio/

update

And do not forget to request these permission in AndroidManifest，

"android.permission.MODIFY_AUDIO_SETTINGS"
"android.permission.READ_EXTERNAL_STORAGE"
"android.permission.WRITE_EXTERNAL_STORAGE"

"android.permission.RECORD_AUDIO"

Body:
I am trying to read audio as 16 bit integers in my android app. I have written this app using Xamarin.android . I am using AudioRecord low level Library for this because i need to read raw bytes from phones mic and not a high level operation .

At StartRecording() function there is an Exception from Java , saying that the Uninitialized AudioRecord.

AudioRecord au = new AudioRecord(AudioSource.Mic, 44100, ChannelIn.Mono, Android.Media.Encoding.Pcm16bit, buffer.Length);
au.StartRecording(); //<-- Here
                     //(Java.Lang.IllegalStateException: startRecording()
                     // called on an uninitialized AudioRecord.)

I went throw some qns in stack overflow and i tried releasing any prior allocation in a try catch block . The problem still persists .

AudioRecord au = new AudioRecord(AudioSource.Mic, 44100, ChannelIn.Mono, Android.Media.Encoding.Pcm16bit, buffer.Length);
            try {
                au.StartRecording();
                au.Read(buffer, 0, buffer.Length);
            }
            catch (Java.Lang.IllegalStateException e ) {
                au.Release();
                au = new AudioRecord(AudioSource.Mic, 44100, ChannelIn.Mono, Android.Media.Encoding.Pcm16bit, buffer.Length);
                au.StartRecording();
                au.Read(buffer, 0, buffer.Length);
            }

This is my compleate code in a separate code file .

using System;
using System.Text;
using System.Collections.Generic;
using Android.Media;
namespace core
{
    public static class RawAudioInput
    {
        public static List<short> Listen()
        {
            int bufferSizeInBytes = AudioRecord
            .GetMinBufferSize(44100, ChannelIn.Mono,
                    Android.Media.Encoding.Pcm16bit);
            byte[] buffer = new byte[bufferSizeInBytes];
            AudioRecord au = new AudioRecord(AudioSource.Mic, 44100, ChannelIn.Mono, Android.Media.Encoding.Pcm16bit, buffer.Length);
            try {
                au.StartRecording();
                au.Read(buffer, 0, buffer.Length);
            }
            catch (Java.Lang.IllegalStateException e ) {
                au.Release();
                au = new AudioRecord(AudioSource.Mic, 44100, ChannelIn.Mono, Android.Media.Encoding.Pcm16bit, buffer.Length);
                au.StartRecording();//<-- (Java.Lang.IllegalStateException: startRecording() called on an uninitialized AudioRecord.)
                au.Read(buffer, 0, buffer.Length);
            }
            au.Stop();
            List<short> result = new List<short>();
            for (int i = 0; i < buffer.Length; i += 2)
            {
                result.Add(BitConverter.ToInt16(buffer, i));
            }
            au.Release();
            return result;
        }
    }

}

I dont understand where i am doing things wrong .Please help me solve this issue.

Edit
I managed to get the full stack trace of the exception from System.Diagnostics.Debug.WriteLine()
Here it is :

[0:] Java.Lang.IllegalStateException: startRecording() called on an uninitialized AudioRecord.
  at Java.Interop.JniEnvironment+InstanceMethods.CallVoidMethod (Java.Interop.JniObjectReference instance, Java.Interop.JniMethodInfo method, Java.Interop.JniArgumentValue* args) [0x00069] in <286213b9e14c442ba8d8d94cc9dbec8e>:0
  at Java.Interop.JniPeerMembers+JniInstanceMethods.InvokeVirtualVoidMethod (System.String encodedMember, Java.Interop.IJavaPeerable self, Java.Interop.JniArgumentValue* parameters) [0x0002a] in <286213b9e14c442ba8d8d94cc9dbec8e>:0
  at Android.Media.AudioRecord.StartRecording () [0x0000a] in <b781ed64f1d743e7881ac038e0fbdf85>:0
  at core.RawAudioInput.Listen () [0x00028] in C:\Users\aditya_nadig\source\repos\RawAudio\RawAudio\RawAudioInput.cs:17
  at RawAudio.MainActivity.OnRecordButtonClick (System.Object sender, System.EventArgs e) [0x00004] in C:\Users\aditya_nadig\source\repos\RawAudio\RawAudio\MainActivity.cs:31
  --- End of managed Java.Lang.IllegalStateException stack trace ---
java.lang.IllegalStateException: startRecording() called on an uninitialized AudioRecord.
    at android.media.AudioRecord.startRecording(AudioRecord.java:1011)
    at mono.android.view.View_OnClickListenerImplementor.n_onClick(Native Method)
    at mono.android.view.View_OnClickListenerImplementor.onClick(View_OnClickListenerImplementor.java:30)
    at android.view.View.performClick(View.java:6993)
    at android.widget.TextView.performClick(TextView.java:12752)
    at android.view.View$PerformClick.run(View.java:26512)
    at android.os.Handler.handleCallback(Handler.java:790)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:7025)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:441)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)


问:
jquery ui accordion - multiple accordions expand/collapse all - style issues
I'm attempting to create an accordion where I can expand/collapse all sections with a single click.  I also need the ability for the user to open and close the sections having 0-n sections open at a time.  Using several of the discussions here on stackoverflow and on jquery forums, here's the solution i've come up with:
I've implemented each section as it's own accordion, where each is set to collapsible = true.

```<code><html>
    <head>
        <title>Accordion Test</title>

        <script type="text/javascript" src="../scripts/jquery-1.4.2.min.js"></script>
        <script type="text/javascript" src="../scripts/jquery-ui-1.8.4.custom.min.js"></script>

        <link rel="stylesheet" href="../_templates/css/jquery-ui-1.8.6.custom.css"  type="text/css" />
        <link rel="stylesheet" href="../_templates/css/jquery.ui.accordion.css" type="text/css" />
    </head>

<body>
        <a onClick="expandAll()">Expand All</a>
        <br>
        <a onClick="collapseAll()">Collapse All</a>
            <div id="accordion1" class="accord">
            <h5><a href="#">section 1</a></h5>
            <div>
                    section 1 text
            </div>
            </div>

            <!-- orders section -->
            <div id="accordion2" class="accord">
            <h5><a href="#">section 2</a></h5>
            <div>
                    section 2 text
            </div>
            </div>

            <!--  section 3 -->
            <div id="accordion3" class="accord">
            <h5><a href="#">section 3</a></h5>
            <div>
                    section 3 text
            </div>
            </div>

            <!-- section 4 -->
            <div id="accordion4">
            <h5><a href="#">section 4</a></h5>
            <div>
                    section 4 text
            </div>
            </div>

</body>
</html>

<script type="text/javascript">

$(function() {
    $('#accordion1').accordion({
        header: 'h5',
        collapsible: true,
        autoHeight: false
    });
});
$(function() {
    $('#accordion2').accordion({
        header: 'h5',
        collapsible: true,
        autoHeight: false,
        active: false
    });
});
$(function() {
    $('#accordion3').accordion({
        header: 'h5',
        collapsible: true,
        autoHeight: false,
        active: false
    });
});
$(function() {
    $('#accordion4').accordion({
        header: 'h5',
        collapsible: true,
        autoHeight: false,
        active: false
    });
});

</script>

<script type="text/javascript">
$(document).ready(function() {

})

function expandAll() {
    alert("calling expandAll");
    $("#accordion1, #accordion2, #accordion3, #accordion4")
        .filter(":not(:has(.ui-state-active))")
        .accordion("activate", 0);
}

function collapseAll() {
    alert("calling collapseAll");
    $("#accordion1, #accordion2, #accordion3, #accordion4")
        .filter(":has(.ui-state-active)")
        .accordion("activate", -1);
}

</script>
</code>```

The problem I'm running into, is when I click the header of an open section, the section is collapsed as expected, but the header still have the "ui-state-focus" class, until I click elsewhere on the page.  So what I see in the ui is the header of section just closed has the same background color as my hover effect, until I click elsewhere, and it shifts to the 'default, not focused' color.

In addition, when I use the Collapse All link, all looks great in Firefox.  In IE, the last section header has the same hover-focus coloring.

Any suggestions?  Do I somehow need to force the accordion to lose focus when it is closed?  How would I accomplish that?

答:
Solution to implement accordion with all open panels. Panels are static and can't be closed.

Do not initialize accordion div with accordion widget!

```<code>$("#accordion").addClass("ui-accordion ui-widget ui-helper-reset")
  .find('h3')
  .addClass("current ui-accordion-header ui-helper-reset ui-state-active ui-corner-top")
  .prepend('<span class="ui-icon ui-icon-triangle-1-s"/>')
  .next().addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active");
</code>```

Body:
I'm attempting to create an accordion where I can expand/collapse all sections with a single click.  I also need the ability for the user to open and close the sections having 0-n sections open at a time.  Using several of the discussions here on stackoverflow and on jquery forums, here's the solution i've come up with:
I've implemented each section as it's own accordion, where each is set to collapsible = true.

        <title>Accordion Test</title>

        <link rel="stylesheet" href="../_templates/css/jquery-ui-1.8.6.custom.css"  type="text/css" />
        <link rel="stylesheet" href="../_templates/css/jquery.ui.accordion.css" type="text/css" />

        Expand All

        Collapse All

section 1

                    section 1 text

section 2

                    section 2 text

section 3

                    section 3 text

section 4

                    section 4 text

The problem I'm running into, is when I click the header of an open section, the section is collapsed as expected, but the header still have the "ui-state-focus" class, until I click elsewhere on the page.  So what I see in the ui is the header of section just closed has the same background color as my hover effect, until I click elsewhere, and it shifts to the 'default, not focused' color.

In addition, when I use the Collapse All link, all looks great in Firefox.  In IE, the last section header has the same hover-focus coloring.

Any suggestions?  Do I somehow need to force the accordion to lose focus when it is closed?  How would I accomplish that?

Body:
Solution to implement accordion with all open panels. Panels are static and can't be closed.

Do not initialize accordion div with accordion widget!

$("#accordion").addClass("ui-accordion ui-widget ui-helper-reset")
  .find('h3')
  .addClass("current ui-accordion-header ui-helper-reset ui-state-active ui-corner-top")
  .prepend('<span class="ui-icon ui-icon-triangle-1-s"/>')
  .next().addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active");


问:
How to replace with for loop statement by matching different files in shell/bash script
With my shell script i'm trying to match 2 different files and replace the occurencies in File1 with the lines of File2:

```<code>File1 occurency 1 <-- File2 row 1
File1 occurency 2 <-- File2 row 2
File1 occurency 3 <-- File2 row 3
...
</code>```

The number of rows in File 2 is equal to occurencies in File 1 because initialy they were taken from File 1

File1 - is a Json file

```<code>...
"@type" : "Review",
"@id":"https://google.com/social/profile/xxxxxxx.jpg"
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",

"@type" : "Review",
"@id":"https://google.com/social/profile/xxxxxxx.jpg"
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",
 ...
</code>```

File2 - is a formated "json like" file

```<code>"profilePhoto":"https://someurl.ltd/aaaa_90.jpg"
"profilePhoto":"https://someurl.ltd/bbbb_90.jpg"
"profilePhoto":"https://someurl.ltd/cccc_90.jpg"
 ....
</code>```

Actually the part of script that have to make this job looks like

```<code>IFS=$'\n'
set -f
for i in $(cat < File2.txt); do

sed -i "s|.*social.*|$i|g" File1.json

done
</code>```

This script replace all occurencies in File1 with the first line of File2, so on second loop there is no more matching to find.
output example

```<code>...
"@type" : "Review",
"profilePhoto":"https://someurl.ltd/cccc_90.jpg"
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",

"@type" : "Review",
"profilePhoto":"https://someurl.ltd/cccc_90.jpg"
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",
 ...
</code>```

I need instead the output like this

```<code>...
"@type" : "Review",
*"profilePhoto":"https://someurl.ltd/**aaaa**_90.jpg"*
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",

"@type" : "Review",
*"profilePhoto":"https://someurl.ltd/**bbbb**_90.jpg"*
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",
 ...
</code>```

Thank you in advance for any help.

答:
This might work for you (GNU sed):

```<code>sed -e '/xxxxxxx\.jpg/R file2' -e '//d' file1
</code>```

This replaces each line the contains xxxxxxx.jpg by a line from file2.

Body:
With my shell script i'm trying to match 2 different files and replace the occurencies in File1 with the lines of File2:

File1 occurency 1 <-- File2 row 1
File1 occurency 2 <-- File2 row 2
File1 occurency 3 <-- File2 row 3
...

The number of rows in File 2 is equal to occurencies in File 1 because initialy they were taken from File 1

File1 - is a Json file

...
"@type" : "Review",
"@id":"https://google.com/social/profile/xxxxxxx.jpg"
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",

"@type" : "Review",
"@id":"https://google.com/social/profile/xxxxxxx.jpg"
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",
 ...

File2 - is a formated "json like" file

"profilePhoto":"https://someurl.ltd/aaaa_90.jpg"
"profilePhoto":"https://someurl.ltd/bbbb_90.jpg"
"profilePhoto":"https://someurl.ltd/cccc_90.jpg"
 ....

Actually the part of script that have to make this job looks like

IFS=$'\n'
set -f
for i in $(cat < File2.txt); do

sed -i "s|.*social.*|$i|g" File1.json

done

This script replace all occurencies in File1 with the first line of File2, so on second loop there is no more matching to find.
output example

...
"@type" : "Review",
"profilePhoto":"https://someurl.ltd/cccc_90.jpg"
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",

"@type" : "Review",
"profilePhoto":"https://someurl.ltd/cccc_90.jpg"
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",
 ...

I need instead the output like this

...
"@type" : "Review",
*"profilePhoto":"https://someurl.ltd/**aaaa**_90.jpg"*
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",

"@type" : "Review",
*"profilePhoto":"https://someurl.ltd/**bbbb**_90.jpg"*
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",
 ...

Thank you in advance for any help.

Body:
This might work for you (GNU sed):

sed -e '/xxxxxxx\.jpg/R file2' -e '//d' file1

This replaces each line the contains xxxxxxx.jpg by a line from file2.


问:
Process finished with exit code 1 Spring Boot Intellij
I've received the message "Process finished with exit code 1" when I run my project. I have tried several solutions but no topic is the same error as mine. My project doesn't execute any line of code, just abort the process.

答:
Its very complicated because mostly it might happen due to missing of properties. In my case the below property not defined in application.properties which cause this issue and its clue less. Hope this will help you

Due to missing properties like server port or any other placeholder which is defined in any Bean or Component can cause this issue. verify all the properties and placeholders.

```<code>  @Value(value = "${resource.path.accountNumbers}")
            private Resource accountNumbers;
    application.properties--verify all properties/placeholders
    resource.path.accountNumbers=classpath:accountNumbers.properties
</code>```

Body:
Its very complicated because mostly it might happen due to missing of properties. In my case the below property not defined in application.properties which cause this issue and its clue less. Hope this will help you

Due to missing properties like server port or any other placeholder which is defined in any Bean or Component can cause this issue. verify all the properties and placeholders.

  @Value(value = "${resource.path.accountNumbers}")
            private Resource accountNumbers;
    application.properties--verify all properties/placeholders
    resource.path.accountNumbers=classpath:accountNumbers.properties