问:
How to restart bluetooth service when my server service restarts in systemd
I am using systemd services on an embedded system. I have a web service that needs to restart bluetooth everytime it restarts. How do I write the unit file for this. Also the service I have is put into systemd/user and not systemd/system.
I tried using PartOf=bluetooth.service but that didn't work.</p>

```<code>[Unit]

# Human readable name of the unit
Description=Python User Service
#Link it to bluetooth
After=bluetooth.service
Requires=bluetooth.service
PartOf=bluetooth.service

[Service]

# Command to execute when the service is started
ExecStart=/usr/bin/python3 /home/root/MyServ.py

# Disable Python's buffering of STDOUT and STDERR, so that output from the
# service shows up immediately in systemd's logs
Environment=PYTHONUNBUFFERED=1

# Automatically restart the service if it crashes
Restart=on-failure

# Our service will notify systemd once it is up and running
#Type=notify
Type=simple

# Use a dedicated user to run our service
User=root

[Install]

# Tell systemd to automatically start this service when the system boots
# (assuming the service is enabled)
WantedBy=default.target
</code>```

答:
On [Unit] section you can reload services

PropagatesReloadTo=, ReloadPropagatedFrom=

A space-separated list of one or more units where reload requests on this unit will be propagated to, or reload requests on the
  other unit will be propagated to this unit, respectively. Issuing a
  reload request on a unit
         will automatically also enqueue a reload request on all units that the reload request shall be propagated to via these two settings.

It sends bluetoothd command to reload via dbus. Not kill daemon, just reread configuration.

Or on [Service] section

```<code>ExecStopPost=/usr/bin/systemctl restart bluetooth.service
</code>```

Or use override.conf on bluetooth.service

```<code>systemctl edit bluetooth.service
</code>```

And here put

```<code>[Unit]
BindsTo=MyServ.service
</code>```

Body:
I am using systemd services on an embedded system. I have a web service that needs to restart bluetooth everytime it restarts. How do I write the unit file for this. Also the service I have is put into systemd/user and not systemd/system.
I tried using PartOf=bluetooth.service but that didn't work.

[Unit]

# Human readable name of the unit
Description=Python User Service
#Link it to bluetooth
After=bluetooth.service
Requires=bluetooth.service
PartOf=bluetooth.service

[Service]

# Command to execute when the service is started
ExecStart=/usr/bin/python3 /home/root/MyServ.py

# Disable Python's buffering of STDOUT and STDERR, so that output from the
# service shows up immediately in systemd's logs
Environment=PYTHONUNBUFFERED=1

# Automatically restart the service if it crashes
Restart=on-failure

# Our service will notify systemd once it is up and running
#Type=notify
Type=simple

# Use a dedicated user to run our service
User=root

[Install]

# Tell systemd to automatically start this service when the system boots
# (assuming the service is enabled)
WantedBy=default.target

Body:
On [Unit] section you can reload services

PropagatesReloadTo=, ReloadPropagatedFrom=

A space-separated list of one or more units where reload requests on this unit will be propagated to, or reload requests on the
  other unit will be propagated to this unit, respectively. Issuing a
  reload request on a unit
         will automatically also enqueue a reload request on all units that the reload request shall be propagated to via these two settings.

It sends bluetoothd command to reload via dbus. Not kill daemon, just reread configuration.

Or on [Service] section

ExecStopPost=/usr/bin/systemctl restart bluetooth.service

Or use override.conf on bluetooth.service

systemctl edit bluetooth.service

And here put

[Unit]
BindsTo=MyServ.service


来源: stackexchange

问:
textfield value changing detect in php
```<code> <input name="aa" type="text" id="aa" value="please enter your name" size="22"            maxlength="60" />
 <input name="aab" type="text" id="aab" value="please enter your email" size="22"            maxlength="60" />
</code>```

i have a textfield and it's value is "please enter your name"(likewise i have many fields.i want to add the value to the database only if the value is changed.(if user entered a name)

i used php isset function and it does not work properly.
 how to detect that in php?

答: You should do the comparison after the form is posted by fetching the data from the database and inserting new records as necessary. You also should use transactions to be sure of race conditions. If it is a critical system you have to perform extensive tests.</p>

ContentLicense: CC BY-SA 3.0

Title: textfield value changing detect in php

Body:
 <input name="aa" type="text" id="aa" value="please enter your name" size="22"            maxlength="60" />
 <input name="aab" type="text" id="aab" value="please enter your email" size="22"            maxlength="60" />

i have a textfield and it's value is "please enter your name"(likewise i have many fields.i want to add the value to the database only if the value is changed.(if user entered a name)

i used php isset function and it does not work properly.
 how to detect that in php?


问:
How to change the index of a vector element?
In JavaScript I would do this:

function move(arr, old_index, new_index) {
  while (old_index < 0) {
    old_index += arr.length;
  }
  while (new_index < 0) {
    new_index += arr.length;
  }
  if (new_index >= arr.length) {
    var k = new_index - arr.length;
    while ((k--) + 1) {
      arr.push(undefined);
    }
  }
  arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);
  return arr;
}
```

How can I accomplish the same thing in Rust?

I don't want to use insert and remove because my vector is a std::vec::Vec<std::string::String> and I want to literally move them to a different location in the vector, not remove them and then insert a copy.

I don't want to swap 2 elements.  I want to change the index of an element to an arbitrary other index, like a person cutting to some arbitrary other position in a queue.

答:
Thanks to SCappella for telling me that JavaScript Array.splice() does the same thing as Rust Vec.insert() and Vec.remove().  So I just went ahead and ported the function as literally as I could.

Thanks to John Kugelman for letting me know I can delete everything but the last 2 lines.

/* move is a reserved identifier */
fn move_(arr: &mut Vec<String>, old_index: usize, new_index: usize) {
    let removed = arr.remove(old_index);
    arr.insert(new_index, removed);
}
```

ContentLicense: CC BY-SA 4.0

Body:
In JavaScript I would do this:

function move(arr, old_index, new_index) {
  while (old_index < 0) {
    old_index += arr.length;
  }
  while (new_index < 0) {
    new_index += arr.length;
  }
  if (new_index >= arr.length) {
    var k = new_index - arr.length;
    while ((k--) + 1) {
      arr.push(undefined);
    }
  }
  arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);
  return arr;
}

How can I accomplish the same thing in Rust?

I don't want to use insert and remove because my vector is a std::vec::Vec<std::string::String> and I want to literally move them to a different location in the vector, not remove them and then insert a copy.

I don't want to swap 2 elements.  I want to change the index of an element to an arbitrary other index, like a person cutting to some arbitrary other position in a queue.


问:
Create json structure in Android
I'm trying to create a json structure like this in Android but cannot find any way to complete it.

```<code>{
  "FirstName": Fred,
  "LastName": "Poulsen",
  "Age": "18",
  "Phone": {
    "mobile": {}
  }
}
</code>```

This is what I have tried to do.

```<code>        Map<Object, Object> objectMap = new HashMap<>();
        Map<Object, Object> phone = new HashMap<>();

        objectMap.put("FirstName", "Fred");
        objectMap.put("LastName", "Poulsen");
        objectMap.put("Age", "18");
        objectMap.put("Phone", phone);
        input.put("mobile", body);
</code>```

答:
I guess the perfect structure will be :

```<code>    Map<Object, Object> phone = new HashMap<>();
    phone.put("mobile","1234567890");

    Map<Object, Object> objectMap = new HashMap<>();
    objectMap.put("FirstName", "Fred");
    objectMap.put("LastName", "Poulsen");
    objectMap.put("Age", "18");
    objectMap.put("Phone", phone);
</code>```

You can get mobile number using edittext.getText().toString().trim() and can add validation and then you can use this method easily.

Title: Create json structure in Android

Body:
I'm trying to create a json structure like this in Android but cannot find any way to complete it.

{
  "FirstName": Fred,
  "LastName": "Poulsen",
  "Age": "18",
  "Phone": {
    "mobile": {}
  }
}

This is what I have tried to do.

        Map<Object, Object> objectMap = new HashMap<>();
        Map<Object, Object> phone = new HashMap<>();

        objectMap.put("FirstName", "Fred");
        objectMap.put("LastName", "Poulsen");
        objectMap.put("Age", "18");
        objectMap.put("Phone", phone);
        input.put("mobile", body);

Body:
I guess the perfect structure will be :

    Map<Object, Object> phone = new HashMap<>();
    phone.put("mobile","1234567890");

    Map<Object, Object> objectMap = new HashMap<>();
    objectMap.put("FirstName", "Fred");
    objectMap.put("LastName", "Poulsen");
    objectMap.put("Age", "18");
    objectMap.put("Phone", phone);

You can get mobile number using edittext.getText().toString().trim() and can add validation and then you can use this method easily.


问:
Error while starting apache2 server in ubuntu
systemctl start apache2.service

Getting this error:-

Job for apache2.service failed because the control process exited with error code.
See "systemctl status apache2.service" and "journalctl -xe" for details.

Logs of systemctl status apache2.service

```<code>● apache2.service - The Apache HTTP Server
   Loaded: loaded (/lib/systemd/system/apache2.service; disabled; vendor preset: enabled)
  Drop-In: /lib/systemd/system/apache2.service.d
           └─apache2-systemd.conf
   Active: failed (Result: exit-code) since Tue 2020-06-02 08:24:55 IST; 49s ago
  Process: 9759 ExecStart=/usr/sbin/apachectl start (code=exited, status=127)

Jun 02 08:24:55 GS-4996 systemd[1]: Starting The Apache HTTP Server...
Jun 02 08:24:55 GS-4996 apachectl[9759]: /usr/sbin/apachectl: 174: /usr/sbin/apachectl: /usr/sbin/apache2: not found
Jun 02 08:24:55 GS-4996 apachectl[9759]: Action 'start' failed.
Jun 02 08:24:55 GS-4996 apachectl[9759]: The Apache error log may have more information.
Jun 02 08:24:55 GS-4996 systemd[1]: apache2.service: Control process exited, code=exited status=127
Jun 02 08:24:55 GS-4996 systemd[1]: apache2.service: Failed with result 'exit-code'.
Jun 02 08:24:55 GS-4996 systemd[1]: Failed to start The Apache HTTP Server.
</code>```

答: Can you please attach error logs or the output of  "systemctl status apache2.service"</p>

Body:
systemctl start apache2.service

Getting this error:-

Job for apache2.service failed because the control process exited with error code.
See "systemctl status apache2.service" and "journalctl -xe" for details.

Logs of systemctl status apache2.service

● apache2.service - The Apache HTTP Server
   Loaded: loaded (/lib/systemd/system/apache2.service; disabled; vendor preset: enabled)
  Drop-In: /lib/systemd/system/apache2.service.d
           └─apache2-systemd.conf
   Active: failed (Result: exit-code) since Tue 2020-06-02 08:24:55 IST; 49s ago
  Process: 9759 ExecStart=/usr/sbin/apachectl start (code=exited, status=127)

