问:
"java.sql.SQLException: No database selected" with MySQL JDBC
Code:

```<code>Connection dbConnection;
public Connection getDbConnection() throws ClassNotFoundException, SQLException{
String connectionString = "jdbc:mysql://127.2.0.1:3306/?user=root?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&useSSL=false";
;
String url="?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
    Class.forName("com.mysql.jdbc.Driver");

    dbConnection = DriverManager.getConnection(connectionString, dbUser, dbPass);
    return dbConnection;

}
public void SingUpUser(String id,String login, String password) {
    String insert = "INSERT INTO"+Constant.USER_TABLE+"("+Constant.USERS_ID+","+Constant.USERS_LOGIN+","+Constant.USER_PASSWORD+")"+
"VALUES(?,?,?)";

    try {
        PreparedStatement prSt = getDbConnection().prepareStatement(insert);
        prSt.setString(1, id);
        prSt.setString(2, login);
        prSt.setString(3, password);
        prSt.executeUpdate();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
}
</code>```

Error:

```<code>java.sql.SQLException: No database selected
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:955)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1094)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1042)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1345)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:1027)
at minelaunch.Databases.SingUpUser(Databases.java:36)
at minelaunch.minelauncherv1$5.actionPerformed(minelauncherv1.java:182)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
</code>```

I expect to write to the database, but I get this error.

答:
From the stack trace:

java.sql.SQLException: No database selected

You have removed the database name from your connection string, so now MySQL does not know which database you want to work with. Edit your connection string again and  specify the actual name of the database you want to use.

Body:
Code:

Connection dbConnection;
public Connection getDbConnection() throws ClassNotFoundException, SQLException{
String connectionString = "jdbc:mysql://127.2.0.1:3306/?user=root?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&useSSL=false";
;
String url="?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
    Class.forName("com.mysql.jdbc.Driver");

    dbConnection = DriverManager.getConnection(connectionString, dbUser, dbPass);
    return dbConnection;

}
public void SingUpUser(String id,String login, String password) {
    String insert = "INSERT INTO"+Constant.USER_TABLE+"("+Constant.USERS_ID+","+Constant.USERS_LOGIN+","+Constant.USER_PASSWORD+")"+
"VALUES(?,?,?)";

    try {
        PreparedStatement prSt = getDbConnection().prepareStatement(insert);
        prSt.setString(1, id);
        prSt.setString(2, login);
        prSt.setString(3, password);
        prSt.executeUpdate();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
}

Error:

java.sql.SQLException: No database selected
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:955)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1094)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1042)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1345)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:1027)
at minelaunch.Databases.SingUpUser(Databases.java:36)
at minelaunch.minelauncherv1$5.actionPerformed(minelauncherv1.java:182)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

I expect to write to the database, but I get this error.


来源: stackexchange

问:
convert from Color to brush
How do I convert a Color to a Brush in C#?

答:
```<code>Brush brush = new SolidColorBrush(color);
</code>```

The other way around:

```<code>if (brush is SolidColorBrush colorBrush)
    Color color = colorBrush.Color;
</code>```

Or something like that.

Point being not all brushes are colors but you could turn all colors into a (SolidColor)Brush.

ContentLicense: CC BY-SA 3.0

Title: convert from Color to brush

Body:
Brush brush = new SolidColorBrush(color);

The other way around:

if (brush is SolidColorBrush colorBrush)
    Color color = colorBrush.Color;

Or something like that.

Point being not all brushes are colors but you could turn all colors into a (SolidColor)Brush.

ContentLicense: CC BY-SA 4.0


问:
Fastest/most computationally efficient way to create a pandas dataframe where columns are filled with random strings, for several million rows?
This is a followup to this question

How to create a pandas dataframe where columns are filled with random strings?

In which an solution is given to full pandas rows with random strings. However, the solution is not fast enough for me, as it takes many hours to create several million rows of data, which I need to create a minimal example for another problem involving memory error.

I have tried the following code

from random import randint
import string
import numpy as np
import pandas as pd
import random
draw = randint(200, 5500)
def id_generator(size=draw, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))

num_rows =10000
data = np.array([id_generator() for i in range(2*num_rows)]).reshape(-1,2)
dfAll = pd.DataFrame(data)

#original is 65
for i in range(300):
    print('step ', i)
    draw = randint(200, 5500)
    data = np.array([id_generator() for i in range(2*num_rows)]).reshape(-1,2)
    df = pd.DataFrame(data)
    dfAll = pd.concat([ df,  dfAll ])

```

I am making the dataframe using the append method with chunks otherwise there will be a memory error if I do it all at once.

I am using Google Collaboratory as my enviroment. My desired result is that it makes a 6 million row dataframe of random string within 1 hour. For this, I need a more computationally efficient method of populating a pandas dataframe with random strings.

答:
Use NumPy to generate the array of strings with a single call to np.random.choice,
instead of a list comprehension which calls id_generator 2*num_rows times (and calls random.choice 2*num_rows*size times):

```<code>import string
import numpy as np
import pandas as pd
from random import randint
import random

def make_random_str_array(size=10, num_rows=100, chars=string.ascii_uppercase + string.digits):
    return (np.random.choice(list(chars), num_rows*size)
            .view('|U{}'.format(size)))

def id_generator(size, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))

def orig(size, num_rows):
    data = np.array([id_generator(size=size) for i in range(2*num_rows)]).reshape(-1, 2)
    dfAll = pd.DataFrame(data)
    return dfAll

def alt(size, num_rows):
    data = make_random_str_array(size, num_rows=2*num_rows).reshape(-1, 2)
    dfAll = pd.DataFrame(data)
    return dfAll
</code>```

For size=1000 and num_rows=10000, alt is ~26x faster:

```<code>In [94]: %timeit orig(1000, 10000)
9.22 s ± 49.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [95]: %timeit alt(1000, 10000)
343 ms ± 2.85 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [97]: 9220/343
Out[98]: 26.88046647230321
</code>```

Note that calling pd.concat in a for-loop leads to quadratic copying.
It is much more efficient to collect the sub-DataFrames in a list, and then call pd.concat once after the loop has completed:

```<code>parts = []
for i in range(300):
    print('step ', i)
    size = random.randint(200, 5500)
    data = make_random_str_array(size, num_rows=2*num_rows).reshape(-1, 2)
    parts.append(pd.DataFrame(data))
dfAll = pd.concat(parts)
</code>```

Body:
This is a followup to this question

How to create a pandas dataframe where columns are filled with random strings?

In which an solution is given to full pandas rows with random strings. However, the solution is not fast enough for me, as it takes many hours to create several million rows of data, which I need to create a minimal example for another problem involving memory error.

I have tried the following code

from random import randint
import string
import numpy as np
import pandas as pd
import random
draw = randint(200, 5500)
def id_generator(size=draw, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))

num_rows =10000
data = np.array([id_generator() for i in range(2*num_rows)]).reshape(-1,2)
dfAll = pd.DataFrame(data)

#original is 65
for i in range(300):
    print('step ', i)
    draw = randint(200, 5500)
    data = np.array([id_generator() for i in range(2*num_rows)]).reshape(-1,2)
    df = pd.DataFrame(data)
    dfAll = pd.concat([ df,  dfAll ])

I am making the dataframe using the append method with chunks otherwise there will be a memory error if I do it all at once.

I am using Google Collaboratory as my enviroment. My desired result is that it makes a 6 million row dataframe of random string within 1 hour. For this, I need a more computationally efficient method of populating a pandas dataframe with random strings.

Body:
Use NumPy to generate the array of strings with a single call to np.random.choice,
instead of a list comprehension which calls id_generator 2*num_rows times (and calls random.choice 2*num_rows*size times):

import string
import numpy as np
import pandas as pd
from random import randint
import random

def make_random_str_array(size=10, num_rows=100, chars=string.ascii_uppercase + string.digits):
    return (np.random.choice(list(chars), num_rows*size)
            .view('|U{}'.format(size)))

def id_generator(size, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))

def orig(size, num_rows):
    data = np.array([id_generator(size=size) for i in range(2*num_rows)]).reshape(-1, 2)
    dfAll = pd.DataFrame(data)
    return dfAll

def alt(size, num_rows):
    data = make_random_str_array(size, num_rows=2*num_rows).reshape(-1, 2)
    dfAll = pd.DataFrame(data)
    return dfAll

For size=1000 and num_rows=10000, alt is ~26x faster:

In [94]: %timeit orig(1000, 10000)
9.22 s ± 49.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [95]: %timeit alt(1000, 10000)
343 ms ± 2.85 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [97]: 9220/343
Out[98]: 26.88046647230321

Note that calling pd.concat in a for-loop leads to quadratic copying.
It is much more efficient to collect the sub-DataFrames in a list, and then call pd.concat once after the loop has completed:

parts = []
for i in range(300):
    print('step ', i)
    size = random.randint(200, 5500)
    data = make_random_str_array(size, num_rows=2*num_rows).reshape(-1, 2)
    parts.append(pd.DataFrame(data))
dfAll = pd.concat(parts)


问:
Function uuid_generate_v4() does not exist postgres 11
I am trying to use node-pg-migrate and run migrations to create tables in my node project.
When I run migrations I get function uuid_generate_v4() does not exist.

I did check in my extensions and uuid-ossp is available.

```<code>extname  | extowner | extnamespace | extrelocatable | extversion | extconfig | extcondition
-----------+----------+--------------+----------------+------------+-----------+--------------
 plpgsql   |       10 |           11 | f              | 1.0        |           |
 uuid-ossp |    16384 |         2200 | t              | 1.1        |           |