Jun 02 08:24:55 GS-4996 systemd[1]: Starting The Apache HTTP Server...
Jun 02 08:24:55 GS-4996 apachectl[9759]: /usr/sbin/apachectl: 174: /usr/sbin/apachectl: /usr/sbin/apache2: not found
Jun 02 08:24:55 GS-4996 apachectl[9759]: Action 'start' failed.
Jun 02 08:24:55 GS-4996 apachectl[9759]: The Apache error log may have more information.
Jun 02 08:24:55 GS-4996 systemd[1]: apache2.service: Control process exited, code=exited status=127
Jun 02 08:24:55 GS-4996 systemd[1]: apache2.service: Failed with result 'exit-code'.
Jun 02 08:24:55 GS-4996 systemd[1]: Failed to start The Apache HTTP Server.


问:
Flask: where to put static javascript files in templates
I'm developing a flask app with the following folder structure:

```<code>|-->flask_app.py
    |-->static
        |-->css
            |-->bootstrap.min.css
            |-->styles.css
        |-->js
            |-->jquery-3.1.1.min.js
            |-->bootstrap.min.js
            |-->script.js
    |-->templates
        |-->index.html
</code>```

What is the proper way to link to these css and js files in index.html and what parameters do I need associated with them?

My CSS links look like this and are located in the header:

```<code><link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">
</code>```

And my JS links look like this and are located at the end of the body tag:

```<code><script src="{{ url_for('static', filename='js/script.js') }}"></script>
</code>```

Is this the correct syntax? Are they located in the correct spots in my templates (I'm sure there's flexibility here)? And are there any other parameters I should pass in (e.g. type="text/css", type="text/javascript", media="screen")?

Everything is working as expected but I want to follow recommended practice if there is any.

答:
As the Flask documentation mentions, you should store .css and .js files within your static folder and for organizational purposes, its fine to have each type of file as subdirectories (especially as your app grows).

Per this SO answer, you don't need to have type="text/css" or type="text/javascript" in the jinja expression.

Body:
I'm developing a flask app with the following folder structure:

|-->flask_app.py
    |-->static
        |-->css
            |-->bootstrap.min.css
            |-->styles.css
        |-->js
            |-->jquery-3.1.1.min.js
            |-->bootstrap.min.js
            |-->script.js
    |-->templates
        |-->index.html

What is the proper way to link to these css and js files in index.html and what parameters do I need associated with them?

My CSS links look like this and are located in the header:

<link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">

And my JS links look like this and are located at the end of the body tag:

Is this the correct syntax? Are they located in the correct spots in my templates (I'm sure there's flexibility here)? And are there any other parameters I should pass in (e.g. type="text/css", type="text/javascript", media="screen")?

Everything is working as expected but I want to follow recommended practice if there is any.


问:
How to check programmatically if Gradle task has been scheduled to be executed?
I would like to enable a task dependency only if another task has been scheduled. How can I tell if a task has been scheduled to be executed?</p>

答:
Not exactly enabling a task dependency if another task has been scheduled, but using onlyIf has a similar effect:

```<code>task dependee

task depender {
  dependsOn: dependee
  onlyIf {
    dependee.doesWork
  }
}
</code>```

Body:
Not exactly enabling a task dependency if another task has been scheduled, but using onlyIf has a similar effect:

task dependee

task depender {
  dependsOn: dependee
  onlyIf {
    dependee.doesWork
  }
}


问:
Select minimum row and return the column name using R
```<code>df <- data.frame(PATIENT_ID=c(1,2,3,4,5,6,7),
             A=c(2,4,6,7,8,9,2),
             B=c(3,2,3,6,6,4,3),
             C=c(1,2,3,4,6,3,2))
</code>```

I want to create a variable named 'type', the value of the 'type' variable is the A,B,C's column name which has the min value. And if A=B=C, fill A, if B=C

So the output should be:

```<code>df <- data.frame(PATIENT_ID=c(1,2,3,4,5,6,7),
             A=c(2,4,6,7,8,9,2),
             B=c(3,2,3,6,6,4,3),
             C=c(1,2,3,4,6,3,2),
          type=c(C,B,B,C,B,C,A))
</code>```

答:
We can use max.col which returns the column number of maximum value in each row but since we want min value here we can negate it. In case of a tie first minimum value will be returned this can be specified via ties.method.

```<code>names(df)[-1][max.col(-df[-1], ties.method = 'first')]
#[1] "C" "B" "B" "C" "B" "C" "A"
</code>```

-1 here is to ignore the first column i.e PATIENT_ID.

We can also use apply :

```<code>names(df[-1])[apply(df[-1], 1, which.min)]
</code>```

You can select only specific columns by :

```<code>cols <- c('A', 'B', 'C')
cols[max.col(-df[cols], ties.method = 'first')]
</code>```

Or

```<code>cols[apply(df[cols], 1, which.min)]
</code>```

Body:
df <- data.frame(PATIENT_ID=c(1,2,3,4,5,6,7),
             A=c(2,4,6,7,8,9,2),
             B=c(3,2,3,6,6,4,3),
             C=c(1,2,3,4,6,3,2))

I want to create a variable named 'type', the value of the 'type' variable is the A,B,C's column name which has the min value. And if A=B=C, fill A, if B=C

So the output should be:

df <- data.frame(PATIENT_ID=c(1,2,3,4,5,6,7),
             A=c(2,4,6,7,8,9,2),
             B=c(3,2,3,6,6,4,3),
             C=c(1,2,3,4,6,3,2),
          type=c(C,B,B,C,B,C,A))

Body:
We can use max.col which returns the column number of maximum value in each row but since we want min value here we can negate it. In case of a tie first minimum value will be returned this can be specified via ties.method.

names(df)[-1][max.col(-df[-1], ties.method = 'first')]
#[1] "C" "B" "B" "C" "B" "C" "A"

-1 here is to ignore the first column i.e PATIENT_ID.

We can also use apply :

names(df[-1])[apply(df[-1], 1, which.min)]

You can select only specific columns by :

cols <- c('A', 'B', 'C')
cols[max.col(-df[cols], ties.method = 'first')]

Or

cols[apply(df[cols], 1, which.min)]


问:
PL/SQL call from JDBC resulting in "SQLSyntaxErrorException: ORA-00900"
I'm trying to use the following code to run a PL/SQL statement on my database server.

```<code>public class Main {
    public static void main(String[] args) {
        String jdbcURL = "jdbc:oracle:thin:@172.22.88.9:1521/xavier.i.com";

        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        String user = "bigdb";
        String password = "fakepassword";
        String result = null;
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
            conn = DriverManager.getConnection(jdbcURL, user, password);

            result = runStatement(conn,
              "{begin ANALYZE TABLE BIGDB.scr_fct_exact_access
              ESTIMATE STATISTICS; end}");

        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            ex.printStackTrace();
        }
    }

    private static String runStatement(Connection con, String statement)
      throws Exception {
        PreparedStatement cstmt = con.prepareStatement(statement);
        cstmt.execute(); // this is line 58
        cstmt.close();

        return count;
    }
}
</code>```

On running the code, I get the following exception:

java.sql.SQLSyntaxErrorException: ORA-00900: invalid SQL statement

at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:440)

          at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396)

          at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:837)

          at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:445)

          at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:191)

          at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:523)

          at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:207)

          at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:1010)Time : -1307015416548

at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1315)

          at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3576)

          at oracle.jdbc.driver.OraclePreparedStatement.execute(OraclePreparedStatement.java:3677)

          at oracle.jdbc.driver.OraclePreparedStatementWrapper.execute(OraclePreparedStatementWrapper.java:1374)

          at Main.prepareStatement(Main.java:58)

          at Main.main(Main.java:29)

What is going wrong, and how can I fix it?

答:
Use CallableStatement instead of PreparedStatement to run statements with the PL/SQL block syntax from JDBC.

However, as Codo has stated in the other answer, ANALYZE TABLE isn't exactly callable from PL/SQL. It is a SQL command, and hence cannot be executed in a PL/SQL block. And as rightly suggested, DBMS_STATS ought to be used. This is also stated in the documentation of the ANALYZE command:

Note:

For the collection of most
  statistics, use the DBMS_STATS
  package, which lets you collect
  statistics in parallel, collect global
  statistics for partitioned objects,
  and fine tune your statistics
  collection in other ways. See Oracle
  Database PL/SQL Packages and Types
  Reference for more information on the
  DBMS_STATS package. Use the ANALYZE
  statement (rather than DBMS_STATS) for
  statistics collection not related to
  the cost-based optimizer:

To use the VALIDATE or LIST CHAINED
  ROWS clauses

To collect information on freelist
  blocks

If you really want to avoid using DBMS_STATS (and honestly, I wouldn't see a good reason to avoid it), use EXECUTE IMMEDIATE or DBMS_SQL to execute the ANALYZE TABLE command.

Body:
I'm trying to use the following code to run a PL/SQL statement on my database server.

public class Main {
    public static void main(String[] args) {
        String jdbcURL = "jdbc:oracle:thin:@172.22.88.9:1521/xavier.i.com";

        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        String user = "bigdb";
        String password = "fakepassword";
        String result = null;
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
            conn = DriverManager.getConnection(jdbcURL, user, password);

            result = runStatement(conn,
              "{begin ANALYZE TABLE BIGDB.scr_fct_exact_access
              ESTIMATE STATISTICS; end}");

        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            ex.printStackTrace();
        }
    }

    private static String runStatement(Connection con, String statement)
      throws Exception {
        PreparedStatement cstmt = con.prepareStatement(statement);
        cstmt.execute(); // this is line 58
        cstmt.close();

        return count;
    }
}

On running the code, I get the following exception:

java.sql.SQLSyntaxErrorException: ORA-00900: invalid SQL statement

at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:440)

          at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396)

          at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:837)

          at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:445)

          at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:191)

          at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:523)

          at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:207)

          at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:1010)Time : -1307015416548

at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1315)

          at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3576)

          at oracle.jdbc.driver.OraclePreparedStatement.execute(OraclePreparedStatement.java:3677)

          at oracle.jdbc.driver.OraclePreparedStatementWrapper.execute(OraclePreparedStatementWrapper.java:1374)

          at Main.prepareStatement(Main.java:58)

          at Main.main(Main.java:29)

What is going wrong, and how can I fix it?


问:
How to fix endless axios request?
I'm building a Spotify web app now using its API. I'm making a get request to get album data of a specific artist. When I try the code below, handleClick is called endlessly in Albums.js. Does it have to do with asynchronous?

Albums.js

```<code>import React, { Component } from "react";
import { useParams } from "react-router-dom";
import axios from "axios";
import AlbumCard from "./AlbumCard";

export class Albums extends Component {
  constructor(props) {
    super(props);

    this.state = { albums: [] };
    this.handleClick = this.handleClick.bind(this);
  }

  async handleClick() {
    const {
      match: { params },
    } = this.props;
    console.log(params.id);
    try {
      const res = await axios.get(
        `http://localhost:4000/albums/${encodeURIComponent(params.id)}`,
        {
          params: {
            id: params.id,
          },
        }
      );
      console.log(`Returned album data from the server: ${res}`);
      this.setState({ albums: res.data });
    } catch (err) {
      //   .catch((err) => console.log(err));
      console.log(err);
    }
  }

  render() {
    return (
      <>
        <div className="container" style={{ color: "white" }}>
          {/* {`${id}'s albums`} */}
          {console.log(this.handleClick())}
          {console.log(this.state.albums)}
        </div>
      </>
    );
  }
}

export default Albums;