(2 rows)

</code>```

I expect my migrations to run but it fails. I am using Postgres 11 on Mac.
Postgres installed from here - https://postgresapp.com/

答:
Unfortunately, I do not have much information about what your pg-migrate files look like, but you must specify the following:</p>

```<code>pgm.createExtension('uuid-ossp', { ifNotExists: true });
// and
pgm.createTable('my_table', {
    id: { type: 'uuid', primaryKey: true, default: new PgLiteral('gen_random_uuid()') },
    // ...

</code>```

Body:
I am trying to use node-pg-migrate and run migrations to create tables in my node project.
When I run migrations I get function uuid_generate_v4() does not exist.

I did check in my extensions and uuid-ossp is available.

extname  | extowner | extnamespace | extrelocatable | extversion | extconfig | extcondition
-----------+----------+--------------+----------------+------------+-----------+--------------
 plpgsql   |       10 |           11 | f              | 1.0        |           |
 uuid-ossp |    16384 |         2200 | t              | 1.1        |           |
(2 rows)

I expect my migrations to run but it fails. I am using Postgres 11 on Mac.
Postgres installed from here - https://postgresapp.com/

Body:
Unfortunately, I do not have much information about what your pg-migrate files look like, but you must specify the following:

pgm.createExtension('uuid-ossp', { ifNotExists: true });
// and
pgm.createTable('my_table', {
    id: { type: 'uuid', primaryKey: true, default: new PgLiteral('gen_random_uuid()') },
    // ...


问:
Binding the value of a variable to a text input
I've been looking all over the internet but I couldn't find an answer to the following question: Is it possible to have the value of some string variable bound to the text inside a text input control? To clarify, whatever text was entered into the text input would be stored as the value of the variable.</p>

答: This may not be exactly what you're looking for but you could always have an event handler on the focusLostevent from the textInput which sets the variable you want to the textInput.text


问:
How to update setState properly on click of a button in ReactJS
I want to change the state on click of a button in React.
Essentially I am trying to update the value of the name displayed in my div by setting this.state.name equal to whatever is typed in the text-box.

What am I doing wrong here?

I also don't quite understand the difference between onClick={() => this.updateText()} and onClick={this.updateText()} and/or onClick={this.updateText}. Maybe it's related to that?

Form.tsx

```<code>import React from 'react';

export default class Form extends React.Component<any, any> {

  constructor(props: any) {
    super(props);

    this.state = {
      title: "Enter a new name here",
      description: "Hola",
      textInput: null,
      name: this.props.name
    };
  }

  updateText() {
    this.setState({
      name: this.state.textInput
    });
  }

  render() {
    return (
      <div className="App">
        <div>{this.props.text} {this.state.name}</div>
        <div>{this.state.age}</div>
        <input type="text" placeholder={this.state.title}>{this.state.textInput}</input>
        <br />
        <button type="submit" onClick={() => this.updateText()}>Submit</button>
      </div>
    );
  }
}
</code>```

App.tsx

```<code>import React from 'react';
import './App.css';
import Form from "./Form";

class App extends React.Component {
  render() {
    return (
      <div className="App">
        <Form text="Hello" age={22} name="Thomas"/>
      </div>
    );
  }
}

export default App;
</code>```

this.state.name comes up as empty or null upon typing something and clicking the submit button.

答:
As @Alexander Staroselsky said in his comment, you should use an onChange handler for your input. This way you can update the textInput and set it to your name value.

{this.updateText()} is not a proper way of using the handler. If you use it like that it is invoked on every render but not with the click.

onClick={this.updateText} Here, you can use the function reference and it works. But, either you have to bind it in the constructor or define it as an arrow function. You can see an example below.

onClick={() => this.updateText()} This is an option of using it. You are using here an arrow function for your handler. It works also without binding your handler function for this. But, with this way your handler function is recreated with every render. Avoid this if possible.

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

        <Form text="Hello" age={22} name="Thomas"/>

    );
  }
}

class Form extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      title: "Enter a new name here",
      description: "Hola",
      textInput: "",
      name: this.props.name
    };
  }

  updateText = () => {
    this.setState({
      name: this.state.textInput
    });
  }

  handleChange = (e) => this.setState({ textInput: e.target.value})

  render() {
    return (

{this.props.text} {this.state.name}

{this.state.age}

        <input value={this.state.textInput} onChange={this.handleChange} type="text" placeholder={this.state.title} />

        <button type="submit" onClick={this.updateText}>Submit</button>

    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root" /></code>```

Body:
I want to change the state on click of a button in React.
Essentially I am trying to update the value of the name displayed in my div by setting this.state.name equal to whatever is typed in the text-box.

What am I doing wrong here?

I also don't quite understand the difference between onClick={() => this.updateText()} and onClick={this.updateText()} and/or onClick={this.updateText}. Maybe it's related to that?

Form.tsx

import React from 'react';

export default class Form extends React.Component<any, any> {

  constructor(props: any) {
    super(props);

    this.state = {
      title: "Enter a new name here",
      description: "Hola",
      textInput: null,
      name: this.props.name
    };
  }

  updateText() {
    this.setState({
      name: this.state.textInput
    });
  }

  render() {
    return (

{this.props.text} {this.state.name}

{this.state.age}

        <input type="text" placeholder={this.state.title}>{this.state.textInput}</input>

        <button type="submit" onClick={() => this.updateText()}>Submit</button>

    );
  }
}

App.tsx

import React from 'react';
import './App.css';
import Form from "./Form";

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

        <Form text="Hello" age={22} name="Thomas"/>

    );
  }
}

export default App;

this.state.name comes up as empty or null upon typing something and clicking the submit button.

Body:
As @Alexander Staroselsky said in his comment, you should use an onChange handler for your input. This way you can update the textInput and set it to your name value.

{this.updateText()} is not a proper way of using the handler. If you use it like that it is invoked on every render but not with the click.

onClick={this.updateText} Here, you can use the function reference and it works. But, either you have to bind it in the constructor or define it as an arrow function. You can see an example below.

onClick={() => this.updateText()} This is an option of using it. You are using here an arrow function for your handler. It works also without binding your handler function for this. But, with this way your handler function is recreated with every render. Avoid this if possible.

class App extends React.Component {
  render() {
    return (
      <div className="App">
        <Form text="Hello" age={22} name="Thomas"/>
      </div>
    );
  }
}