</code>```

server.js

```<code>
app.get("/albums/:id", (req, res) => {
  console.log(req.params.id);
  spotifyApi.getArtistAlbums(req.params.id).then(function (data) {
    console.log(data.body.items);
    res.json(data.body.items);
    res.end();
  });
});

</code>```

答:
No, it has to do with you calling handleClick inside render.

Inside your handleClick, you call setState and when state is set render is called and then handleClick is called again, which sets the state again, which causes render to be called again etc.

You probably meant to set handleClick as an event handler on a button inside render

So, the following would NOT cause an endless loop and would probably be closer to what you actually wanted to do

render() {
    return (
      <>

          <button onClick={this.handleClick}>Click me</button>
          {console.log(this.state.albums)}

      </>
    );
  }
```

Title: How to fix endless axios request?

Body:
I'm building a Spotify web app now using its API. I'm making a get request to get album data of a specific artist. When I try the code below, handleClick is called endlessly in Albums.js. Does it have to do with asynchronous?

Albums.js

import React, { Component } from "react";
import { useParams } from "react-router-dom";
import axios from "axios";
import AlbumCard from "./AlbumCard";

export class Albums extends Component {
  constructor(props) {
    super(props);

    this.state = { albums: [] };
    this.handleClick = this.handleClick.bind(this);
  }

  async handleClick() {
    const {
      match: { params },
    } = this.props;
    console.log(params.id);
    try {
      const res = await axios.get(
        `http://localhost:4000/albums/${encodeURIComponent(params.id)}`,
        {
          params: {
            id: params.id,
          },
        }
      );
      console.log(`Returned album data from the server: ${res}`);
      this.setState({ albums: res.data });
    } catch (err) {
      //   .catch((err) => console.log(err));
      console.log(err);
    }
  }

  render() {
    return (
      <>

          {/* {`${id}'s albums`} */}
          {console.log(this.handleClick())}
          {console.log(this.state.albums)}

      </>
    );
  }
}

export default Albums;

server.js

app.get("/albums/:id", (req, res) => {
  console.log(req.params.id);
  spotifyApi.getArtistAlbums(req.params.id).then(function (data) {
    console.log(data.body.items);
    res.json(data.body.items);
    res.end();
  });
});

Body:
No, it has to do with you calling handleClick inside render.

Inside your handleClick, you call setState and when state is set render is called and then handleClick is called again, which sets the state again, which causes render to be called again etc.

You probably meant to set handleClick as an event handler on a button inside render

So, the following would NOT cause an endless loop and would probably be closer to what you actually wanted to do

render() {
    return (
      <>
        <div className="container" style={{ color: "white" }}>
          <button onClick={this.handleClick}>Click me</button>
          {console.log(this.state.albums)}
        </div>
      </>
    );
  }


问:
Drag and drop multiple files by filter into listview
I'm currently have this code to store data to listview
I have to store first the info to textbox lines and then store them to listview.

Is there easy way without storing first textbox and directly put the files into listview?
What I want is to drag and drop or browse the multiple video ts file in the first column and then the srt in the sub column.
hope that you know what I mean. I'm rally new in listview

```<code>Sub AddToListView()
    LV.Items.Clear()
    Dim vn = vName.Lines
    Dim sn = sName.Lines
    Dim vp = vPath.Lines
    Dim sp = sPath.Lines

    Dim items As New List(Of ListViewItem)

    Dim upper = {vn.GetUpperBound(0), sn.GetUpperBound(0), vp.GetUpperBound(0), sp.GetUpperBound(0)}
    For I = 0 To upper.Min
        items.Add(New ListViewItem({vn(I), sn(I), vp(I), sp(I)}))
    Next
    LV.BeginUpdate()
    LV.Items.AddRange(items.ToArray())
    SortItems()
    LV.EndUpdate()
    AddToParam()
End Sub

Sub readFiles()
    Dim folder As String = txtinputFolder.Text
    Dim sb1 As New StringBuilder
    Dim sb2 As New StringBuilder
    Dim sb3 As New StringBuilder
    Dim sb4 As New StringBuilder

    For Each item In My.Computer.FileSystem.GetFiles(folder, FileIO.SearchOption.SearchTopLevelOnly, "*.ts")
        sb1.Append(item & vbNewLine)
    Next
    vPath.Text = ""
    vPath.Text = sb1.ToString.Trim

    For Each file As String In My.Computer.FileSystem.GetFiles(folder, FileIO.SearchOption.SearchTopLevelOnly, "*.ts")
        sb2.Append(Path.GetFileName(file) & vbNewLine)
    Next
    vName.Text = ""
    vName.Text = sb2.ToString.Trim

    For Each file As String In My.Computer.FileSystem.GetFiles(folder, FileIO.SearchOption.SearchTopLevelOnly, "*.srt")
        sb3.Append(Path.GetFileName(file) & vbNewLine)
    Next
    sName.Text = ""
    sName.Text = sb3.ToString.Trim

    For Each item3 In My.Computer.FileSystem.GetFiles(folder, FileIO.SearchOption.SearchTopLevelOnly, "*.srt")
        sb4.Append(item3 & vbNewLine)
    Next
    sPath.Text = ""
    sPath.Text = sb4.ToString.Trim
End Sub
</code>```

答:
You could try something like this:

```<code>Sub AddToListView(vNames As String(), sNames As String(), vPaths As String(), sPaths As String())
    LV.Items.Clear()

    Dim items As New List(Of ListViewItem)
    Dim upperBounds = {vNames.GetUpperBound(0), sNames.GetUpperBound(0), vPaths.GetUpperBound(0), sPaths.GetUpperBound(0)}

    For i = 0 To upperBounds.Min
        items.Add(New ListViewItem({vNames(i), sNames(i), vPaths(i), sPaths(i)}))
    Next

    LV.BeginUpdate()
    LV.Items.AddRange(items.ToArray())
    SortItems()
    LV.EndUpdate()
    AddToParam()
End Sub

Sub readFiles()
    Dim folder As String = txtinputFolder.Text
    Dim vPaths As New List(Of String)
    Dim vNames As New List(Of String)
    Dim sPaths As New List(Of String)
    Dim sNames As New List(Of String)

    For Each filePath In Directory.EnumerateFiles(folder, "*.ts")
        vPaths.Add(filePath)
        vNames.Add(Path.GetFileName(filePath))
    Next

    For Each filePath In Directory.EnumerateFiles(folder, "*.srt")
        sPaths.Add(filePath)
        sNames.Add(Path.GetFileName(filePath))
    Next

    AddToListView(vNames.ToArray(), sNames.ToArray(), vPaths.ToArray(), sPaths.ToArray())
End Sub
</code>```

If you don't want readFiles calling AddToListView, you could use fields to store the data rather than local variables, or you could have readFields return the data in a Tuple or some dedicated object.

This seems like a reasonable answer based on the code provided and the actual question asked but it has nothing to do with drag and drop, so I'm not sure whether I'm missing something or you are.

Body:
I'm currently have this code to store data to listview
I have to store first the info to textbox lines and then store them to listview.

Is there easy way without storing first textbox and directly put the files into listview?
What I want is to drag and drop or browse the multiple video ts file in the first column and then the srt in the sub column.
hope that you know what I mean. I'm rally new in listview

Sub AddToListView()
    LV.Items.Clear()
    Dim vn = vName.Lines
    Dim sn = sName.Lines
    Dim vp = vPath.Lines
    Dim sp = sPath.Lines

    Dim items As New List(Of ListViewItem)

    Dim upper = {vn.GetUpperBound(0), sn.GetUpperBound(0), vp.GetUpperBound(0), sp.GetUpperBound(0)}
    For I = 0 To upper.Min
        items.Add(New ListViewItem({vn(I), sn(I), vp(I), sp(I)}))
    Next
    LV.BeginUpdate()
    LV.Items.AddRange(items.ToArray())
    SortItems()
    LV.EndUpdate()
    AddToParam()
End Sub

Sub readFiles()
    Dim folder As String = txtinputFolder.Text
    Dim sb1 As New StringBuilder
    Dim sb2 As New StringBuilder
    Dim sb3 As New StringBuilder
    Dim sb4 As New StringBuilder

    For Each item In My.Computer.FileSystem.GetFiles(folder, FileIO.SearchOption.SearchTopLevelOnly, "*.ts")
        sb1.Append(item & vbNewLine)
    Next
    vPath.Text = ""
    vPath.Text = sb1.ToString.Trim

    For Each file As String In My.Computer.FileSystem.GetFiles(folder, FileIO.SearchOption.SearchTopLevelOnly, "*.ts")
        sb2.Append(Path.GetFileName(file) & vbNewLine)
    Next
    vName.Text = ""
    vName.Text = sb2.ToString.Trim

    For Each file As String In My.Computer.FileSystem.GetFiles(folder, FileIO.SearchOption.SearchTopLevelOnly, "*.srt")
        sb3.Append(Path.GetFileName(file) & vbNewLine)
    Next
    sName.Text = ""
    sName.Text = sb3.ToString.Trim

    For Each item3 In My.Computer.FileSystem.GetFiles(folder, FileIO.SearchOption.SearchTopLevelOnly, "*.srt")
        sb4.Append(item3 & vbNewLine)
    Next
    sPath.Text = ""
    sPath.Text = sb4.ToString.Trim
End Sub

Body:
You could try something like this:

Sub AddToListView(vNames As String(), sNames As String(), vPaths As String(), sPaths As String())
    LV.Items.Clear()

    Dim items As New List(Of ListViewItem)
    Dim upperBounds = {vNames.GetUpperBound(0), sNames.GetUpperBound(0), vPaths.GetUpperBound(0), sPaths.GetUpperBound(0)}

    For i = 0 To upperBounds.Min
        items.Add(New ListViewItem({vNames(i), sNames(i), vPaths(i), sPaths(i)}))
    Next

    LV.BeginUpdate()
    LV.Items.AddRange(items.ToArray())
    SortItems()
    LV.EndUpdate()
    AddToParam()
End Sub

Sub readFiles()
    Dim folder As String = txtinputFolder.Text
    Dim vPaths As New List(Of String)
    Dim vNames As New List(Of String)
    Dim sPaths As New List(Of String)
    Dim sNames As New List(Of String)

    For Each filePath In Directory.EnumerateFiles(folder, "*.ts")
        vPaths.Add(filePath)
        vNames.Add(Path.GetFileName(filePath))
    Next

    For Each filePath In Directory.EnumerateFiles(folder, "*.srt")
        sPaths.Add(filePath)
        sNames.Add(Path.GetFileName(filePath))
    Next

    AddToListView(vNames.ToArray(), sNames.ToArray(), vPaths.ToArray(), sPaths.ToArray())
End Sub

If you don't want readFiles calling AddToListView, you could use fields to store the data rather than local variables, or you could have readFields return the data in a Tuple or some dedicated object.

This seems like a reasonable answer based on the code provided and the actual question asked but it has nothing to do with drag and drop, so I'm not sure whether I'm missing something or you are.


问:
Moving image on click in R with gganimate
I just started using the awesome gganimate package, and I managed to create a pretty cool animated gif.
However, I would like the image to move from one state to another on click, not automatically. Is there a way to do that with the gganimate package or with another package?

Thank you,

Sarah

答:
I am 2 short of reputations for commenting hence answering directly, otherwise would have asked for data & code, nevertheless I'll try to answer based on understanding from the linked gif.

Since the main aim of gganimate is to create animations which are simply stitched frames from ggplot output, so to my knowledge there is no option to have a click functionality directly.

This would require a package which has capability for interactive graphics, hence plotly is best option. Not trying to demean gganimate (I am myself a big fan of it).

library(plotly)
library(ggplot2)

df <- data.frame(Dim1 = runif(100,-200,200), Dim2 = rpois(100,5),
                 Timepoint = rep(c("PRE","4WP"),50), pop = runif(100,1,10))

gg <- ggplot(df, aes(Dim1, Dim2)) +
  geom_point(aes(size = pop, frame = Timepoint))

ggplotly(gg) %>%
  animation_opts(
    frame = 1000,
    transition = 1000,
    easing = "linear",
    redraw = TRUE,
    mode = "immediate"
  )
```

<p>you can try more <code>easing</code> options from plotly/animation_attributes.js.
This will directly create a interactive plot:
<img src="https://i.stack.imgur.com/TxfLE.gif" alt="plotly"><br>
Another option would be to use same animations from <code>gganimate</code> by first saving each frame generated by it in file system using: (as I dont know how you are creating your animation I will create a basic one)</p>

```p <- gg + transition_states(Timepoint, transition_length = 100, state_length = 5)
animate(p, renderer = file_renderer(prefix = "gganim_plot", overwrite = TRUE))
```

which can then be fed into saveHTML command of animation R package.

Body:
I am 2 short of reputations for commenting hence answering directly, otherwise would have asked for data & code, nevertheless I'll try to answer based on understanding from the linked gif.

Since the main aim of gganimate is to create animations which are simply stitched frames from ggplot output, so to my knowledge there is no option to have a click functionality directly.

This would require a package which has capability for interactive graphics, hence plotly is best option. Not trying to demean gganimate (I am myself a big fan of it).

library(plotly)
library(ggplot2)

df <- data.frame(Dim1 = runif(100,-200,200), Dim2 = rpois(100,5),
                 Timepoint = rep(c("PRE","4WP"),50), pop = runif(100,1,10))

gg <- ggplot(df, aes(Dim1, Dim2)) +
  geom_point(aes(size = pop, frame = Timepoint))

ggplotly(gg) %>%
  animation_opts(
    frame = 1000,
    transition = 1000,
    easing = "linear",
    redraw = TRUE,
    mode = "immediate"
  )

you can try more easing options from plotly/animation_attributes.js.
This will directly create a interactive plot:

Another option would be to use same animations from gganimate by first saving each frame generated by it in file system using: (as I dont know how you are creating your animation I will create a basic one)

p <- gg + transition_states(Timepoint, transition_length = 100, state_length = 5)
animate(p, renderer = file_renderer(prefix = "gganim_plot", overwrite = TRUE))

which can then be fed into saveHTML command of animation R package.


答:
You are calling the handleClick inside render method (in console.log).

So here is the flow:

component is rendered and handleClick is called and you set state

component is re-rendered and handleClick is called again and you set state

component is re-rendered .... and so on

So have a button and provide a reference of handleClick to onClick event

  {/* {`${id}'s albums`} */}
  {/* {console.log(this.handleClick())} //<---don't do this */}
  <button onClick={handleClick}>click me</button>
  {console.log(this.state.albums)}

;
```

Title: How to fix endless axios request?

Body:
You are calling the handleClick inside render method (in console.log).

So here is the flow:

component is rendered and handleClick is called and you set state

component is re-rendered and handleClick is called again and you set state

component is re-rendered .... and so on

So have a button and provide a reference of handleClick to onClick event

<div className="container" style={{ color: "white" }}>
  {/* {`${id}'s albums`} */}
  {/* {console.log(this.handleClick())} //<---don't do this */}
  <button onClick={handleClick}>click me</button>
  {console.log(this.state.albums)}
</div>;


问:
Exclude architectural services from being processed by aspect
I'm creating an aspect to wrap my services but I'm also defining some services under the package

```<code>com.foo.arch
</code>```

My application classes will be instead under

```<code>com.foo
</code>```

Please notice that arch is a subpackage of com.foo but I can't put the "arch" keyword before.Isn't there a pointcut expression to say:

All classess under com.foo not having "arch" as third package?

答:
Consider an interface SampleService

  public interface SampleService {
        void test();
    }
```

<p>and has 3 implementations in these three package</p>

<pre class="lang-java prettyprint-override"><code>com

com.foo

com.foo.arch
</code>```

an aspect to exclude arch package and only advice classes under com and com.foo would be as follows

@Component
@Aspect
public class ExcludeAspect {

    @Around("execution(* test()) && !within(com.foo.arch.*)")
    public void adviceTestMethod(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("Adviced");
        pjp.proceed();
    }
}
```

Reference :
within

Combining Pointcut Expressions

Hope this helps

Body:
I'm creating an aspect to wrap my services but I'm also defining some services under the package

com.foo.arch

My application classes will be instead under

com.foo

Please notice that arch is a subpackage of com.foo but I can't put the "arch" keyword before.Isn't there a pointcut expression to say:

All classess under com.foo not having "arch" as third package?

Body:
Consider an interface SampleService

  public interface SampleService {
        void test();
    }

and has 3 implementations in these three package

com

com.foo

com.foo.arch

an aspect to exclude arch package and only advice classes under com and com.foo would be as follows

@Component
@Aspect
public class ExcludeAspect {

    @Around("execution(* test()) && !within(com.foo.arch.*)")
    public void adviceTestMethod(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("Adviced");
        pjp.proceed();
    }
}

Reference :
within

Combining Pointcut Expressions

Hope this helps


问:
How do I cast a JSON Object to a TypeScript class?
I read a JSON object from a remote REST server. This JSON object has all the properties of a typescript class (by design). How do I cast that received JSON object to a type var?

I don't want to populate a typescript var (ie have a constructor that takes this JSON object). It's large and copying everything across sub-object by sub-object & property by property would take a lot of time.

Update: You can however cast it to a typescript interface!

答:
Personally I find it appalling that typescript does not allow an endpoint definition to specify
the type of the object being received.  As it appears that this is indeed the case,
I would do what I have done with other languages, and that is that I would separate the JSON object from the class definition,
and have the class definition use the JSON object as its only data member.

I despise boilerplate code, so for me it is usually a matter of getting to the desired result with the least amount of code while preserving type.

Consider the following JSON object structure definitions - these would be what you would receive at an endpoint, they are structure definitions only, no methods.

```<code>interface IAddress {
    street: string;
    city: string;
    state: string;
    zip: string;
}

interface IPerson {
    name: string;
    address: IAddress;
}
</code>```

If we think of the above in object oriented terms, the above interfaces are not classes because they only define a data structure.
A class in OO terms defines data and the code that operates on it.

So we now define a class that specifies data and the code that operates on it...

```<code>class Person {
    person: IPerson;

    constructor(person: IPerson) {
        this.person = person;
    }

    // accessors
    getName(): string {
        return person.name;
    }

    getAddress(): IAddress {
        return person.address;
    }

    // You could write a generic getter for any value in person,
    // no matter how deep, by accepting a variable number of string params

    // methods
    distanceFrom(address: IAddress): float {
        // Calculate distance from the passed address to this persons IAddress
        return 0.0;
    }
}
</code>```

And now we can simply pass in any object conforming to the IPerson structure and be on our way...

```<code>   Person person = new Person({
            name: "persons name",
            address: {
                street: "A street address",
                city: "a city",
                state: "a state",
                zip: "A zipcode"
            }
        });
</code>```

In the same fashion we can now process the object received at your endpoint with something along the lines of...

```<code>Person person = new Person(req.body);    // As in an object received via a POST call

person.distanceFrom({ street: "Some street address", etc.});
</code>```

This is much more performant and uses half the memory of copying the data, while significantly reducing the amount of boilerplate code you must write for each entity type.
It simply relies on the type safety provided by TypeScript.

Body:
Personally I find it appalling that typescript does not allow an endpoint definition to specify
the type of the object being received.  As it appears that this is indeed the case,
I would do what I have done with other languages, and that is that I would separate the JSON object from the class definition,
and have the class definition use the JSON object as its only data member.

I despise boilerplate code, so for me it is usually a matter of getting to the desired result with the least amount of code while preserving type.

Consider the following JSON object structure definitions - these would be what you would receive at an endpoint, they are structure definitions only, no methods.

interface IAddress {
    street: string;
    city: string;
    state: string;
    zip: string;
}

interface IPerson {
    name: string;
    address: IAddress;
}

If we think of the above in object oriented terms, the above interfaces are not classes because they only define a data structure.
A class in OO terms defines data and the code that operates on it.

So we now define a class that specifies data and the code that operates on it...

class Person {
    person: IPerson;

    constructor(person: IPerson) {
        this.person = person;
    }

    // accessors
    getName(): string {
        return person.name;
    }

    getAddress(): IAddress {
        return person.address;
    }

    // You could write a generic getter for any value in person,
    // no matter how deep, by accepting a variable number of string params

    // methods
    distanceFrom(address: IAddress): float {
        // Calculate distance from the passed address to this persons IAddress
        return 0.0;
    }
}

And now we can simply pass in any object conforming to the IPerson structure and be on our way...

   Person person = new Person({
            name: "persons name",
            address: {
                street: "A street address",
                city: "a city",
                state: "a state",
                zip: "A zipcode"
            }
        });

In the same fashion we can now process the object received at your endpoint with something along the lines of...

Person person = new Person(req.body);    // As in an object received via a POST call

person.distanceFrom({ street: "Some street address", etc.});

This is much more performant and uses half the memory of copying the data, while significantly reducing the amount of boilerplate code you must write for each entity type.
It simply relies on the type safety provided by TypeScript.


答:
You are requesting the API in the render(), that is why it is endless.

```<code>export class Albums extends Component {
  constructor(props) {
    super(props);

    this.state = { albums: [] };
    this.handleClick = this.handleClick.bind(this);
  }

  componentDidMount(){
    this.handleClick() // I don't know why its name is `handleClick`.
  }
  ...

  render() {
    return (
      <>
        <div className="container" style={{ color: "white" }}>
          <button onClick={handleClick}>Click</button>
          {/* {`${id}'s albums`} */}
          {/* console.log(this.handleClick()) */} /* should be removed */
          {console.log(this.state.albums)}
        </div>
      </>
    );
  }
}
</code>```

Title: How to fix endless axios request?

Body:
You are requesting the API in the render(), that is why it is endless.

export class Albums extends Component {
  constructor(props) {
    super(props);

    this.state = { albums: [] };
    this.handleClick = this.handleClick.bind(this);
  }

  componentDidMount(){
    this.handleClick() // I don't know why its name is `handleClick`.
  }
  ...

  render() {
    return (
      <>
        <div className="container" style={{ color: "white" }}>
          <button onClick={handleClick}>Click</button>
          {/* {`${id}'s albums`} */}
          {/* console.log(this.handleClick()) */} /* should be removed */
          {console.log(this.state.albums)}
        </div>
      </>
    );
  }
}


问:
Is there a simple way to remove one dependency from the local gradle cache?
The local gradle cache stores copies of maven/gradle dependencies. How to clear gradle cache? covers how to clear the whole cache, but not individual packages.