class Form extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      title: "Enter a new name here",
      description: "Hola",
      textInput: "",
      name: this.props.name
    };
  }

  updateText = () => {
    this.setState({
      name: this.state.textInput
    });
  }

  handleChange = (e) => this.setState({ textInput: e.target.value})

  render() {
    return (
      <div className="App">
        <div>{this.props.text} {this.state.name}</div>
        <div>{this.state.age}</div>
        <input value={this.state.textInput} onChange={this.handleChange} type="text" placeholder={this.state.title} />
        <br />
        <button type="submit" onClick={this.updateText}>Submit</button>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root" />


问:
How to secure requesting post - C# and PHP
I have a problems with C#, PHP, MYSQLi.
I made a form for Login & Registration system with

This a simple C# function for user registration.

IEnumerator registrar(
    string name,
    string username,
    string email,
    string password
) {

```<code>// This is what sends messages to our php script
WWWForm form = new WWWForm();

// The fields are the variables we are sending
form.AddField("name", name);
form.AddField("username", username);
form.AddField("email", email);
form.AddField("password", password);

//string url = "http://www.my-server.com/registrar.php";
string url = "http://localhost/registrar.php";

UnityWebRequest www = UnityWebRequest.Post(url, form);

// Wait for php to send something back to unity
yield return www.SendWebRequest();

if (
    www.isNetworkError || www.isHttpError
) {
    Debug.Log("Error!");
} else {
    Debug.Log("Complete!");
}}
</code>```

__

```<code>// Database variables
$db_host        = "localhost";
$db_user        = "root";
$db_password    = "test";
$db_name        = "test";

// Connect to database.
$db = mysqli_connect($db_host, $db_user, $db_password, $db_name);

// User variables
$name           = $db->real_escape_string($_POST["name"]);
$username       = $db->real_escape_string($_POST["username"]);
$email          = $db->real_escape_string($_POST["email"]);
$password       = $db->real_escape_string($_POST["password"]);
$password_hash  = password_hash($password, PASSWORD_DEFAULT);

// E-mail can not be empty
if(
    !empty($email)
    &&
    !empty($username)
    &&
    !empty($password)
) {
    // Insert user data
    $db->query("INSERT INTO `user`(`username`, `name`, `email`, `password`) VALUES ('$username', '$name', '$email', '$password_hash')");

    // Display...
    echo "Success!";
} else {
    // Display an error
    echo "Error!";
}
?>
</code>```

Everything is OK, The PHP code are work to.

But my problem now what gonna happen if the hackers get the URL of registration page, And make for himself a form just like my form and use my URL of registration page and using.

This is my problem, This problem will hack the Game data Like (Score, Total play, Time play, Otherss data).

So how can I protect & secure (request post) Do I have do something in PHP or C#.

答:
Add authentication through an API key! You can make this as advanced or as simple as you want:

form.AddField("apikey", apikey);
```

<pre class="lang-php prettyprint-override"><code>if ($_POST['apikey'] != "<the_api_key>")
    header('HTTP/1.0 403 Forbidden');
</code>```

Or something like that.

Body:
I have a problems with C#, PHP, MYSQLi.
I made a form for Login & Registration system with

This a simple C# function for user registration.

IEnumerator registrar(
    string name,
    string username,
    string email,
    string password
) {

// This is what sends messages to our php script
WWWForm form = new WWWForm();

// The fields are the variables we are sending
form.AddField("name", name);
form.AddField("username", username);
form.AddField("email", email);
form.AddField("password", password);

//string url = "http://www.my-server.com/registrar.php";
string url = "http://localhost/registrar.php";

UnityWebRequest www = UnityWebRequest.Post(url, form);

// Wait for php to send something back to unity
yield return www.SendWebRequest();

if (
    www.isNetworkError || www.isHttpError
) {
    Debug.Log("Error!");
} else {
    Debug.Log("Complete!");
}}

__

// Database variables
$db_host        = "localhost";
$db_user        = "root";
$db_password    = "test";
$db_name        = "test";

// Connect to database.
$db = mysqli_connect($db_host, $db_user, $db_password, $db_name);

// User variables
$name           = $db->real_escape_string($_POST["name"]);
$username       = $db->real_escape_string($_POST["username"]);
$email          = $db->real_escape_string($_POST["email"]);
$password       = $db->real_escape_string($_POST["password"]);
$password_hash  = password_hash($password, PASSWORD_DEFAULT);

// E-mail can not be empty
if(
    !empty($email)
    &&
    !empty($username)
    &&
    !empty($password)
) {
    // Insert user data
    $db->query("INSERT INTO `user`(`username`, `name`, `email`, `password`) VALUES ('$username', '$name', '$email', '$password_hash')");

    // Display...
    echo "Success!";
} else {
    // Display an error
    echo "Error!";
}
?>

Everything is OK, The PHP code are work to.

But my problem now what gonna happen if the hackers get the URL of registration page, And make for himself a form just like my form and use my URL of registration page and using.

This is my problem, This problem will hack the Game data Like (Score, Total play, Time play, Otherss data).

So how can I protect & secure (request post) Do I have do something in PHP or C#.

Body:
Add authentication through an API key! You can make this as advanced or as simple as you want:

form.AddField("apikey", apikey);

if ($_POST['apikey'] != "<the_api_key>")
    header('HTTP/1.0 403 Forbidden');

Or something like that.


问:
How to align text vertically in a div displayed like a grid?
I've been trying to align vertically some text that I've putted in a div, but I wasn't able to do it.

I've already tried to display the div as a table, and display the inner divs as table-cell but this didn't worked because I'm displaying the div that contains the other divs as a grid, nonetheless I setted some css attributes that in theory it should allow me to vertical align the text, but it doesn't worked as well.

/* CSS */

/* TABLA */

.grid-container {
  display: grid;
  grid-template-columns: auto auto auto auto auto auto auto;
  grid-template-rows: 80px 300px;
  grid-gap: 10px;
  background-color: #424242;
  padding: 10px;
  margin: 50px;
}

.grid-container>div {
  background-color: #D0D3D4;
  text-align: center;
  padding: 20px 0;
  font-size: 25px;
  font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif, Haettenschweiler, 'Arial Narrow Bold', sans-serif, Geneva, Tahoma, sans-serif;
}

#align {
  text-align: center;
  vertical-align: middle;
  line-height: 90px;
}

/* IMAGENES */

.resize {
  width: 300px;
  height: 250px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- HTML -->

<div class="grid-container">
  <!-- TITULOS -->
  <div>Portada</div>
  <div>Nombre</div>
  <div>Artista</div>
  <div>Precio</div>
  <div>Cantidad</div>
  <div>Total</div>
  <div>Cancelar</div>
  <!-- CONTENIDOS -->
  <div><img src="rsc/parachutes.jpg" class="resize"></div>
  <div class="align">Parachutes</div>
  <div>Coldplay</div>
  <div>S/100</div>
  <div>1</div>
  <div>S/100</div>
  <div><button>Eliminar</button></div>
  <div><img src="rsc/dookie.jpg" class="resize"></div>
  <div>Dookie</div>
  <div>Green Day</div>
  <div>S/115</div>
  <div>1</div>
  <div>S/115</div>
  <div><button>Eliminar</button></div>
</div></code>```

I want to get the text of each row centered (including the image), but instead I ended up getting this.

答:
Please change #align  to .align

and then add some css code:

```<code>.align {
    text-align: center;
    vertical-align: middle;
    line-height: 90px;
    display: flex;
    justify-content:center;
    align-items:Center;
}
</code>```

Body:
I've been trying to align vertically some text that I've putted in a div, but I wasn't able to do it.

I've already tried to display the div as a table, and display the inner divs as table-cell but this didn't worked because I'm displaying the div that contains the other divs as a grid, nonetheless I setted some css attributes that in theory it should allow me to vertical align the text, but it doesn't worked as well.

/* CSS */

/* TABLA */

.grid-container {
  display: grid;
  grid-template-columns: auto auto auto auto auto auto auto;
  grid-template-rows: 80px 300px;
  grid-gap: 10px;
  background-color: #424242;
  padding: 10px;
  margin: 50px;
}

.grid-container>div {
  background-color: #D0D3D4;
  text-align: center;
  padding: 20px 0;
  font-size: 25px;
  font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif, Haettenschweiler, 'Arial Narrow Bold', sans-serif, Geneva, Tahoma, sans-serif;
}

#align {
  text-align: center;
  vertical-align: middle;
  line-height: 90px;
}

/* IMAGENES */

.resize {
  width: 300px;
  height: 250px;
}

Portada

Nombre

Artista

Precio

Cantidad

Total

Cancelar

Parachutes

Coldplay

S/100

1

S/100

<button>Eliminar</button>

Dookie

Green Day

S/115

1

S/115

<button>Eliminar</button>

I want to get the text of each row centered (including the image), but instead I ended up getting this.

Body:
Please change #align  to .align

and then add some css code:

.align {
    text-align: center;
    vertical-align: middle;
    line-height: 90px;
    display: flex;
    justify-content:center;
    align-items:Center;
}


答:
You cannot ensure that hackers cant post a false score.

You can try on server-side to verify the data (like "is this score possible for played time?").

Or you can do the most as possible on server-side (your C#-application call your php-backend when the user starts a game and return a token (= random string) and measures time).

And you can enforce https on server-side.

Title: How to secure requesting post - C# and PHP


问:
python: testing specific functions in unit test?
I already know how to test specific classes in python's unittest framework. However, I am having trouble testing specific functions. Here is what I use to select classes that I want to get tested:

```<code>if __name__ == '__main__':
    test_classes_to_run = [Class1, Class2, Class3]

    loader = unittest.TestLoader()

    suites_list = []
    for test_class in test_classes_to_run:
        suite = loader.loadTestsFromTestCase(test_class)
        suites_list.append(suite)

    big_suite = unittest.TestSuite(suites_list)

    runner = unittest.TextTestRunner()
    results = runner.run(big_suite)
</code>```

So I tried selecting a specific function doing:

```<code>if __name__ == '__main__':
    testing_class = Class1
    test_classes_to_run = [Class1.function1]

    loader = unittest.TestLoader()

    suites_list = []
    for test_class in test_classes_to_run:
        suite = loader.loadTestsFromTestCase(test_class)
        suites_list.append(suite)

    big_suite = unittest.TestSuite(suites_list)

    runner = unittest.TextTestRunner()
    results = runner.run(big_suite)
</code>```

but I get the following error:

TypeError: issubclass() arg 1 must be a class

答:
Just use

```<code>unittest.TestLoader.loadTestsFromName('Path.to.Class1.test_function1')
</code>```

From the documentation of the unittest module:

For example, if you have a module SampleTests containing a
  TestCase-derived class SampleTestCase with three test methods
  (test_one(), test_two(), and test_three()), the specifier
  'SampleTests.SampleTestCase' would cause this method to return a suite
  which will run all three test methods. Using the specifier
  'SampleTests.SampleTestCase.test_two' would cause it to return a test
  suite which will run only the test_two() test method. The specifier
  can refer to modules and packages which have not been imported; they
  will be imported as a side-effect.

Body:
I already know how to test specific classes in python's unittest framework. However, I am having trouble testing specific functions. Here is what I use to select classes that I want to get tested:

if __name__ == '__main__':
    test_classes_to_run = [Class1, Class2, Class3]

    loader = unittest.TestLoader()

    suites_list = []
    for test_class in test_classes_to_run:
        suite = loader.loadTestsFromTestCase(test_class)
        suites_list.append(suite)

    big_suite = unittest.TestSuite(suites_list)

    runner = unittest.TextTestRunner()
    results = runner.run(big_suite)

So I tried selecting a specific function doing:

if __name__ == '__main__':
    testing_class = Class1
    test_classes_to_run = [Class1.function1]

    loader = unittest.TestLoader()

    suites_list = []
    for test_class in test_classes_to_run:
        suite = loader.loadTestsFromTestCase(test_class)
        suites_list.append(suite)

    big_suite = unittest.TestSuite(suites_list)

    runner = unittest.TextTestRunner()
    results = runner.run(big_suite)

but I get the following error:

TypeError: issubclass() arg 1 must be a class

Body:
Just use

unittest.TestLoader.loadTestsFromName('Path.to.Class1.test_function1')

From the documentation of the unittest module:

For example, if you have a module SampleTests containing a
  TestCase-derived class SampleTestCase with three test methods
  (test_one(), test_two(), and test_three()), the specifier
  'SampleTests.SampleTestCase' would cause this method to return a suite
  which will run all three test methods. Using the specifier
  'SampleTests.SampleTestCase.test_two' would cause it to return a test
  suite which will run only the test_two() test method. The specifier
  can refer to modules and packages which have not been imported; they
  will be imported as a side-effect.


问:
No connection could be made because the target machine actively refused it
I can access web service on my iis by IE. But when I want to access web service by emulator,it raises No connection could be made because the target machine actively refused it. I am using VS 2008.Emulator can access internet. I updated my web referance as localhost or http://127.0.0.1/ but it doesnt work. Anonymus access is enabled on web service and I dont use proxy server.What can be problem?</p>

答: The last time I saw this was because the server didn't have its actual IP.  I don't believe the emulator isn't going to have access to the computer's 127.0.0.1 address.  Have you tried using the actual IP address?</p>


问:
Keep uppercase after / in a string
I'm trying to title the following string:

"Men's L/S long sleeve"

I'm using string.capwords right now but it's not working as expected.

For example:

```<code>x = "Men's L/s Long Sleeve"
y = string.capwords(x)
print(y)
</code>```

outputs:

Men's L/s Long Sleeve

but I want:

Men's L/S Long Sleeve (uppercased S after the /)

Is there an easy way to go about doing this?

答:
Split by /, then run capwords individually on all the components, then rejoin the components</p>

```<code>text = "Men's L/s Long Sleeve"
"/".join(map(string.capwords, text.split("/")))
Out[10]: "Men's L/S Long Sleeve"
</code>```

Title: Keep uppercase after / in a string

Body:
I'm trying to title the following string:

"Men's L/S long sleeve"

I'm using string.capwords right now but it's not working as expected.

For example:

x = "Men's L/s Long Sleeve"
y = string.capwords(x)
print(y)

outputs:

Men's L/s Long Sleeve

but I want:

Men's L/S Long Sleeve (uppercased S after the /)

Is there an easy way to go about doing this?

Body:
Split by /, then run capwords individually on all the components, then rejoin the components

text = "Men's L/s Long Sleeve"
"/".join(map(string.capwords, text.split("/")))
Out[10]: "Men's L/S Long Sleeve"


答:
You can split the string on '/', use string.capwords on each substring, and rejoin on '/':</p>

```<code>import string

'/'.join(string.capwords(s) for s in "Men's L/S long sleeve".split('/'))
</code>```

Title: Keep uppercase after / in a string

Body:
You can split the string on '/', use string.capwords on each substring, and rejoin on '/':

import string

'/'.join(string.capwords(s) for s in "Men's L/S long sleeve".split('/'))


问:
How to upload file to a specific folder in S3 by Boto3
How to upload a file to S3 into a specified folder?

The folder is created as year/month/day/uuid/

I used boto3 and created the folder in an S3 bucket.

```<code>def create_Object(bucket_name):
    s3 = boto3.resource('s3')
    now = datetime.now()
    year=now.strftime("%Y")
    month=now.strftime("%m")
    day=now.strftime("%d")
    uuidf=uuid.uuid4()
    obj_key=year+"/"+month+"/"+day+"/"+str(uuidf)
    print(obj_key)
    objRe=s3.upload_file(obj_key, bucket_name, "testfile.txt")

</code>```

After the upload I need to send a message to SQS. How can I do that?

答:
Be careful -- in the upload_file call, you have the local file and the S3 Key mixed up.

Here's some code that will upload a given file to a Y/M/D/random/ path, then send a message to SQS:

import boto3
from datetime import datetime
import uuid

LOCAL_FILE = 'file.txt'
BUCKET = 'my-bucket'
SQS_QUEUE = 'https://sqs.ap-southeast-2.amazonaws.com/123456789012/foo'

# Upload file to Y/M/D/random-id/filename
s3_client = boto3.client('s3', region_name='ap-southeast-2')
path = datetime.now().strftime("%Y/%m/%d/") + str(uuid.uuid4()) + '/'
print(path)
response = s3_client.upload_file(LOCAL_FILE, BUCKET, path + LOCAL_FILE)

# Send a message to SQS
sqs_client = boto3.client('sqs', region_name='ap-southeast-2')
response = sqs_client.send_message(
    QueueUrl = SQS_QUEUE,
    MessageBody = 'New file is: ' + path + LOCAL_FILE
    )
```

Body:
How to upload a file to S3 into a specified folder?

The folder is created as year/month/day/uuid/

I used boto3 and created the folder in an S3 bucket.

def create_Object(bucket_name):
    s3 = boto3.resource('s3')
    now = datetime.now()
    year=now.strftime("%Y")
    month=now.strftime("%m")
    day=now.strftime("%d")
    uuidf=uuid.uuid4()
    obj_key=year+"/"+month+"/"+day+"/"+str(uuidf)
    print(obj_key)
    objRe=s3.upload_file(obj_key, bucket_name, "testfile.txt")

After the upload I need to send a message to SQS. How can I do that?


问:
Why is a[j] equal to j[a] for every array a and integer j?
I am reading through the section about pointers and arrays from "The c++ programming language", and I came across something that stumps me.

For every built-in array a and integer j within the range of a, we
  have:

a[j] == *(&a[0]+j) == *(a+j) == *(j+a) == j[a]

I understand why *(&a[0]+j) means the same as a[j], because &a[0] points to the first element of a and then it's incremented by j.

I also get that *(a+j) and *(j+a) are equal to a[j], a gets implicitly converted from an array to a pointer to the first element of a, and then incremented by j and dereferenced.

But why is a[j] == j[a]?
What am I missing?

答:
Because the subscript operator is commutative. It is simply specified to be so by the language.

You can see the symmetry from the equivalence with the pointer arithmetic expressions, where the addition operator is also commutative:

```<code>a[j] == ∗(a+j)
j[a] == ∗(j+a)
∗(a+j) == ∗(j+a)
</code>```

The language standard (draft) says:

[expr.sub]

... The expression E1[E2] is identical (by definition) to *((E1)+(E2)) ...

[Note: Despite its asymmetric appearance, subscripting is a commutative operation except for sequencing.

Body:
Because the subscript operator is commutative. It is simply specified to be so by the language.

You can see the symmetry from the equivalence with the pointer arithmetic expressions, where the addition operator is also commutative:

a[j] == ∗(a+j)
j[a] == ∗(j+a)
∗(a+j) == ∗(j+a)

The language standard (draft) says:

[expr.sub]

... The expression E1[E2] is identical (by definition) to *((E1)+(E2)) ...

[Note: Despite its asymmetric appearance, subscripting is a commutative operation except for sequencing.


问:
NSThread Picks Up Queue and Processes It
I have an app that needs to send collected data every X milliseconds (and NOT sooner!). My first thought was to stack up the data on an NSMutableArray (array1) on thread1. When thread2 has finished waiting it's X milliseconds, it will swap out the NSMutableArray with a fresh one (array2) and then process its contents. However, I don't want thread1 to further modify array1 once thread2 has it.

This will probably work, but thread safety is not a field where you want to "just try it out." What are the pitfalls to this approach, and what should I do instead?

(Also, if thread2 is actually an NSTimer instance, how does the problem/answer change? Would it all happen on one thread [which would be fine for me, since the processing takes a tiny fraction of a millisecond]?).

答:
You should use either NSOperationQueue or Grand Central Dispatch. Basically, you'll create an operation that receives your data and uploads it when X milliseconds have passed. Each operation will be independent and you can configure the queue wrt how many concurrent ops you allow, op priority, etc.

The Apple docs on concurrency should help:

http://developer.apple.com/library/ios/#documentation/General/Conceptual/ConcurrencyProgrammingGuide/Introduction/Introduction.html


问:
Is it possible to have a segmentation fault due to an x-server?
For a school project, I'm building a GUI, but I wanted to work on this project at home, and as I only own a windows computer, I installed a x-server (to use with the Windows Subsystem for Linux) : "VcXsrv Windows X Server".

For some of my test programs it worked perfectly, but for one, I've got a segmentation fault (core dumped).

So I tried to debug with gdb (which doesn't neet the x-server to work), but... it worked perfectly...

So here's my question : is it possible to get a segmentation fault due to the x-server ?

答:
If your program fails with a segmentation fault then the root cause is almost certain to be in your program, not the environment.  It is possible, however, that the undefined behavior of your program that manifests as a segfault in one environment manifests differently in another environment or with a different configuration.  In that sense, you could say that an X server could "cause" a segfault, but characterizing it that way does not in any way let your program off the hook.

It's not uncommon that UB manifests differently when a program is run under a debugger than when run directly.  This goes along with being "undefined".  If you're seeing segfaults then it's not unreasonable to turn to a debugger, but a more likely tool for characterizing the problem would be a memory-usage analyzer, such as Valgrind.


问:
express res not working after DB connection
I try to connect the DB with Node.js. If I fire the script from console, all seems fine. But accessing from browser, response stops when connecting

From console, I get
inside contest
Example all listening on port 3000!
Connected Con!

From browser, I get
Hello World!inside restest

Since the the "listening..." message was before "Connected" in console version, I thought that in browser version, maybe the system got res.end() before it got connected to DB. Thus, I moved the res.end() from end of app.get -function to end of restest -function, and put a send()- to original place just in case. But that was not the reason as I still cannot get the "Connected Res!" -message.

```<code>var http = require('http');
const express = require('express');
const app = express();
const port = 3000;
var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "login",
  password: "psw",
  database: "db"
});

function restest(req, res) {
    res.write("inside restest");

    con.connect(function(err) {
        if (err) throw err;
        res.write("Connected Res!");
        res.end();
    });
}

function contest() {
    console.log("inside contest");

    con.connect(function(err) {
        if (err) throw err;
        console.log("Connected Con!");
    });
}

contest();

app.get('/nodejs/', function(req, res) {
    res.write('Hello World!');
    restest(req,res);
    res.send("this should not print out");
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`));
</code>```

No error messages, it just stops responses after writing "inside restest"

答: So, here what's happening is that: Once the /nodejs api is called it will write the Hello World! text and then it will go to restest function and it will write inside restest and then it will start connecting to the DB asynchronously as DB connect is an asynchrous function and it will come back to the restest function and it will send the response with res.send("this should not print out");. So, after this the res is no more accessible inside the DB connect function.

Body:
I try to connect the DB with Node.js. If I fire the script from console, all seems fine. But accessing from browser, response stops when connecting

From console, I get
inside contest
Example all listening on port 3000!
Connected Con!

From browser, I get
Hello World!inside restest

Since the the "listening..." message was before "Connected" in console version, I thought that in browser version, maybe the system got res.end() before it got connected to DB. Thus, I moved the res.end() from end of app.get -function to end of restest -function, and put a send()- to original place just in case. But that was not the reason as I still cannot get the "Connected Res!" -message.

var http = require('http');
const express = require('express');
const app = express();
const port = 3000;
var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "login",
  password: "psw",
  database: "db"
});

function restest(req, res) {
    res.write("inside restest");

    con.connect(function(err) {
        if (err) throw err;
        res.write("Connected Res!");
        res.end();
    });
}

function contest() {
    console.log("inside contest");

    con.connect(function(err) {
        if (err) throw err;
        console.log("Connected Con!");
    });
}

contest();

app.get('/nodejs/', function(req, res) {
    res.write('Hello World!');
    restest(req,res);
    res.send("this should not print out");
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`));

No error messages, it just stops responses after writing "inside restest"


问:
Adding consecutive elements across dimension in tensorflow (np.add.reduceat)
Is there any tensorflow function or elegant of doing following task

consider I have 2d tensor with dimensions  say $3 \times 10$.now I want to add consecutive elements along dimension $1$(or row) where number of consecutive elements to be added is decided by tensor.if it says $[2,2,4,2]$ the output tensor should be of size $ 3 \times 4$. because $ [ a_1 + a_2 , a_3+a_4 , a_5+a_6+a_7+a_8 , a_9+a_10]$ would tensor across each row

ex:

```<code>$\begin{bmatrix}
1 & 2 & 3 & 4 & 5 & 6 & 1 & 2 & 3 &4\\
7 & 8 & 9 & 10 &11  &12 & 7 & 8 & 9 & 10\\
13 &14  &15  &16  &17  &18 & 13 &14 &15 &16
\end{bmatrix}$
</code>```

and output should be following

```<code>$\begin{bmatrix}
3 & 7 & 14 & 7\\
15 & 19 &38 &19\\
27  &31 & 62 &31
\end{bmatrix}$
</code>```

EDIT:there seems to be function for this in numpy np.add.reduceat

答:
There is no such function in tensorflow. But you can construct it by splitting the array:

```<code>def tf_reduceat(data, at_array, axis=-1):
    split_data = tf.split(data, at_array, axis=axis)
    return tf.stack([tf.reduce_sum(i, axis=axis) for i in split_data], axis=axis)

a = tf.constant([[1, 2, 3, 4, 5, 6, 1, 2, 3, 4],
                 [7, 8, 9, 10, 11, 12, 7, 8, 9, 10],
                 [13, 14, 15, 16, 17, 18, 13, 14, 15, 16]])
result = tf_reduceat(a, [2, 2, 4, 2])
</code>```

Running result yields:

```<code>array([[ 3,  7, 14,  7],
       [15, 19, 38, 19],
       [27, 31, 62, 31]], dtype=int32)
</code>```

Body:
Is there any tensorflow function or elegant of doing following task

consider I have 2d tensor with dimensions  say $3 \times 10$.now I want to add consecutive elements along dimension $1$(or row) where number of consecutive elements to be added is decided by tensor.if it says $[2,2,4,2]$ the output tensor should be of size $ 3 \times 4$. because $ [ a_1 + a_2 , a_3+a_4 , a_5+a_6+a_7+a_8 , a_9+a_10]$ would tensor across each row

ex:

$\begin{bmatrix}
1 & 2 & 3 & 4 & 5 & 6 & 1 & 2 & 3 &4\\
7 & 8 & 9 & 10 &11  &12 & 7 & 8 & 9 & 10\\
13 &14  &15  &16  &17  &18 & 13 &14 &15 &16
\end{bmatrix}$

and output should be following

$\begin{bmatrix}
3 & 7 & 14 & 7\\
15 & 19 &38 &19\\
27  &31 & 62 &31
\end{bmatrix}$

EDIT:there seems to be function for this in numpy np.add.reduceat

Body:
There is no such function in tensorflow. But you can construct it by splitting the array:

def tf_reduceat(data, at_array, axis=-1):
    split_data = tf.split(data, at_array, axis=axis)
    return tf.stack([tf.reduce_sum(i, axis=axis) for i in split_data], axis=axis)

a = tf.constant([[1, 2, 3, 4, 5, 6, 1, 2, 3, 4],
                 [7, 8, 9, 10, 11, 12, 7, 8, 9, 10],
                 [13, 14, 15, 16, 17, 18, 13, 14, 15, 16]])
result = tf_reduceat(a, [2, 2, 4, 2])

Running result yields:

array([[ 3,  7, 14,  7],
       [15, 19, 38, 19],
       [27, 31, 62, 31]], dtype=int32)


问:
Trying to append a column in numpy array, getting ValueError
I am trying to append column for the following arrays

```<code>train = np.append(train_data, train_labels, axis=1)

(60000, 784)
(60000,)
</code>```

And I get the error

```<code>ValueError: all the input arrays must have same number of dimensions
</code>```

I cannot understand what the issue is...
I need output of

```<code>(60000, 785)
</code>```

答:
You should run

```<code>train = np.append(train_data, train_labels.reshape(-1, 1), axis=1)
</code>```

That will fix your problem.
Cheers

Body:
I am trying to append column for the following arrays

train = np.append(train_data, train_labels, axis=1)

(60000, 784)
(60000,)

And I get the error

ValueError: all the input arrays must have same number of dimensions

I cannot understand what the issue is...
I need output of

(60000, 785)

Body:
You should run

train = np.append(train_data, train_labels.reshape(-1, 1), axis=1)

That will fix your problem.
Cheers


问:
How to check to see if two buttons are HELD together at same time ANDROID?
I have two circular buttons, each a different color.

Now if both buttons are held at the same time, I want them to both turn a completely new 3rd color, along with a sound effect, some graphical changes, etc.

The following code seems to work about 50% of the time, usually only when both buttons are pressed perfectly together. (If one button is held, and then the other is held shortly after, even by a hair, the app seems to crash).

```<code>    new Thread(new Runnable() {
        public void run(){
            while (keepgoing) {
                if (held1== true && held2==true) {
                    player2.start();
                    greenbutton.setBackground(getResources().getDrawable(R.drawable.brickbutton));
                    pinkbutton.setBackground(getResources().getDrawable(R.drawable.brickbutton));
                    keepgoing = false;
                    return;
                }
            }
            return;
        }

   }).start();

}
</code>```

held1 is set to true when the  button1.setOnLongClick event happens.
held1 is set to false when the MotionEvent.ACTION_UP case happens for an OnTouchListener for button1.

same for button 2, like so.

```<code>      greenbutton.setOnLongClickListener(new View.OnLongClickListener() {
          @Override
          public boolean onLongClick(View v) {
              held1 = true;
              player.start();
              if (switched){
                  revertButtons();
                  return true;
              }
              else {
                  switchButtons();
                  return true;
              }
          }
      });

      greenbutton.setOnTouchListener(new View.OnTouchListener() {
          @Override
          public boolean onTouch(View v, MotionEvent event) {
              switch (event.getAction()){
                  case MotionEvent.ACTION_UP:
                      held1 = false;
                      player.start();
                      if (bricked){
                          return true;
                      }
                      if (switched){
                          revertButtons();
                          break;
                      }
                      else {
                          switchButtons();
                          break;
                      }
              }
              return false;
          }
      });
</code>```

why is this code so unstable?

答:
How about doing something like this,

```<code>while(held1 == true){
if(held2 == false){
//do something
}else{
player2.start();
                    greenbutton.setBackground(getResources().getDrawable(R.drawable.brickbutton));
                    pinkbutton.setBackground(getResources().getDrawable(R.drawable.brickbutton));
                    keepgoing = false;
                    return;
}
}
</code>```

The idea is to imitate observer pattern like solution. Not only when they are both held together like you did, but to observe the second one so that at any point if they are both clicked then your work will be done. This is the beauty of RxJava/Rxandroid observer pattern. It would be perfect solution in your case.

Body:
I have two circular buttons, each a different color.

Now if both buttons are held at the same time, I want them to both turn a completely new 3rd color, along with a sound effect, some graphical changes, etc.

The following code seems to work about 50% of the time, usually only when both buttons are pressed perfectly together. (If one button is held, and then the other is held shortly after, even by a hair, the app seems to crash).

    new Thread(new Runnable() {
        public void run(){
            while (keepgoing) {
                if (held1== true && held2==true) {
                    player2.start();
                    greenbutton.setBackground(getResources().getDrawable(R.drawable.brickbutton));
                    pinkbutton.setBackground(getResources().getDrawable(R.drawable.brickbutton));
                    keepgoing = false;
                    return;
                }
            }
            return;
        }

   }).start();

}

held1 is set to true when the  button1.setOnLongClick event happens.
held1 is set to false when the MotionEvent.ACTION_UP case happens for an OnTouchListener for button1.

same for button 2, like so.

      greenbutton.setOnLongClickListener(new View.OnLongClickListener() {
          @Override
          public boolean onLongClick(View v) {
              held1 = true;
              player.start();
              if (switched){
                  revertButtons();
                  return true;
              }
              else {
                  switchButtons();
                  return true;
              }
          }
      });

      greenbutton.setOnTouchListener(new View.OnTouchListener() {
          @Override
          public boolean onTouch(View v, MotionEvent event) {
              switch (event.getAction()){
                  case MotionEvent.ACTION_UP:
                      held1 = false;
                      player.start();
                      if (bricked){
                          return true;
                      }
                      if (switched){
                          revertButtons();
                          break;
                      }
                      else {
                          switchButtons();
                          break;
                      }
              }
              return false;
          }
      });

why is this code so unstable?

Body:
How about doing something like this,

while(held1 == true){
if(held2 == false){
//do something
}else{
player2.start();
                    greenbutton.setBackground(getResources().getDrawable(R.drawable.brickbutton));
                    pinkbutton.setBackground(getResources().getDrawable(R.drawable.brickbutton));
                    keepgoing = false;
                    return;
}
}

The idea is to imitate observer pattern like solution. Not only when they are both held together like you did, but to observe the second one so that at any point if they are both clicked then your work will be done. This is the beauty of RxJava/Rxandroid observer pattern. It would be perfect solution in your case.


问:
Is it possible to deserialize inline arrays with Json.NET?
Let me try to simplify my question by extracting and abstracting relevant information from a complex object and large JSON text.

```<code>Class Foo()
{
  string Name;
  Version[] versions;
}
</code>```

JsonText(converted from XML) can be something like this:

```<code>  "Foo": {
    "Name": "test",
    "versions": {
        "Major": "1",
        "Minor": "1"
    },
    "versions": {
        "Major": "2",
        "Minor": "1"
    },
    "versions": {
        "Major": "3",
        "Minor": "1"
    }
    }
</code>```

or the following:

```<code>  "Foo": {
    "Name": "test",
    "versions": {
        "Major": "1",
        "Minor": "1"
    }
    }
</code>```

JsonConvert.DeserializeObject(JsonText) results in:

```<code>Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'Version[]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
</code>```

Is it possible to do this desrialization?

答:
Updated based on commment

Your Json doesn't look valid. A Json needs to be enclosed with "[" "]". For example,

```<code>[ "Ford", "BMW", "Fiat" ]
</code>```

If you are allowed to modify your Json, You could modify the Json as following

```<code>{
"Foo":
{
    "Name": "test",
    "versions": [
    {
        "Major": "1",
        "Minor": "1"
    },
    {
        "Major": "2",
        "Minor": "1"
    },
    {
        "Major": "3",
        "Minor": "1"
    }]
}
}
</code>```

Based on your comment, you would like to avoid the Json Array Syntax if there is only a single element. On other cases, you would like to stick to Array Syntax. In such scenario,you could write a Custom Json Converter.

```<code>class CustomConverter<T> : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(List<T>));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JToken token = JToken.Load(reader);
        if (token.Type == JTokenType.Array)
        {
            return token.ToObject<List<T>>().ToArray();
        }
        return new List<T> { token.ToObject<T>() }.ToArray();
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}
</code>```

You can decorate your class with JsonConverter attribute to use the Custom Json Converter.

```<code>class Wrapper
{
    public Foo Foo{get;set;}
}
class Foo
{
  [JsonProperty("Name")]
  public string Name{get;set;}

  [JsonProperty("versions")]
  [JsonConverter(typeof(CustomConverter<Version>))]
  public Version[] versions{get;set;}
}
</code>```

Now you can deserialize as

```<code>var result =JsonConvert.DeserializeObject<Wrapper>(str);
</code>```

This would now work, if you use either of following Json definition.

```<code> {
    'Foo':
    {
        'Name': 'test',
        'versions': [
        {
            'Major': '1',
            'Minor': '1'
        },
        {
            'Major': '2',
            'Minor': '1'
        },
        {
            'Major': '3',
            'Minor': '1'
        }]
    }
    }
</code>```

Single Version (Without Array syntax)

```<code>  {
    'Foo':
    {
        'Name': 'test',
        'versions':
        {
            'Major': '1',
            'Minor': '1'
        }
    }
    }
</code>```

Body:
Let me try to simplify my question by extracting and abstracting relevant information from a complex object and large JSON text.

Class Foo()
{
  string Name;
  Version[] versions;
}

JsonText(converted from XML) can be something like this:

  "Foo": {
    "Name": "test",
    "versions": {
        "Major": "1",
        "Minor": "1"
    },
    "versions": {
        "Major": "2",
        "Minor": "1"
    },
    "versions": {
        "Major": "3",
        "Minor": "1"
    }
    }

or the following:

  "Foo": {
    "Name": "test",
    "versions": {
        "Major": "1",
        "Minor": "1"
    }
    }

JsonConvert.DeserializeObject(JsonText) results in:

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'Version[]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

Is it possible to do this desrialization?

Body:
Updated based on commment

Your Json doesn't look valid. A Json needs to be enclosed with "[" "]". For example,

[ "Ford", "BMW", "Fiat" ]

If you are allowed to modify your Json, You could modify the Json as following

{
"Foo":
{
    "Name": "test",
    "versions": [
    {
        "Major": "1",
        "Minor": "1"
    },
    {
        "Major": "2",
        "Minor": "1"
    },
    {
        "Major": "3",
        "Minor": "1"
    }]
}
}

Based on your comment, you would like to avoid the Json Array Syntax if there is only a single element. On other cases, you would like to stick to Array Syntax. In such scenario,you could write a Custom Json Converter.

class CustomConverter<T> : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(List<T>));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JToken token = JToken.Load(reader);
        if (token.Type == JTokenType.Array)
        {
            return token.ToObject<List<T>>().ToArray();
        }
        return new List<T> { token.ToObject<T>() }.ToArray();
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