Is there a simple way to remove one package from the local gradle cache? This would be useful, for example, when actively developing a library. To test a minor library change, I currently have to clear the entire cache from the filesystem so an old cached version of the library is not used.

I understand it is also possible to use the gradle ResolutionStrategy described in How can I force gradle to redownload dependencies?. I would prefer not to change the gradle configuration because most of the time and for most developers, the default caching behavior is fine.

答:
Works great, but for newer versions of gradle, use this instead:</p>

```<code>task seekAndDestroy{
    doLast {
        configurations.findanddelete.each{
            println 'Deleting: '+ it
            delete it.parent
        }
    }
}
</code>```

Body:
Works great, but for newer versions of gradle, use this instead:

task seekAndDestroy{
    doLast {
        configurations.findanddelete.each{
            println 'Deleting: '+ it
            delete it.parent
        }
    }
}


问:
How to end java program
Do I have to add some exit statement?

Code seems to be running well, but after it finish its task I still can't interact with console.

```<code>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package excelb;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.JFrame;

/**
 *
 * @author hp
 */
public class Excelb {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws FileNotFoundException, IOException {
        // TODO code application logic here
        String row;
        String row2;
        File fn = null;
        int counter = 0;

        Scanner in = new Scanner(System.in);
        System.out.println("Enter the run identifier for output file");
        String output = in.nextLine();

        //input
        JFileChooser jFileChooser = new JFileChooser();
        jFileChooser.setCurrentDirectory(new File("C:/"));

        int result = jFileChooser.showOpenDialog(new JFrame());

        if (result == JFileChooser.APPROVE_OPTION) {
             fn=jFileChooser.getSelectedFile();
            System.out.println("Data file: " + fn.getAbsolutePath());
            //System.out.println("Data file: " + fn.getTitle());
        }

        BufferedReader csvReader = new BufferedReader(new FileReader("Keywords.csv"));
        BufferedReader csvReader2 = new BufferedReader(new FileReader(fn.getAbsolutePath()));

        row = csvReader.readLine();
        String[] data = row.split(",");
        while (counter < data.length) {
            while ((row2 = csvReader2.readLine()) != null) {
                String[] data2 = row2.split(",");
                for (int j = 0; j < data.length; j++) {
                    if ((data2[data2.length - 1].contains(data[j]))) {
                        //DateFormat df = new SimpleDateFormat("dd/MM/yy");
                        //Date dateobj = new Date();
                        //String d = df.format(dateobj);
                        //d = d.replaceAll("/", "");
                        String newFile = data[j] + "_" + output + ".csv";
                        FileWriter csvWriter = new FileWriter(newFile, true);
                        for (int i = 0; i < data2.length; i++) {
                           csvWriter.append(data2[i]);
                            csvWriter.append(",");
                        }
                        csvWriter.append("\n");
                        csvWriter.close();
                    }
                }
            }
            counter++;
        }
        System.out.println("Finished");
        csvReader.close();
        csvReader2.close();
    }

}
</code>```

答:
Pshemo's answer explains why your app isn't ending.

But it does fail to make the key point, which is:

To exit a Java app, run System.exit(0); - and consider returning a non-0 value if errors occurred. Don't wait for the JVM to exit itself (it does do so, once the only remaining live threads have the daemon flag set) - that's a frail strategy if the point is to close the app. Just call exit.

Title: How to end java program

Body:
Do I have to add some exit statement?

Code seems to be running well, but after it finish its task I still can't interact with console.

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package excelb;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.JFrame;

/**
 *
 * @author hp
 */
public class Excelb {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws FileNotFoundException, IOException {
        // TODO code application logic here
        String row;
        String row2;
        File fn = null;
        int counter = 0;

        Scanner in = new Scanner(System.in);
        System.out.println("Enter the run identifier for output file");
        String output = in.nextLine();

        //input
        JFileChooser jFileChooser = new JFileChooser();
        jFileChooser.setCurrentDirectory(new File("C:/"));

        int result = jFileChooser.showOpenDialog(new JFrame());

        if (result == JFileChooser.APPROVE_OPTION) {
             fn=jFileChooser.getSelectedFile();
            System.out.println("Data file: " + fn.getAbsolutePath());
            //System.out.println("Data file: " + fn.getTitle());
        }

        BufferedReader csvReader = new BufferedReader(new FileReader("Keywords.csv"));
        BufferedReader csvReader2 = new BufferedReader(new FileReader(fn.getAbsolutePath()));

        row = csvReader.readLine();
        String[] data = row.split(",");
        while (counter < data.length) {
            while ((row2 = csvReader2.readLine()) != null) {
                String[] data2 = row2.split(",");
                for (int j = 0; j < data.length; j++) {
                    if ((data2[data2.length - 1].contains(data[j]))) {
                        //DateFormat df = new SimpleDateFormat("dd/MM/yy");
                        //Date dateobj = new Date();
                        //String d = df.format(dateobj);
                        //d = d.replaceAll("/", "");
                        String newFile = data[j] + "_" + output + ".csv";
                        FileWriter csvWriter = new FileWriter(newFile, true);
                        for (int i = 0; i < data2.length; i++) {
                           csvWriter.append(data2[i]);
                            csvWriter.append(",");
                        }
                        csvWriter.append("\n");
                        csvWriter.close();
                    }
                }
            }
            counter++;
        }
        System.out.println("Finished");
        csvReader.close();
        csvReader2.close();
    }

}


问:
Change appended td by condition inside loop
I am appending rows and columns to a table using javascript. But I need one of the classname inside the td to somethings else based on the condition inside a `$.post() response.

I did this:

```<code>let arr = ['Hermione', 'Ron', 'Harry']

arr.forEach(d=>{
    $('#the_table>tbody').append(`
                <tr id='tr_${d}'>
                    <td'>${d}</td>
                    <td><i id='change' class='no'></i></td>
                </tr>
            `);
});

const myfunc = () => {
$.post(api, json_object,
    function(data, status) {
        if (data.value === 'started') {
        setTimeout(myfunc, 5000);
    } else {
        $('#change').removeClass('no').addClass('yes');
        }
}, 'json');
            }
myfunc();
</code>```

When I do this, it is only changing the value for the first value (Hermione). But in the console.log, I can see that the data.value is not started so it should've changed to yes.

Hoe can I change it to yes for each of the rows once the condition has been passed

答:
```<code>$('#change').removeClass('no').addClass('yes');
</code>```

you need to fix this selector $('#change')

i dont know if the api return has id

but you need to select it like this

```<code>$(`tr#${data.something} #change`)
</code>```

Body:
I am appending rows and columns to a table using javascript. But I need one of the classname inside the td to somethings else based on the condition inside a `$.post() response.

I did this:

let arr = ['Hermione', 'Ron', 'Harry']

arr.forEach(d=>{
    $('#the_table>tbody').append(`

                    ${d}

            `);
});

const myfunc = () => {
$.post(api, json_object,
    function(data, status) {
        if (data.value === 'started') {
        setTimeout(myfunc, 5000);
    } else {
        $('#change').removeClass('no').addClass('yes');
        }
}, 'json');
            }
myfunc();

When I do this, it is only changing the value for the first value (Hermione). But in the console.log, I can see that the data.value is not started so it should've changed to yes.

Hoe can I change it to yes for each of the rows once the condition has been passed

Body:
$('#change').removeClass('no').addClass('yes');

you need to fix this selector $('#change')

i dont know if the api return has id

but you need to select it like this

$(`tr#${data.something} #change`)


问:
Angular 9: Scoping Issues Using Named Functions as Arguments for then(), listen(), and subscribe()
Having some trouble understanding why I'm having scoping issues.

When using functions defined inside of then(), everything works fine:

import GoogleAuth = gapi.auth2.GoogleAuth;
import GoogleUser = gapi.auth2.GoogleUser;

@Injectable()
export class MyService {
  constructor() { }

  private googleAuth: GoogleAuth = undefined;
  private clientConfig = { ... };

  public init(): void {
    gapi.load('auth2', () => {
      gapi.auth2.init(this.clientConfig)
        .then((response: GoogleAuth) => {
          this.googleAuth = response;
      });
    });
  }
}
```
<p>But, when I try to use a named function as argument for then(), I get an error (next to line in code):</p>
<pre class="lang-js prettyprint-override"><code>import GoogleAuth = gapi.auth2.GoogleAuth;
import GoogleUser = gapi.auth2.GoogleUser;

@Injectable()
export class MyService {
  constructor() { }

  private googleAuth: GoogleAuth = undefined;
  private clientConfig = { ... };

  private onInit(response: GoogleAuth): void {
    console.log(this); // undefined
    this.googleAuth = response; // Cannot read property 'googleAuth' of undefined
  }

  public init(): void {
    gapi.load('auth2', () => {
      gapi.auth2.init(this.clientConfig)
        .then(this.onInit);
    });
  }
}
</code>```

I thought at first it was because I assigned undefined as the value for "googleAuth", but even if I run "console.log(this);" inside of "onInit", undefined is what appears in the console. If I were to call the method manually and pass the expected parameters, it has no trouble seeing "this" and "this.googleAuth". I have the exact same issues when using listen() and subscribe().

How can I fix this issue?

答:
The way you passed in the function this.onInit to then, you looses the context. Proper way to do it is

    public init(): void {
      gapi.load('auth2', () => {
        gapi.auth2.init(this.clientConfig)
          .then((resp) => this.onInit(resp));
        });
    }
```

Note the use of fat arrow function.

Body:
Having some trouble understanding why I'm having scoping issues.

When using functions defined inside of then(), everything works fine:

import GoogleAuth = gapi.auth2.GoogleAuth;
import GoogleUser = gapi.auth2.GoogleUser;

@Injectable()
export class MyService {
  constructor() { }

  private googleAuth: GoogleAuth = undefined;
  private clientConfig = { ... };

  public init(): void {
    gapi.load('auth2', () => {
      gapi.auth2.init(this.clientConfig)
        .then((response: GoogleAuth) => {
          this.googleAuth = response;
      });
    });
  }
}

But, when I try to use a named function as argument for then(), I get an error (next to line in code):

import GoogleAuth = gapi.auth2.GoogleAuth;
import GoogleUser = gapi.auth2.GoogleUser;

@Injectable()
export class MyService {
  constructor() { }

  private googleAuth: GoogleAuth = undefined;
  private clientConfig = { ... };

  private onInit(response: GoogleAuth): void {
    console.log(this); // undefined
    this.googleAuth = response; // Cannot read property 'googleAuth' of undefined
  }

  public init(): void {
    gapi.load('auth2', () => {
      gapi.auth2.init(this.clientConfig)
        .then(this.onInit);
    });
  }
}

I thought at first it was because I assigned undefined as the value for "googleAuth", but even if I run "console.log(this);" inside of "onInit", undefined is what appears in the console. If I were to call the method manually and pass the expected parameters, it has no trouble seeing "this" and "this.googleAuth". I have the exact same issues when using listen() and subscribe().

How can I fix this issue?

Body:
The way you passed in the function this.onInit to then, you looses the context. Proper way to do it is

    public init(): void {
      gapi.load('auth2', () => {
        gapi.auth2.init(this.clientConfig)
          .then((resp) => this.onInit(resp));
        });
    }

Note the use of fat arrow function.


问:
Azure Repos - allow co-workers to submit without pushing
I created an Azure repos (the first of my life ;-) and I have invited people to work on the project. They have a microsoft account. This is the free Azure environment.

I want to be notified when they submit their work and accept or reject it before I accept to commit the modification in the branches.

I am confused about the amount of working group options and I did not found the way to do what I want!

Does someone know what configuration must be done with their accounts / the Azure authorizations ?

答:
Found :
Go to the Azure project settings and in the left column, click on repositories. Then, change the authorizations given to the groups - developpers. You can now allow contributors to check in but if you do so, they can check in and I have no way to accept or reject the modification. In the other way, if you select deny to push in, they cannot push anything at all.

Git on azure allows for code validation before to commit. TFS Doesn't. A work around is to create a pullrequest folder where contributors are allowed to push in and be notified each time someone pushes their code in it. Verify and then merge / push in the corresponding branch.


问:
Dev Tools, Inspect Element, why is my CSS unchecked?
On a freshly loaded site, when I go inspect an element, a CSS property is always unchecked. It's there and I can enable it, but it's unchecked by default.

The style is position: sticky

Tried this in different browsers:

 * Chrome and Firefox: it's unchecked, but I can toggle it

 * Safari: it's "commented out" and also I can toggle it

To be clear: I don't see any other position styles being applied on that same element.

Any ideas?

答:
Figured it out - the style was actually commented out in code.

What surprised my was Dev Tools picking up commented out styles and listing it.

Updated: as @sebastian-zartner pointed out, these commented out styles will always be displayed


问:
Python3: List comprehension with named function definition possible?
I'm using html-requests library but the library-specific knowledge doesn't matter that much in this question

```<code>results = asession.run(*[lambda m=j: get_size(m) for j in i])
</code>```

asession.run(f1, f2, f3, ...) asynchronously runs f1(),f2(),f3(), and so on, returning [f3(), f1(), f2()] (returned list order varies)

The problem is, my get_size function can throw an error.

So I'd like to set some fallback value.
But with lambda expression, there's no way to insert try-except block. (lambda function only allows return value after :, not expression)

Instead of

```<code>[lambda m=j: get_size(m) for j in i]
</code>```

Is the following kind of code impossible?  (of course the following code is syntactically wrong)

```<code>[def fn(m=j): try: return get_size(m) except: return 0 for j in i]
</code>```

Is the following the only way?

```<code>def fn(m):
    try:
        return get_size(m)
    except:
        return 0
[lambda m=j: fn(m) for j in i]
</code>```

I like some one-line list comprehension in my case and wonder there is any way to use named function definition (anything except lambda because lambda only allows return value hence is limited) inside list comprehension.

答:
If you know what value of m causes the error (Eg. len(m) is 0) i.e. Condition, then you can use a lambda expression like so

```<code>f = lambda m : get_size(m) if not Condition else 0
[f(j) for j in i]
</code>```

Body:
I'm using html-requests library but the library-specific knowledge doesn't matter that much in this question

results = asession.run(*[lambda m=j: get_size(m) for j in i])

asession.run(f1, f2, f3, ...) asynchronously runs f1(),f2(),f3(), and so on, returning [f3(), f1(), f2()] (returned list order varies)

The problem is, my get_size function can throw an error.

So I'd like to set some fallback value.
But with lambda expression, there's no way to insert try-except block. (lambda function only allows return value after :, not expression)

Instead of

[lambda m=j: get_size(m) for j in i]

Is the following kind of code impossible?  (of course the following code is syntactically wrong)

[def fn(m=j): try: return get_size(m) except: return 0 for j in i]

Is the following the only way?

def fn(m):
    try:
        return get_size(m)
    except:
        return 0
[lambda m=j: fn(m) for j in i]

I like some one-line list comprehension in my case and wonder there is any way to use named function definition (anything except lambda because lambda only allows return value hence is limited) inside list comprehension.

Body:
If you know what value of m causes the error (Eg. len(m) is 0) i.e. Condition, then you can use a lambda expression like so

f = lambda m : get_size(m) if not Condition else 0
[f(j) for j in i]


问:
Stored procedure that selects from multiple group the results then order each group in descending order?
Here is the list of tables:

My Tables

I will like to create a stored procedure that will use the athleteId as parameter for the query and select all the columns in the result table and a few columns in each of the other tables Group the results by the EventName of the Event Table then order the groups by the Mark in descending order from the Result table and select the last record for each event.

I have search the net and tried various queries but cant seem to get the results I need.

This is hat I created. It retrieves all the info I need but I just don't seem to be able to group, order and select the lowest mark.

```<code>SELECT
    a.Id as AthleteId, a.FirstName AS FirstName, a.LastName AS LastName,
    a.BirthDate AS BirthDate, a.IsMale AS Male,
    a.Phone AS Phone, a.Email AS Email,
    p.FirstName AS ParentName, p.LastName AS ParentSurname,
    p.Phone AS ParentPhone, p.Email AS ParentEmail,
    ad.Street1 AS Street1, ad.Street2 AS Street2, ad.Town AS Town,
    ad.Parish AS Parish, ad.Country AS Country,
    s.SchoolName AS School, s.Phone AS SchoolPhone,
    s.[Location] AS SchoolLocation,
    c.FirstName AS CoachName, c.LastName AS CoachSurname,
    c.Phone AS CoachPhone, c.Email AS CoachEmail,
    m.MeetName AS MeetName,
    m.StartDate AS StartDate, m.EndDate AS EndDate, m.[Location] AS MeetLocation,
    e.EventName AS EventName,
    r.Mark AS EventMark, r.Wind AS Wind, r.PerfDate AS PerfDate
FROM
    dbo.Result r
INNER JOIN
    dbo.[Event] e ON e.Id = r.EventId
INNER JOIN
    dbo.Meet m ON m.Id = r.MeetId
INNER JOIN
    dbo.Athlete a
JOIN
    dbo.Parent p ON p.Id = a.ParentId
JOIN
    dbo.[Address] ad ON ad.Id = a.AddressId
JOIN
    dbo.Coach c ON c.Id = a.CoachId
JOIN
    dbo.School s ON s.Id = a.SchoolId
    ON a.Id = r.AthleteId
WHERE
    r.AthleteId = @AthleteId
</code>```

When I try adding the group by it shows an error.

Can anyone help me with this?

答:
A quick-and-dirty way to do this in SQL Server is:</p>

```<code>select top (1) with ties . . .
. . .
. . .
order by row_number() over (partition by r.eventid order by r.mark desc)
</code>```

Body:
Here is the list of tables:

My Tables

I will like to create a stored procedure that will use the athleteId as parameter for the query and select all the columns in the result table and a few columns in each of the other tables Group the results by the EventName of the Event Table then order the groups by the Mark in descending order from the Result table and select the last record for each event.

I have search the net and tried various queries but cant seem to get the results I need.

This is hat I created. It retrieves all the info I need but I just don't seem to be able to group, order and select the lowest mark.

SELECT
    a.Id as AthleteId, a.FirstName AS FirstName, a.LastName AS LastName,
    a.BirthDate AS BirthDate, a.IsMale AS Male,
    a.Phone AS Phone, a.Email AS Email,
    p.FirstName AS ParentName, p.LastName AS ParentSurname,
    p.Phone AS ParentPhone, p.Email AS ParentEmail,
    ad.Street1 AS Street1, ad.Street2 AS Street2, ad.Town AS Town,
    ad.Parish AS Parish, ad.Country AS Country,
    s.SchoolName AS School, s.Phone AS SchoolPhone,
    s.[Location] AS SchoolLocation,
    c.FirstName AS CoachName, c.LastName AS CoachSurname,
    c.Phone AS CoachPhone, c.Email AS CoachEmail,
    m.MeetName AS MeetName,
    m.StartDate AS StartDate, m.EndDate AS EndDate, m.[Location] AS MeetLocation,
    e.EventName AS EventName,
    r.Mark AS EventMark, r.Wind AS Wind, r.PerfDate AS PerfDate
FROM
    dbo.Result r
INNER JOIN
    dbo.[Event] e ON e.Id = r.EventId
INNER JOIN
    dbo.Meet m ON m.Id = r.MeetId
INNER JOIN
    dbo.Athlete a
JOIN
    dbo.Parent p ON p.Id = a.ParentId
JOIN
    dbo.[Address] ad ON ad.Id = a.AddressId
JOIN
    dbo.Coach c ON c.Id = a.CoachId
JOIN
    dbo.School s ON s.Id = a.SchoolId
    ON a.Id = r.AthleteId
WHERE
    r.AthleteId = @AthleteId

When I try adding the group by it shows an error.

Can anyone help me with this?

Body:
A quick-and-dirty way to do this in SQL Server is:

select top (1) with ties . . .
. . .
. . .
order by row_number() over (partition by r.eventid order by r.mark desc)


问:
iPhone: Increment badge counter automatically

Possible Duplicate:

  Push-Notification Badge auto increment.

I have implemented Push Notification for my iPhone application. Whenever I get the message, I want to increment badge value by one so I need not to pass it in Push Notification payload. Is it possible?

From here I learnt that I have to manage that from server side, so that's the only way? I had to store the previous value in Database and get the last value whenever I send next message? Isn't Apple support this automatically like incrementing application.applicationIconBadgeNumber whenever Push Notification received.

The problem with managing Badge number from server side is if user has already seen the previous Push Notification message, you would send wrong badge number!

答:
It's not really a problem. The client just needs to let the server know what messages it has seen. Everyone else is doing it, so just learn how to do it and do it.

EDIT: You can set the badge counter using:

```<code>[UIApplication sharedApplication].applicationIconBadgeNumber = badgeCount;
</code>```

Every time you do, you should send badgeCount to the server, so that the server knows the current count.

Body:
It's not really a problem. The client just needs to let the server know what messages it has seen. Everyone else is doing it, so just learn how to do it and do it.

EDIT: You can set the badge counter using:

[UIApplication sharedApplication].applicationIconBadgeNumber = badgeCount;

Every time you do, you should send badgeCount to the server, so that the server knows the current count.


问:
Determine if a character exists within a string? (Not using loops)
I'm trying to create a funcion that returns true if a non-alphanumeric character exists within a string. I cannot use a loop, however, and I'm looking for the right algorithm to do so.

```<code>not_alphanumeric("hello")  // This would return FALSE
not_alphanumeric("h%llo")  // This would return TRUE
</code>```

I need to know what type of algorithm I need to use in order to do this, OR if there is some non-loop related method in order to do this.

答:
If you don't know about the any_of() defined in algorithm library, you should take a look into it if you're making a program which contains no loops.

Consider this:

```<code>#include <iostream>
#include <algorithm>

bool checkAlphaNum(char *);

int main(void) {
    char *string = new char[1024];

    std::cout << "Enter a string: ";
    std::cin >> string;

    std::cout << checkAlphaNum(string) << std::endl;

    return 0;
}