You can decorate your class with JsonConverter attribute to use the Custom Json Converter.

class Wrapper
{
    public Foo Foo{get;set;}
}
class Foo
{
  [JsonProperty("Name")]
  public string Name{get;set;}

  [JsonProperty("versions")]
  [JsonConverter(typeof(CustomConverter<Version>))]
  public Version[] versions{get;set;}
}

Now you can deserialize as

var result =JsonConvert.DeserializeObject<Wrapper>(str);

This would now work, if you use either of following Json definition.

 {
    'Foo':
    {
        'Name': 'test',
        'versions': [
        {
            'Major': '1',
            'Minor': '1'
        },
        {
            'Major': '2',
            'Minor': '1'
        },
        {
            'Major': '3',
            'Minor': '1'
        }]
    }
    }

Single Version (Without Array syntax)

  {
    'Foo':
    {
        'Name': 'test',
        'versions':
        {
            'Major': '1',
            'Minor': '1'
        }
    }
    }


问:
Syntax meaning for `impl<'a> Config<'a> {`
For the following code:

```<code>struct Config<'a> {
    query: &'a str,
    filename: &'a str,
    case_sensitive: bool,
}

impl<'a> Config<'a> {
    pub fn new(args: &'a [String]) -> Result<Config, &'static str> {
        if args.len() < 3 {
            return Err("not enough arguments");
        }

        let query = &args[1];
        let filename = &args[2];

        let case_sensitive = env::var("CASE_INSENSITIVE").is_err();

        Ok(Config {
            query,
            filename,
            case_sensitive,
        })
    }
}
</code>```