bool checkAlphaNum(char *arr) {
    // verifying each character of the given string argument
    return std::any_of(arr, arr + strlen(arr), [](char ch)
    {return isalnum(ch);});
}
</code>```

Body:
I'm trying to create a funcion that returns true if a non-alphanumeric character exists within a string. I cannot use a loop, however, and I'm looking for the right algorithm to do so.

not_alphanumeric("hello")  // This would return FALSE
not_alphanumeric("h%llo")  // This would return TRUE

I need to know what type of algorithm I need to use in order to do this, OR if there is some non-loop related method in order to do this.

Body:
If you don't know about the any_of() defined in algorithm library, you should take a look into it if you're making a program which contains no loops.

Consider this:

#include <iostream>
#include <algorithm>

bool checkAlphaNum(char *);

int main(void) {
    char *string = new char[1024];

    std::cout << "Enter a string: ";
    std::cin >> string;

    std::cout << checkAlphaNum(string) << std::endl;

    return 0;
}

bool checkAlphaNum(char *arr) {
    // verifying each character of the given string argument
    return std::any_of(arr, arr + strlen(arr), [](char ch)
    {return isalnum(ch);});
}


问:
Android emulator not running with my React Native App
Trying to run my React Native app in Android emulator but it keeps throwing error:

"Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have
set up your Android development environment:
https://facebook.github.io/react-native/docs/getting-started.html
error spawnSync ./gradlew EACCES. Run CLI with --verbose flag for more details."

Tried react-native run-android, npm start, react-native start... nothing worked!!!

Am I missing out something here?? struggling with this since morning. Please help....

Update:

Ran "adb devices" in terminal. Still its not working :/ Same error!!!

答:
Check the permission on android/gradew. It should be 755 and not 644.

Run the following command inside your app root folder:

```<code>chmod 755 android/gradlew
</code>```

The run: react-native run-android. If you are on Windows, make sure to run react-native run-android in CMD as administrator.

Hope it helps :)

EDIT for the new problem in the comments:

The following are a few ways you can try to fix the error you mentioned in the comments:

1) Go to FILE -> sync project with gradle files.

If no.1 doesn't work for you. Try no.2

2) Go to .gradle\caches\2.0\scripts\build_7l4t45nbnsvdcl79ol8u0beli4\ProjectScript and remove the cache.properties.lock file. If you are on windows try this as: C:\Users\<username>\.gradle\caches\<gradle version such as 2.4 or something else>\scripts>del /S *.lock

Hope this solves your problem :)

EDIT 2:

You can downgrade from your Java 13 to Java 8. It may solve your problems. However, if you are unwilling to downgrade go to build.gradle and do the following:

```<code>compileJava.options.fork = true
compileJava.options.forkOptions.executable = /path_to_javac
</code>```

If you do the following above instead of downgrading you will set a concrete path which will hinder your project if you are sharing it with other developers.

This was the best I could come up with from simulating the same problem on one of my test projects in my computer. Hope it helps :)

Body:
Check the permission on android/gradew. It should be 755 and not 644.

Run the following command inside your app root folder:

chmod 755 android/gradlew

The run: react-native run-android. If you are on Windows, make sure to run react-native run-android in CMD as administrator.

Hope it helps :)

EDIT for the new problem in the comments:

The following are a few ways you can try to fix the error you mentioned in the comments:

1) Go to FILE -> sync project with gradle files.

If no.1 doesn't work for you. Try no.2

2) Go to .gradle\caches\2.0\scripts\build_7l4t45nbnsvdcl79ol8u0beli4\ProjectScript and remove the cache.properties.lock file. If you are on windows try this as: C:\Users\<username>\.gradle\caches\<gradle version such as 2.4 or something else>\scripts>del /S *.lock

Hope this solves your problem :)

EDIT 2:

You can downgrade from your Java 13 to Java 8. It may solve your problems. However, if you are unwilling to downgrade go to build.gradle and do the following:

compileJava.options.fork = true
compileJava.options.forkOptions.executable = /path_to_javac

If you do the following above instead of downgrading you will set a concrete path which will hinder your project if you are sharing it with other developers.

This was the best I could come up with from simulating the same problem on one of my test projects in my computer. Hope it helps :)


答:
How about adding this to your pointcut?

```<code>within(com.foo..*) && !within(com.foo.arch..*)
</code>```

This will capture all sub-packages of com.foo except for com.foo.arch and its respective sub-packages.

If you only want com.foo and no sub-packages at all, it would simply be:

```<code>within(com.foo.*)
</code>```

Title: Exclude architectural services from being processed by aspect

Body:
I'm creating an aspect to wrap my services but I'm also defining some services under the package

com.foo.arch

My application classes will be instead under

com.foo

Please notice that arch is a subpackage of com.foo but I can't put the "arch" keyword before.Isn't there a pointcut expression to say:

All classess under com.foo not having "arch" as third package?

Body:
How about adding this to your pointcut?

within(com.foo..*) && !within(com.foo.arch..*)

This will capture all sub-packages of com.foo except for com.foo.arch and its respective sub-packages.

If you only want com.foo and no sub-packages at all, it would simply be:

within(com.foo.*)


问:
CSS Transition When Moved
When the first element gets deleted, I want to make the other elements to slide into their new places instead of going instantly there. Using the code below, all of the other boxes move instantly to their new positions when you delete the first one. Eventually, there will be many rows of boxes.

var pile = document.getElementById("pile");
function removeFirst(){
  pile.removeChild(event.target);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box{
  border: 1px solid black;
  padding: 20px;
}
#pile{
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}</code>```

I'm the first box

I'm the second box

I'm the third box

I'm the fourth box

```

答:
var pile = document.getElementById("pile");
function removeFirst(thisDom){
    thisDom.style.transition = 'margin-left .3s'
    thisDom.style.opacity = 0
    thisDom.style.marginLeft = -thisDom.getBoundingClientRect().width + 'px'
    setTimeout(()=> {
        pile.removeChild(thisDom);
    }, 300)
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box{
  border: 1px solid black;
  padding: 20px;
}
#pile{
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}</code>```

I'm the first box

I'm the second box

I'm the third box

I'm the fourth box

```
</div>
</div>
</p>

<p>Remove <code>dom</code> when the transition is complete</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var rectArr = Array.from(document.getElementsByClassName('rect'));

var box = document.getElementById('box')
var delay = 300
box.addEventListener('click', function(e){
    if(e.target === box) return
    let index = e.target.getAttribute('data-index')

    var moveArr = rectArr.splice(index, rectArr.length)

    moveArr.forEach(item => {
        item.preLeft = item.offsetLeft
        item.preTop = item.offsetTop
    })

    box.removeChild(e.target)

    moveArr.forEach(item => {
        item.style.transform = `translate(${item.preLeft - item.offsetLeft}px,${item.preTop - item.offsetTop}px)`
    })
    setTimeout(() => {
        moveArr.forEach(item => {
            item.style.transition = `transform ${delay}ms ease`
            item.style.transform = `translate(0, 0)`
        })
    }, 1)

    setTimeout(() => {
      moveArr.forEach(item => {
        item.style.transition = ``
        item.style.transform = ''
      })
    }, delay + 1)

    rectArr = [...rectArr, ...moveArr]
})</code>```

.box {
    width: 336px;
    height: 336px;
    box-shadow: 0 0 3px pink;
    list-style: none;
    padding: 0;
}
.rect {
    width: 50px;
    height: 50px;
    box-shadow: 0 0 3px orange inset;
    margin: 3px;
    float: left;
    cursor: pointer;
    line-height: 50px;
    text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="box" id="box">
    <li class="rect" data-index="01">01</li>
    <li class="rect" data-index="02">02</li>
    <li class="rect" data-index="03">03</li>
    <li class="rect" data-index="04">04</li>
    <li class="rect" data-index="05">05</li>
    <li class="rect" data-index="06">06</li>
    <li class="rect" data-index="07">07</li>
    <li class="rect" data-index="08">08</li>
    <li class="rect" data-index="09">09</li>
    <li class="rect" data-index="10">10</li>
    <li class="rect" data-index="11">11</li>
    <li class="rect" data-index="12">12</li>
    <li class="rect" data-index="13">13</li>
    <li class="rect" data-index="14">14</li>
    <li class="rect" data-index="15">15</li>
    <li class="rect" data-index="16">16</li>
    <li class="rect" data-index="17">17</li>
    <li class="rect" data-index="18">18</li>
    <li class="rect" data-index="19">19</li>
    <li class="rect" data-index="20">20</li>
    <li class="rect" data-index="21">21</li>
    <li class="rect" data-index="22">22</li>
    <li class="rect" data-index="23">23</li>
    <li class="rect" data-index="24">24</li>
    <li class="rect" data-index="25">25</li>
    <li class="rect" data-index="26">26</li>
    <li class="rect" data-index="27">27</li>
    <li class="rect" data-index="28">28</li>
    <li class="rect" data-index="29">29</li>
    <li class="rect" data-index="30">30</li>
    <li class="rect" data-index="31">31</li>
    <li class="rect" data-index="32">32</li>
    <li class="rect" data-index="33">33</li>
    <li class="rect" data-index="34">34</li>
    <li class="rect" data-index="35">35</li>
    <li class="rect" data-index="36">36</li>
</ul></code>```

Title: CSS Transition When Moved

Body:
When the first element gets deleted, I want to make the other elements to slide into their new places instead of going instantly there. Using the code below, all of the other boxes move instantly to their new positions when you delete the first one. Eventually, there will be many rows of boxes.

var pile = document.getElementById("pile");
function removeFirst(){
  pile.removeChild(event.target);
}

.box{
  border: 1px solid black;
  padding: 20px;
}
#pile{
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

I'm the first box

I'm the second box

I'm the third box

I'm the fourth box

Body:
var pile = document.getElementById("pile");
function removeFirst(thisDom){
    thisDom.style.transition = 'margin-left .3s'
    thisDom.style.opacity = 0
    thisDom.style.marginLeft = -thisDom.getBoundingClientRect().width + 'px'
    setTimeout(()=> {
        pile.removeChild(thisDom);
    }, 300)
}

.box{
  border: 1px solid black;
  padding: 20px;
}
#pile{
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

<div id="pile">
  <div class="box" onclick="removeFirst(this)">I'm the first box</div>
  <div class="box" onclick="removeFirst(this)">I'm the second box</div>
  <div class="box" onclick="removeFirst(this)">I'm the third box</div>
  <div class="box" onclick="removeFirst(this)">I'm the fourth box</div>
</div>

Remove dom when the transition is complete

var rectArr = Array.from(document.getElementsByClassName('rect'));

var box = document.getElementById('box')
var delay = 300
box.addEventListener('click', function(e){
    if(e.target === box) return
    let index = e.target.getAttribute('data-index')

    var moveArr = rectArr.splice(index, rectArr.length)

    moveArr.forEach(item => {
        item.preLeft = item.offsetLeft
        item.preTop = item.offsetTop
    })

    box.removeChild(e.target)

    moveArr.forEach(item => {
        item.style.transform = `translate(${item.preLeft - item.offsetLeft}px,${item.preTop - item.offsetTop}px)`
    })
    setTimeout(() => {
        moveArr.forEach(item => {
            item.style.transition = `transform ${delay}ms ease`
            item.style.transform = `translate(0, 0)`
        })
    }, 1)

    setTimeout(() => {
      moveArr.forEach(item => {
        item.style.transition = ``
        item.style.transform = ''
      })
    }, delay + 1)

    rectArr = [...rectArr, ...moveArr]
})

.box {
    width: 336px;
    height: 336px;
    box-shadow: 0 0 3px pink;
    list-style: none;
    padding: 0;
}
.rect {
    width: 50px;
    height: 50px;
    box-shadow: 0 0 3px orange inset;
    margin: 3px;
    float: left;
    cursor: pointer;
    line-height: 50px;
    text-align: center;
}

<ul class="box" id="box">
    <li class="rect" data-index="01">01</li>
    <li class="rect" data-index="02">02</li>
    <li class="rect" data-index="03">03</li>
    <li class="rect" data-index="04">04</li>
    <li class="rect" data-index="05">05</li>
    <li class="rect" data-index="06">06</li>
    <li class="rect" data-index="07">07</li>
    <li class="rect" data-index="08">08</li>
    <li class="rect" data-index="09">09</li>
    <li class="rect" data-index="10">10</li>
    <li class="rect" data-index="11">11</li>
    <li class="rect" data-index="12">12</li>
    <li class="rect" data-index="13">13</li>
    <li class="rect" data-index="14">14</li>
    <li class="rect" data-index="15">15</li>
    <li class="rect" data-index="16">16</li>
    <li class="rect" data-index="17">17</li>
    <li class="rect" data-index="18">18</li>
    <li class="rect" data-index="19">19</li>
    <li class="rect" data-index="20">20</li>
    <li class="rect" data-index="21">21</li>
    <li class="rect" data-index="22">22</li>
    <li class="rect" data-index="23">23</li>
    <li class="rect" data-index="24">24</li>
    <li class="rect" data-index="25">25</li>
    <li class="rect" data-index="26">26</li>
    <li class="rect" data-index="27">27</li>
    <li class="rect" data-index="28">28</li>
    <li class="rect" data-index="29">29</li>
    <li class="rect" data-index="30">30</li>
    <li class="rect" data-index="31">31</li>
    <li class="rect" data-index="32">32</li>
    <li class="rect" data-index="33">33</li>
    <li class="rect" data-index="34">34</li>
    <li class="rect" data-index="35">35</li>
    <li class="rect" data-index="36">36</li>
</ul>


问:
Could an interrupt be serviced while the scheduler is changing the current task to another(i mean the scheduler is doing thread context switching)?
Interruptions could be handled while process is runing at the time of interruption occurs. Could an interrupt be serviced while the scheduler is changing the current task to another(i mean the scheduler is doing thread context switching)?

I would be grateful for any hint on this question.

答:
It's impossible, the schedule() function will disable interrupt before doing the context switch.

```<code>static void __sched notrace __schedule(bool preempt)
{
    struct task_struct *prev, *next;
    unsigned long *switch_count;
    struct rq_flags rf;
    struct rq *rq;
    int cpu;

    cpu = smp_processor_id();
    rq = cpu_rq(cpu);
    prev = rq->curr;

    schedule_debug(prev);
    if (sched_feat(HRTICK))
        hrtick_clear(rq);

    //look at here
    local_irq_disable();
......
};
</code>```

Here is the source code, and I write a blog about that, maybe helpful for you.

Body:
It's impossible, the schedule() function will disable interrupt before doing the context switch.

static void __sched notrace __schedule(bool preempt)
{
    struct task_struct *prev, *next;
    unsigned long *switch_count;
    struct rq_flags rf;
    struct rq *rq;
    int cpu;

    cpu = smp_processor_id();
    rq = cpu_rq(cpu);
    prev = rq->curr;

    schedule_debug(prev);
    if (sched_feat(HRTICK))
        hrtick_clear(rq);

    //look at here
    local_irq_disable();
......
};

Here is the source code, and I write a blog about that, maybe helpful for you.


问:
Flutter Firebase - Get a specific field from document
I'm trying to get a specific field called "specie" from a document in a Firebase collection. I am trying as follows but I have an error of type 'Future ' is not a subtype of type 'String'. What am I doing wrong?

Repository method:

```<code>getSpecie(String petId) {
    Future<DocumentSnapshot> snapshot = petCollection.document(petId).get();
    return snapshot.then((value) => Pet.fromSnapshot(value).specie);
  }
</code>```

Entity method:

```<code> factory Pet.fromSnapshot(DocumentSnapshot snapshot) {
    Pet newPet = Pet.fromJson(snapshot.data);
    newPet.reference = snapshot.reference;
    return newPet;
  }

 factory Pet.fromJson(Map<String, dynamic> json) => _PetFromJson(json);

Pet _PetFromJson(Map<String, dynamic> json) {
  return Pet(json['name'] as String,
      specie: json['specie'] as String);
}
</code>```

答:
Try this..

```<code>getSpecie(String petId) async{
    Future<DocumentSnapshot> snapshot = await petCollection.document(petId).get();
    return snapshot.then((value) => Pet.fromSnapshot(value).specie);
  }
</code>```

This is how I learned to get documents from firestore
https://medium.com/@yasassandeepa007/how-to-get-sub-collection-data-from-firebase-with-flutter-fe1bda8456ca

Body:
I'm trying to get a specific field called "specie" from a document in a Firebase collection. I am trying as follows but I have an error of type 'Future ' is not a subtype of type 'String'. What am I doing wrong?

Repository method:

getSpecie(String petId) {
    Future<DocumentSnapshot> snapshot = petCollection.document(petId).get();
    return snapshot.then((value) => Pet.fromSnapshot(value).specie);
  }

Entity method:

 factory Pet.fromSnapshot(DocumentSnapshot snapshot) {
    Pet newPet = Pet.fromJson(snapshot.data);
    newPet.reference = snapshot.reference;
    return newPet;
  }

 factory Pet.fromJson(Map<String, dynamic> json) => _PetFromJson(json);

Pet _PetFromJson(Map<String, dynamic> json) {
  return Pet(json['name'] as String,
      specie: json['specie'] as String);
}

Body:
Try this..

getSpecie(String petId) async{
    Future<DocumentSnapshot> snapshot = await petCollection.document(petId).get();
    return snapshot.then((value) => Pet.fromSnapshot(value).specie);
  }

This is how I learned to get documents from firestore
https://medium.com/@yasassandeepa007/how-to-get-sub-collection-data-from-firebase-with-flutter-fe1bda8456ca


问:
Filter dataframe base on duplicate column values
Suppose that i have this data,

import pandas as pd
data = pd.DataFrame({'Id':[1,1,1,6,7],'Sales':[2,3,4,2,8]})
```

Is there a filter such that it will output a dataframe such that the Id are the same? See expected output below:

答:
Let us try </p>

```<code>data=data[data.Id.duplicated(keep=False)]
   Id  Sales
0   1      2
1   1      3
2   1      4
</code>```

Body:
Suppose that i have this data,

import pandas as pd
data = pd.DataFrame({'Id':[1,1,1,6,7],'Sales':[2,3,4,2,8]})

Is there a filter such that it will output a dataframe such that the Id are the same? See expected output below:

Body:
Let us try

data=data[data.Id.duplicated(keep=False)]
   Id  Sales
0   1      2
1   1      3
2   1      4


问:
problem in calculating lambda with Pandas
I need to convert the value of the 'Amount' field to dollar, based on the value of another 'Currency' field, but I don't understand why the value of the first record is repeated to me throughout the dataframe.

Here is my code:

```<code>def calculo_dolar_2(data):
  valor = (data*1000)/float(precio_dolar)
  return valor

df_conversion_dolar_2['ED'] = df_conversion_dolar_2['Currency'].apply(lambda x: ( df_conversion_dolar_2['Amount'].apply(calculo_dolar_2)) if x=='$$' else df_conversion_dolar_2['Amount'])

df_conversion_dolar_2
</code>```

capture

I am trying in this other way, but without success:

precio_dolar = 800
def calculo_dolar_3(data):
  if data == '$$':
    valor = (df_conversion_dolar_2['Amount']*1000)/float(precio_dolar)
  else:
    valor = df_conversion_dolar_2['Amount']
  return valor

df_conversion_dolar_2['ED'] = df_conversion_dolar_2['Currency'].apply(lambda x: df_conversion_dolar_2['Amount'].apply(calculo_dolar_3))

df_conversion_dolar_2```

What is it due to?

答:
I haven't tested the code but this is how I would do it; </p>

```<code># make your code clear (what is 2?)
df = df_conversion_dolar_2

precio_dolar = 800

# first, let's make a boolean selector
dolar_select = df['Currency'] == '$$$'

# Selecting dollar rows at the column Amount is as follow:
# This line is only to show you what happens and is not
# needed in your final code
df.loc[dolar_select, 'Amount']

# Anyway, now we apply your function to the selected data:
df['ED'] = df.loc[dolar_select, 'Amount'].map(lambda x: (x*1000)/float(precio_dolar))

# Finally, fill the NaN values in your dataframe (the non selected rows)
df.loc[df['ED'].isna(), 'ED'] = df['Amount']

</code>```

Body:
I need to convert the value of the 'Amount' field to dollar, based on the value of another 'Currency' field, but I don't understand why the value of the first record is repeated to me throughout the dataframe.

Here is my code:

def calculo_dolar_2(data):
  valor = (data*1000)/float(precio_dolar)
  return valor

df_conversion_dolar_2['ED'] = df_conversion_dolar_2['Currency'].apply(lambda x: ( df_conversion_dolar_2['Amount'].apply(calculo_dolar_2)) if x=='$$' else df_conversion_dolar_2['Amount'])

df_conversion_dolar_2

capture

I am trying in this other way, but without success:

precio_dolar = 800
def calculo_dolar_3(data):
  if data == '$$':
    valor = (df_conversion_dolar_2['Amount']*1000)/float(precio_dolar)
  else:
    valor = df_conversion_dolar_2['Amount']
  return valor

df_conversion_dolar_2['ED'] = df_conversion_dolar_2['Currency'].apply(lambda x: df_conversion_dolar_2['Amount'].apply(calculo_dolar_3))

df_conversion_dolar_2

What is it due to?

Body:
I haven't tested the code but this is how I would do it;

# make your code clear (what is 2?)
df = df_conversion_dolar_2

precio_dolar = 800

# first, let's make a boolean selector
dolar_select = df['Currency'] == '$$$'

# Selecting dollar rows at the column Amount is as follow:
# This line is only to show you what happens and is not
# needed in your final code
df.loc[dolar_select, 'Amount']

# Anyway, now we apply your function to the selected data:
df['ED'] = df.loc[dolar_select, 'Amount'].map(lambda x: (x*1000)/float(precio_dolar))

# Finally, fill the NaN values in your dataframe (the non selected rows)
df.loc[df['ED'].isna(), 'ED'] = df['Amount']


问:
In Python, how can I combine a set of tuples from a list of given tuples without using itertools?
Given a list as follows:

[(1, 2), (3, 4, 5), (6,)]

I know it's very easy to combine the list of tuples by using itertools.

(1, 3, 6), (1, 4, 6), (1, 5, 6), (2, 3, 6), (2, 4, 6), (2, 5, 6)

But how can I solve it without using itertools?

Body:
def product(pools):
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    return result

product([(1,2,3),(4,5),(6,)])
[[1, 4, 6], [1, 5, 6], [2, 4, 6], [2, 5, 6], [3, 4, 6], [3, 5, 6]]