Why impl<'a> Config<'a> { is required, rather than impl Config<'a> {?

What is the syntactic meaning of the first and second 'a? I know 'a is a lifetime annotation, but don't know why it's placed after both impl and Config. What does the first 'a do and what does the second 'a do?

答:
The first <'a> declares a context which introduces variables which are universally quantified. In other words, impl<'a> ... means "implement for any possible lifetime 'a ... ".

Once the variables are introduced, the second 'a is the application of the variable to a type.

You can read the syntax impl<'a> Config<'a> as: "for any possible lifetime 'a these methods are defined for Config<'a>".

In a more complex situation the context is where you can place constraints on the parameters. For lifetimes this is always an "outlives" relationship, for example <'a, 'b: 'a> ("for all lifetimes 'a and 'b where 'b outlives 'a"). For types, this could include both trait or lifetime bounds, e.g. <'a, T: + Debug + 'a> ("for all lifetimes, 'a and all types T, where T implements Debug and does not outlive 'a").

Body:
For the following code:

struct Config<'a> {
    query: &'a str,
    filename: &'a str,
    case_sensitive: bool,
}

impl<'a> Config<'a> {
    pub fn new(args: &'a [String]) -> Result<Config, &'static str> {
        if args.len() < 3 {
            return Err("not enough arguments");
        }

        let query = &args[1];
        let filename = &args[2];

        let case_sensitive = env::var("CASE_INSENSITIVE").is_err();

        Ok(Config {
            query,
            filename,
            case_sensitive,
        })
    }
}

Why impl<'a> Config<'a> { is required, rather than impl Config<'a> {?

What is the syntactic meaning of the first and second 'a? I know 'a is a lifetime annotation, but don't know why it's placed after both impl and Config. What does the first 'a do and what does the second 'a do?


答:
All generic lifetimes and types need to be declared somewhere.

Try to compile your code to use impl Config<'a> and you'll get this error message:

error[E0261]: use of undeclared lifetime name `'a`
 --> src/lib.rs:9:13
  |
9 | impl Config<'a> {
  |             ^^ undeclared lifetime
```

<p>Like type parameters, generic lifetime parameters such as the <code>'a</code> in <code>Config<'a></code> need to be declared on every function, type definition or trait implementation that they are used. They do not even have to have exactly the same name as how the parameter was declared originally:</p>

<pre class="lang-rust prettyprint-override"><code>impl<'c> Config<'c> {
    ... // use 'c instead of 'a
}
</code>```

See also:

What are the differences between specifying lifetime parameters on an impl or on a method?

The Rust Programming Language, Section 1.1 on using generic data types in method definitions;

The Rust Programming Language, Section 10.2 on using trait bounds to conditionally implement methods.

Title: Syntax meaning for `impl<'a> Config<'a> {`

Body:
All generic lifetimes and types need to be declared somewhere.

Try to compile your code to use impl Config<'a> and you'll get this error message:

error[E0261]: use of undeclared lifetime name `'a`
 --> src/lib.rs:9:13
  |
9 | impl Config<'a> {
  |             ^^ undeclared lifetime

Like type parameters, generic lifetime parameters such as the 'a in Config<'a> need to be declared on every function, type definition or trait implementation that they are used. They do not even have to have exactly the same name as how the parameter was declared originally:

impl<'c> Config<'c> {
    ... // use 'c instead of 'a
}

See also:

What are the differences between specifying lifetime parameters on an impl or on a method?

The Rust Programming Language, Section 1.1 on using generic data types in method definitions;

The Rust Programming Language, Section 10.2 on using trait bounds to conditionally implement methods.


问:
ehCache and Spring MVC Error with HIbernate
I am trying to get caching working on a Service layer method, but it still goes into it and calls the database.  Is my setup wrong?

```<code>@Cacheable(cacheName="apiActivitiesCache", keyGenerator = @KeyGenerator (
            name = "ListCacheKeyGenerator",
            properties = {
                    @Property( name="useReflection", value="true" ),
                    @Property( name="checkforCycles", value="true" ),
                    @Property( name="includeMethod", value="false" )
            }
        )
    )
    public GetMemberActivitiesResponse getActivities(GetMemberActivitiesRequest request) {
</code>```

servlet-context.xml

```<code><ehcache:annotation-driven cache-manager="ehCacheManager" create-missing-caches="true"/>

    <ehcache:config cache-manager="ehCacheManager">
        <ehcache:evict-expired-elements interval="60" />
    </ehcache:config>

    <beans:bean id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
        <beans:property name="configLocation"  value="/WEB-INF/spring/ehcache.xml"/>
    </beans:bean>
</code>```

ehcache.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
    <defaultCache eternal="true" maxElementsInMemory="100" overflowToDisk="false" />
    <cache name="apiActivitiesCache" eternal="false"
        maxElementsInMemory="100" overflowToDisk="false" diskPersistent="false"
        timeToIdleSeconds="0" timeToLiveSeconds="300"
        memoryStoreEvictionPolicy="LRU" />
</ehcache>
</code>```

答: Is getActivities defined by an interface? Spring uses interface based Java proxies for annotation wrappers so all annotated methods must be defined by an interface.</p>

ContentLicense: CC BY-SA 2.5

Body:
I am trying to get caching working on a Service layer method, but it still goes into it and calls the database.  Is my setup wrong?

@Cacheable(cacheName="apiActivitiesCache", keyGenerator = @KeyGenerator (
            name = "ListCacheKeyGenerator",
            properties = {
                    @Property( name="useReflection", value="true" ),
                    @Property( name="checkforCycles", value="true" ),
                    @Property( name="includeMethod", value="false" )
            }
        )
    )
    public GetMemberActivitiesResponse getActivities(GetMemberActivitiesRequest request) {

servlet-context.xml

<ehcache:annotation-driven cache-manager="ehCacheManager" create-missing-caches="true"/>

    <ehcache:config cache-manager="ehCacheManager">
        <ehcache:evict-expired-elements interval="60" />
    </ehcache:config>

    <beans:bean id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
        <beans:property name="configLocation"  value="/WEB-INF/spring/ehcache.xml"/>
    </beans:bean>

ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
    <defaultCache eternal="true" maxElementsInMemory="100" overflowToDisk="false" />
    <cache name="apiActivitiesCache" eternal="false"
        maxElementsInMemory="100" overflowToDisk="false" diskPersistent="false"
        timeToIdleSeconds="0" timeToLiveSeconds="300"
        memoryStoreEvictionPolicy="LRU" />
</ehcache>


问:
FFmpegMediaMetadataRetriever from External Storage? Android Studio/Kotlin
So I'm making my first Android app and I'm trying to get it to allow the user to pick a video from their gallery before seeing the video and the video's current details in the next activity.
My problem is that when I use FFmpegMediaMetadataRetriever and pass it the video's filepath, I receive the error java.lang.IllegalArgumentException: setDataSource failed: status = 0xFFFFFFFF.
I've heard through the grapevine that this means my filepath is invalid. When I Log.d the filepath, I get content://media/external/file/3565, which to me looks like a proper filepath!
I hope somebody can help me figure this out.

Here is my activity class for context:

```<code>class NewProject : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_new_project)

        val videoPath = intent.getStringExtra("video")
        initVideo(videoPath)

        backButtonText.setOnClickListener{ goBack() }
    }

    private fun goBack() {
        val intent = Intent(this,MainActivity::class.java)
        startActivity(intent)
    }

    private fun initVideo(videoPath:String) {
        newProjVideoView.setVideoPath(videoPath)
        newProjVideoView.start()
        newProjVideoView.setOnCompletionListener {
            newProjVideoView.pause()
        }
        getVideoMetadata(videoPath)
    }

    private fun getVideoMetadata(videoPath: String) {
        try {
            e("videoPath", videoPath)
            val receiver = FFmpegMediaMetadataRetriever()
            receiver.setDataSource(videoPath)

        } catch (e:IOException) {
            e("retrieve1","There was an issue", e)
        }
    }
}
</code>```

I'm also happy to hear any constructive feedback on my code!
Please, thank you and have a nice day!

答: So, I think my issue stemmed from trying to pass the video through an intent and then running the MetadataRetriever. I solved it by getting all the info in the previous activity before passing each value as an extra to be used on the next screen.</p>

Body:
So I'm making my first Android app and I'm trying to get it to allow the user to pick a video from their gallery before seeing the video and the video's current details in the next activity.
My problem is that when I use FFmpegMediaMetadataRetriever and pass it the video's filepath, I receive the error java.lang.IllegalArgumentException: setDataSource failed: status = 0xFFFFFFFF.
I've heard through the grapevine that this means my filepath is invalid. When I Log.d the filepath, I get content://media/external/file/3565, which to me looks like a proper filepath!
I hope somebody can help me figure this out.

Here is my activity class for context:

class NewProject : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_new_project)

        val videoPath = intent.getStringExtra("video")
        initVideo(videoPath)

        backButtonText.setOnClickListener{ goBack() }
    }

    private fun goBack() {
        val intent = Intent(this,MainActivity::class.java)
        startActivity(intent)
    }

    private fun initVideo(videoPath:String) {
        newProjVideoView.setVideoPath(videoPath)
        newProjVideoView.start()
        newProjVideoView.setOnCompletionListener {
            newProjVideoView.pause()
        }
        getVideoMetadata(videoPath)
    }

    private fun getVideoMetadata(videoPath: String) {
        try {
            e("videoPath", videoPath)
            val receiver = FFmpegMediaMetadataRetriever()
            receiver.setDataSource(videoPath)

        } catch (e:IOException) {
            e("retrieve1","There was an issue", e)
        }
    }
}

I'm also happy to hear any constructive feedback on my code!
Please, thank you and have a nice day!