问:
Cannot connect to socket.io connection in node.js
I'm new to node.js and, having worked through the relevant parts of the Wexler book, I am trying to create a simple stream using socket.io.

Here is my node.js server code:

```<code>const port = 3000,
  dataIntervalMillis = 5000,
  express = require("express"),
  app = express(),
  crypto = require('crypto');

const server = app
// .get("/", (req, res) => {
//   res.send("Run this project by typing in <b>nodemon</b> in the node.js command prompt.");
// })
.listen(port, () => {
  console.log(`RNG Server running on port number ${port}`);
}),
io = require("socket.io")(server);

io.on("connection", client => {
  console.log("RNG client connected.");
  io.emit("New RNG client connection.");

  client.on("disconnect", () => {
    console.log("RNG client disconnected.");
    io.emit("RNG client disconnected.");
  });
});
</code>```

I have built a standalone Java application to test the stream:

```<code>//import java.io.BufferedReader;
import java.io.InputStream;
//import java.io.InputStreamReader;
//import java.io.PrintStream;
import java.net.Socket;

public class SimpleSocketClientExample {

    public static void main(String[] args) {

    String server = "localhost";
    int port = 3000;

        try {

            // Connect to the server
        System.out.println("Connect to server " + server + " on port " + port + "...");
            Socket socket = new Socket( server, port );
        System.out.println("...connected.");

        //BufferedReader in = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );
        InputStream in = socket.getInputStream();

        System.out.println("Reading byte...");
        int b = in.read();
        System.out.println("...byte read.");

            // Close our streams
        if (in != null) {
        in.close();
        }
        if (socket != null) {
        socket.close();
        }
        }
        catch( Exception e ) {
            e.printStackTrace();
        }
    }
}
</code>```

The problem is that this client code hangs on the in.read() line.

The only console log from the server is RNG Server running on port number 3000. There is no RNG client connected in the server log, which indicates that the client has not connected (or has connected to something else).

I've tested my node.js app using online socket testers, and they don't seem to connect either - indicating the problem probably lays with my node.js server app.

Can anyone advise what I may have missed?

答:
Turns out socket.io doesn't create a standard TCP socket.

My solution was to leave my client code untouched and change the Node.js server code to use the net library instead.

In case it might help anyone else that runs into the same issue, here's my new code:

```<code>const port = 3000;

const { createServer } = require('net');

const server = createServer();

// A counter to facilitate assigning of socket.id.
let counter = 0;

// An array of connected client sockets that we will broadcast to.
let sockets = {};

server.on('connection', (socket) => {
  socket.id = counter++;
  console.log(`A client has connected: ${socket.id}`);

  // Catch errors so they don't stop the application.
  socket.on('error', function () {
    console.log(`Client error: ${socket.id}`);
    delete sockets[socket.id];
  });

  // Set character encoding.
  socket.setEncoding('utf8');

  // Add socket to array.
  sockets[socket.id] = socket;

  // When connection ends, remove socket from array.
  socket.on('end', data => {
    console.log(`${socket.id} has disconnected`)
    delete sockets[socket.id];
  });
});

server.listen(port, () => {
  console.log(`RNG Server running on port number ${port}`);
});
</code>```

Body:
I'm new to node.js and, having worked through the relevant parts of the Wexler book, I am trying to create a simple stream using socket.io.

Here is my node.js server code:

const port = 3000,
  dataIntervalMillis = 5000,
  express = require("express"),
  app = express(),
  crypto = require('crypto');

const server = app
// .get("/", (req, res) => {
//   res.send("Run this project by typing in nodemon in the node.js command prompt.");
// })
.listen(port, () => {
  console.log(`RNG Server running on port number ${port}`);
}),
io = require("socket.io")(server);

io.on("connection", client => {
  console.log("RNG client connected.");
  io.emit("New RNG client connection.");

  client.on("disconnect", () => {
    console.log("RNG client disconnected.");
    io.emit("RNG client disconnected.");
  });
});

I have built a standalone Java application to test the stream:

//import java.io.BufferedReader;
import java.io.InputStream;
//import java.io.InputStreamReader;
//import java.io.PrintStream;
import java.net.Socket;

public class SimpleSocketClientExample {

    public static void main(String[] args) {

    String server = "localhost";
    int port = 3000;

        try {

            // Connect to the server
        System.out.println("Connect to server " + server + " on port " + port + "...");
            Socket socket = new Socket( server, port );
        System.out.println("...connected.");

        //BufferedReader in = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );
        InputStream in = socket.getInputStream();

        System.out.println("Reading byte...");
        int b = in.read();
        System.out.println("...byte read.");

            // Close our streams
        if (in != null) {
        in.close();
        }
        if (socket != null) {
        socket.close();
        }
        }
        catch( Exception e ) {
            e.printStackTrace();
        }
    }
}

The problem is that this client code hangs on the in.read() line.

The only console log from the server is RNG Server running on port number 3000. There is no RNG client connected in the server log, which indicates that the client has not connected (or has connected to something else).

I've tested my node.js app using online socket testers, and they don't seem to connect either - indicating the problem probably lays with my node.js server app.

Can anyone advise what I may have missed?

Body:
Turns out socket.io doesn't create a standard TCP socket.

My solution was to leave my client code untouched and change the Node.js server code to use the net library instead.

In case it might help anyone else that runs into the same issue, here's my new code:

const port = 3000;

const { createServer } = require('net');

const server = createServer();

// A counter to facilitate assigning of socket.id.
let counter = 0;

// An array of connected client sockets that we will broadcast to.
let sockets = {};

server.on('connection', (socket) => {
  socket.id = counter++;
  console.log(`A client has connected: ${socket.id}`);

  // Catch errors so they don't stop the application.
  socket.on('error', function () {
    console.log(`Client error: ${socket.id}`);
    delete sockets[socket.id];
  });

  // Set character encoding.
  socket.setEncoding('utf8');

  // Add socket to array.
  sockets[socket.id] = socket;

  // When connection ends, remove socket from array.
  socket.on('end', data => {
    console.log(`${socket.id} has disconnected`)
    delete sockets[socket.id];
  });
});

server.listen(port, () => {
  console.log(`RNG Server running on port number ${port}`);
});


来源: stackexchange

问:
`Authorization Token has expired` issue AWS-CLI on MacOS Sierra
I'm trying to push a docker image to the AWS ECR repository using the aws-cli.

I just run the get-login command

execute the output (which returns login succeeded)

then try to push a docker image then I get the
message:

denied: Your Authorization Token has expired. Please run
'aws ecr get-login' to fetch a new one.

I don't know whats going wrong,  I'm pushing to the right repo, the time on my mac is correct.
This was working before, but since I reinstalled my mac and upgraded to macOS Sierra it's not working anymore, so probably related to that.

My aws --version output:

aws-cli/1.11.34 Python/2.7.10 Darwin/16.3.0 botocore/1.4.91

The complete output of the commands I run:

```<code>$ aws ecr get-login --region eu-west-1
docker login -u AWS -p AQECAHh....b6Wk -e none https://1234567890.dkr.ecr.eu-west-1.amazonaws.com
$ docker login -u AWS -p AQECAHh....b6Wk -e none https://1234567890.dkr.ecr.eu-west-1.amazonaws.com
Flag --email has been deprecated, will be removed in 1.13.
Login Succeeded
$ docker push 1234567890.dkr.ecr.eu-west-1.amazonaws.com/service-web:latest
The push refers to a repository [1234567890.dkr.ecr.eu-west-1.amazonaws.com/service-web]
c1f87971dfa9: Preparing
2eb644aea3de: Preparing
9c8843ffe48e: Preparing
39bb58d049d4: Preparing
f053bc969599: Preparing
7169084246b8: Waiting
bb134a1936fd: Waiting
184e76848a1c: Waiting
75c8fcf65748: Waiting
eb9b9ee1ea58: Waiting
f4bf35723edd: Waiting
ddffe1a64b3c: Waiting
fd1a1154db16: Waiting
b542e946067a: Waiting
d49ed2a5e1ed: Waiting
bb39b980367a: Waiting
25b8358d062f: Waiting
997eee521fc7: Waiting
50b5447183a8: Waiting
4339b5cb0e1d: Waiting
3dbd4a53b21b: Waiting
2bec16216500: Waiting
b9fd8e264df6: Waiting
b6ca02dfe5e6: Waiting
denied: Your Authorization Token has expired. Please run 'aws ecr get-login' to fetch a new one.
</code>```

答:
The following steps worked for me. First, run

```<code>aws ecr get-login --region us-west-2
</code>```

You will get an output which returns:

```<code>docker login -u AWS -p AQECAHh....b6Wk -e none 1234567890.dkr.ecr.eu-west-1.amazonaws.com
</code>```

Now, remove "-e none" from the above result and run the command again.

You will be able to login successfully.

Now, try pushing your docker image and it will work!

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to push a docker image to the AWS ECR repository using the aws-cli.

I just run the get-login command

execute the output (which returns login succeeded)

then try to push a docker image then I get the
message:

denied: Your Authorization Token has expired. Please run
'aws ecr get-login' to fetch a new one.

I don't know whats going wrong,  I'm pushing to the right repo, the time on my mac is correct.
This was working before, but since I reinstalled my mac and upgraded to macOS Sierra it's not working anymore, so probably related to that.

My aws --version output:

aws-cli/1.11.34 Python/2.7.10 Darwin/16.3.0 botocore/1.4.91

The complete output of the commands I run:

$ aws ecr get-login --region eu-west-1
docker login -u AWS -p AQECAHh....b6Wk -e none https://1234567890.dkr.ecr.eu-west-1.amazonaws.com
$ docker login -u AWS -p AQECAHh....b6Wk -e none https://1234567890.dkr.ecr.eu-west-1.amazonaws.com
Flag --email has been deprecated, will be removed in 1.13.
Login Succeeded
$ docker push 1234567890.dkr.ecr.eu-west-1.amazonaws.com/service-web:latest
The push refers to a repository [1234567890.dkr.ecr.eu-west-1.amazonaws.com/service-web]
c1f87971dfa9: Preparing
2eb644aea3de: Preparing
9c8843ffe48e: Preparing
39bb58d049d4: Preparing
f053bc969599: Preparing
7169084246b8: Waiting
bb134a1936fd: Waiting
184e76848a1c: Waiting
75c8fcf65748: Waiting
eb9b9ee1ea58: Waiting
f4bf35723edd: Waiting
ddffe1a64b3c: Waiting
fd1a1154db16: Waiting
b542e946067a: Waiting
d49ed2a5e1ed: Waiting
bb39b980367a: Waiting
25b8358d062f: Waiting
997eee521fc7: Waiting
50b5447183a8: Waiting
4339b5cb0e1d: Waiting
3dbd4a53b21b: Waiting
2bec16216500: Waiting
b9fd8e264df6: Waiting
b6ca02dfe5e6: Waiting
denied: Your Authorization Token has expired. Please run 'aws ecr get-login' to fetch a new one.

Body:
The following steps worked for me. First, run

aws ecr get-login --region us-west-2

You will get an output which returns:

docker login -u AWS -p AQECAHh....b6Wk -e none 1234567890.dkr.ecr.eu-west-1.amazonaws.com

Now, remove "-e none" from the above result and run the command again.

You will be able to login successfully.

Now, try pushing your docker image and it will work!

ContentLicense: CC BY-SA 4.0


问:
Swift: Button with image bigger than button
I can't figure out a way to make a button look like in the following image.

The icon is supposed to be bigger than the button.

I already tired this, but it doesn't work:

```<code>let image = UIImage(named: "CircleForButtonCountries")
goToCoutriesButtonMain.imageView?.contentMode = UIViewContentMode.scaleAspectFit
goToCoutriesButtonMain.setImage(image, for: UIControlState.normal)
</code>```

答:
Working in Swift 5:</p>

```<code>yourButton.clipsToBounds = true
yourButton.contentMode = .scaleAspectFill
yourButton.setBackgroundImage(UIImage(named: "yourImage"), for: .normal)
</code>```

Body:
I can't figure out a way to make a button look like in the following image.

The icon is supposed to be bigger than the button.

I already tired this, but it doesn't work:

let image = UIImage(named: "CircleForButtonCountries")
goToCoutriesButtonMain.imageView?.contentMode = UIViewContentMode.scaleAspectFit
goToCoutriesButtonMain.setImage(image, for: UIControlState.normal)

Body:
Working in Swift 5:

yourButton.clipsToBounds = true
yourButton.contentMode = .scaleAspectFill
yourButton.setBackgroundImage(UIImage(named: "yourImage"), for: .normal)


问:
Handling Third Party Cookies on WKWebView
I need a way to accept/handle third party cookies in WKWebViews for iOS 13.5. It seems iOS is blocking my site from fully loading due to third party cookies. </p>

答: WKWebView does not support third-party cookies. Change your site to work without them.</p>


问:
How to populate a dropdown in Dash using a python list and get it's value in a variable?
I have a dropdown in Jupyter notebook filled with the values in a python list. I would like to replicate the same in Plotly-Dash.

答:
I figured it out while I was at it. Put the list in a dataframe.

```<code>df= pd.DataFrame({
'c' : list
})
</code>```

Code the dropdown

```<code>dcc.Dropdown(
        id='dropdown',
        options=[
            {'label':i, 'value':i} for i in df['c'].unique()
        ],
    ),
html.Div(id='output')
</code>```

Callback

```<code>@app.callback(Output('output', 'children'),
          [Input('dropdown', 'value')])
def update_output_1(value):
filtered_df = df[df['c'] == value]
return filtered_df.iloc[0]['c']
</code>```

Body:
I figured it out while I was at it. Put the list in a dataframe.

df= pd.DataFrame({
'c' : list
})

Code the dropdown

dcc.Dropdown(
        id='dropdown',
        options=[
            {'label':i, 'value':i} for i in df['c'].unique()
        ],
    ),
html.Div(id='output')

Callback

@app.callback(Output('output', 'children'),
          [Input('dropdown', 'value')])
def update_output_1(value):
filtered_df = df[df['c'] == value]
return filtered_df.iloc[0]['c']


问:
How can I make this php database class more secure?
I'm using the following PHP MySQL database class. I'm curious as to what I could do to make it more secure. I'm happy with it so far, but without suggesting to "use PDO" what can I do to improve this currently?</p>

```<code>    <?

    class DbConnector {

    public static function getInstance(){
   static $instance = null;
   if($instance === null){
      $instance = new DbConnector();
   }

   return $instance;
    }

    var $theQuery;
    var $link;

    function DbConnector() {

        $host = 'localhost';
        $db     = '';
        $user = '';
        $pass = '';

        // connect to the db
        $this->link = mysql_connect($host, $user, $pass);
        mysql_select_db($db);
        register_shutdown_function(array(&$this, 'close'));
    }

    function find($query) {
        $ret = mysql_query($query, $this->link);
        if (mysql_num_rows($ret) == 0)
            return array();
        $retArray = array();

        while ($row = mysql_fetch_array($ret))
            $retArray[] = $row;

        return $retArray;
    }

    function insert($query) {
        $ret = mysql_query($query, $this->link);

        if (mysql_affected_rows() < 1)
            return false;
        return true;
    }

    function query($query) {
        $this->theQuery = $query;
        return mysql_query($query, $this->link);
    }

    function fetchArray($result) {

        return mysql_fetch_array($result);
    }

    function close() {
        mysql_close($this->link);
    }

    function exists($query) {
        $ret = mysql_query($query, $this->link);
        if (mysql_num_rows($ret) == 0)
            return false;
    }

    function last_id($query) {
        return mysql_insert_id($query);
    }

}

?>
</code>```

答:
ok I hate PDO too, "my own code is my own risk, while others code is also your own risk". Anyway, if you will use this script without any cleaner I'm sure you will make your DB explode. you may want to take a look at others mysql database connection classes before starting your own:

take a look here

Body:
I'm using the following PHP MySQL database class. I'm curious as to what I could do to make it more secure. I'm happy with it so far, but without suggesting to "use PDO" what can I do to improve this currently?

    <?

    class DbConnector {

    public static function getInstance(){
   static $instance = null;
   if($instance === null){
      $instance = new DbConnector();
   }

   return $instance;
    }

    var $theQuery;
    var $link;

    function DbConnector() {

        $host = 'localhost';
        $db     = '';
        $user = '';
        $pass = '';

        // connect to the db
        $this->link = mysql_connect($host, $user, $pass);
        mysql_select_db($db);
        register_shutdown_function(array(&$this, 'close'));
    }

    function find($query) {
        $ret = mysql_query($query, $this->link);
        if (mysql_num_rows($ret) == 0)
            return array();
        $retArray = array();

        while ($row = mysql_fetch_array($ret))
            $retArray[] = $row;

        return $retArray;
    }

    function insert($query) {
        $ret = mysql_query($query, $this->link);

        if (mysql_affected_rows() < 1)
            return false;
        return true;
    }

    function query($query) {
        $this->theQuery = $query;
        return mysql_query($query, $this->link);
    }

    function fetchArray($result) {

        return mysql_fetch_array($result);
    }

    function close() {
        mysql_close($this->link);
    }

    function exists($query) {
        $ret = mysql_query($query, $this->link);
        if (mysql_num_rows($ret) == 0)
            return false;
    }

    function last_id($query) {
        return mysql_insert_id($query);
    }

}

?>


问:
How do you attach and detach from Docker's process?
I can attach to a docker process but Ctrl+C doesn't work to detach from it. exit basically halts the process.

What's the recommended workflow to have the process running, occasionally attaching to it to make some changes, and then detaching?

答:
Update

I typically used docker attach to see what STDOUT was displaying, for troubleshooting containers. I just found docker logs --follow 621a4334f97b, which lets me see the STDOUT whilst also being able to ctrl+c off of it without affecting container operation! Exactly what I've always wanted.

... naturally you'll need to substitue in your own container ID.

Original Answer

I wanted to leave the container running, but had attached without starting the container with -it. My solution was to sacrifice my SSH connection instead (since I was SSHed into the machine that was running the containers). Killing that ssh session left the container intact but detached me from it.


问:
How to populate a relation with an axiom in event b
So, I have a Rodin event-b project and would like to define a known static relation. For examples sake, lets say I have a set {a,b,c} and would like to specify the relation constant which is equal to {(a,1),(a,2),(b,3)} in an context axiom. (May be multilined, but preferably single if feasable)

How would I go about this?

```<code>CONTEXT

example

SETS

list

CONSTANTS
a
b
c

relation

AXIOMS

axm1   :    partition(list, {a}, {b}, {c})

axm2   :    relation ∈ list↔1‥5

axm3   : ???

END
</code>```

答:
```<code>axm3:  relation = {a↦1, a↦2, b↦3}
</code>```

Body:
So, I have a Rodin event-b project and would like to define a known static relation. For examples sake, lets say I have a set {a,b,c} and would like to specify the relation constant which is equal to {(a,1),(a,2),(b,3)} in an context axiom. (May be multilined, but preferably single if feasable)

How would I go about this?

CONTEXT

example

SETS

list

CONSTANTS
a
b
c

relation

AXIOMS

axm1   :    partition(list, {a}, {b}, {c})

axm2   :    relation ∈ list↔1‥5

axm3   : ???

END

Body: axm3:  relation = {a↦1, a↦2, b↦3}


问:
Nifi json efficiency parsing
I am not really sure how to go about this, I am trying to find the best way to get the data i want and i cant figure out how to do it without 3 different sets of evaluateJsonPath processors.

My data looks like this.

```<code>{
  "@timestamp": "2020-05-29T18:06:53.965Z",
  "@metadata": {
    "beat": "filebeat",
    "type": "_doc",
    "version": "7.7.0"
  },
  "agent": {
    "ephemeral_id": "691847ce-87fa-49de-a635-555b31ed28f4",
    "hostname": "acal",
    "id": "c3336311-de5a-4563-b24b-655613b399aa",
    "version": "7.7.0",
    "type": "filebeat"
  },
  "log": {
    "offset": 3759198,
    "file": {
      "path": "/opt/zactivity.log"
    }
  },
  "message": "{\"eventDate\":\"2020-05-29 18:06:50.913\",\"status\":\"SUCCEEDED\",\"activityType\":\"AUTHENTICATION\",\"user\":\"admin\",\"accountId\":\"4dadb154\",\"ip\":\"111.11.1.111\",\"userRoles\":[\"ROLE_DELETE_ALL\",\"ROLE_INVOKE_ACTIONS\",\"ROLE_SAVE\",\"ROLE_CREATE\",\"ROLE_READ\",\"ROLE_SAVE\",\"ROLE_ADMINISTER\",\"ROLE_SHARE\",\"ROLE_MANAGE\",\"ROLE_EXPORT\",\"ROLE_MANAGE_ALL\",\"ROLE_MANAGE_ACTION\",\"ROLE_EDIT\",\"ROLE_ADMIN\",\"ROLE_MANAG\",\"ROLE_RAW_DATA_ACCESS\",\"ROLE_ADMINIST\"],\"userGroups\":[\"1fb\"],\"userType\":\"USER\",\"authenticationType\":\"USERNAME_PASSWORD\"} ",
  "input": {
    "type": "log"
  },
  "ecs": {
    "version": "1.5.0"
  },
  "host": {
    "mac": [
      "50:6b:8d:db:04:2e"
    ],
    "hostname": "local",
    "architecture": "x86_64",
    "os": {
      "version": "7 (Core)",
      "family": "redhat",
      "name": "CentOS Linux",
      "kernel": "3.10.0-1062.12.1.el7.x86_64",
      "codename": "Core",
      "platform": "centos"
    },
    "id": "a29a885a0aba48418d46414ecbe449e1",
    "containerized": false,
    "name": "local",
    "ip": [
      "11.11.11.11"
    ]
  }
}
</code>```

I want need a few values from message and also log.file.path and maybe even the @timestamp.

I currently have an EvaluateJsonPath just for getting message, log.file.path, and @timestamp. I then route that based on the file path and send it to another EvaluateJsonPath just to take the message and make it a flowfile to pass it into another EvaluateJsonPath to parse out the values within message.

Is there a better way to do this instead of using 3 different EvaluateJsonPath's?

答:
you should be able to use only one EvaluateJsonPath.
set Destination to flowfile-attribute and define 3 dynamic properties, each one for each values you want. </p>

Title: Nifi json efficiency parsing

Body:
I am not really sure how to go about this, I am trying to find the best way to get the data i want and i cant figure out how to do it without 3 different sets of evaluateJsonPath processors.

My data looks like this.

{
  "@timestamp": "2020-05-29T18:06:53.965Z",
  "@metadata": {
    "beat": "filebeat",
    "type": "_doc",
    "version": "7.7.0"
  },
  "agent": {
    "ephemeral_id": "691847ce-87fa-49de-a635-555b31ed28f4",
    "hostname": "acal",
    "id": "c3336311-de5a-4563-b24b-655613b399aa",
    "version": "7.7.0",
    "type": "filebeat"
  },
  "log": {
    "offset": 3759198,
    "file": {
      "path": "/opt/zactivity.log"
    }
  },
  "message": "{\"eventDate\":\"2020-05-29 18:06:50.913\",\"status\":\"SUCCEEDED\",\"activityType\":\"AUTHENTICATION\",\"user\":\"admin\",\"accountId\":\"4dadb154\",\"ip\":\"111.11.1.111\",\"userRoles\":[\"ROLE_DELETE_ALL\",\"ROLE_INVOKE_ACTIONS\",\"ROLE_SAVE\",\"ROLE_CREATE\",\"ROLE_READ\",\"ROLE_SAVE\",\"ROLE_ADMINISTER\",\"ROLE_SHARE\",\"ROLE_MANAGE\",\"ROLE_EXPORT\",\"ROLE_MANAGE_ALL\",\"ROLE_MANAGE_ACTION\",\"ROLE_EDIT\",\"ROLE_ADMIN\",\"ROLE_MANAG\",\"ROLE_RAW_DATA_ACCESS\",\"ROLE_ADMINIST\"],\"userGroups\":[\"1fb\"],\"userType\":\"USER\",\"authenticationType\":\"USERNAME_PASSWORD\"} ",
  "input": {
    "type": "log"
  },
  "ecs": {
    "version": "1.5.0"
  },
  "host": {
    "mac": [
      "50:6b:8d:db:04:2e"
    ],
    "hostname": "local",
    "architecture": "x86_64",
    "os": {
      "version": "7 (Core)",
      "family": "redhat",
      "name": "CentOS Linux",
      "kernel": "3.10.0-1062.12.1.el7.x86_64",
      "codename": "Core",
      "platform": "centos"
    },
    "id": "a29a885a0aba48418d46414ecbe449e1",
    "containerized": false,
    "name": "local",
    "ip": [
      "11.11.11.11"
    ]
  }
}

I want need a few values from message and also log.file.path and maybe even the @timestamp.

I currently have an EvaluateJsonPath just for getting message, log.file.path, and @timestamp. I then route that based on the file path and send it to another EvaluateJsonPath just to take the message and make it a flowfile to pass it into another EvaluateJsonPath to parse out the values within message.

Is there a better way to do this instead of using 3 different EvaluateJsonPath's?


问:
Ruby 2.4 on Mac OS Mojave : image not found ... related to openssl.bundle
So i upgraded my Ruby to 2.4.9 on Mac OS Mojave.

I'm having trouble gem-installing...

```<code>    proj$ gem install google-cloud-vision
ERROR:  Loading command: install (LoadError)
    dlopen(/Users/mc/.rbenv/versions/2.4.2/lib/ruby/2.4.0/x86_64-darwin16/openssl.bundle, 9): Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib
  Referenced from: /Users/mc/.rbenv/versions/2.4.2/lib/ruby/2.4.0/x86_64-darwin16/openssl.bundle
  Reason: image not found - /Users/mc/.rbenv/versions/2.4.2/lib/ruby/2.4.0/x86_64-darwin16/openssl.bundle
ERROR:  While executing gem ... (NoMethodError)
    undefined method `invoke_with_build_args' for nil:NilClass

proj$ ruby -v
ruby 2.4.2p198 (2017-09-14 revision 59899) [x86_64-darwin16]
</code>```

I already did a bunch of brew update && brew upgrade, but i'm stuck... any pointers?

答: Per the comment: Remove Ruby and reinstall.</p>

Body:
So i upgraded my Ruby to 2.4.9 on Mac OS Mojave.

I'm having trouble gem-installing...

    proj$ gem install google-cloud-vision
ERROR:  Loading command: install (LoadError)
    dlopen(/Users/mc/.rbenv/versions/2.4.2/lib/ruby/2.4.0/x86_64-darwin16/openssl.bundle, 9): Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib
  Referenced from: /Users/mc/.rbenv/versions/2.4.2/lib/ruby/2.4.0/x86_64-darwin16/openssl.bundle
  Reason: image not found - /Users/mc/.rbenv/versions/2.4.2/lib/ruby/2.4.0/x86_64-darwin16/openssl.bundle
ERROR:  While executing gem ... (NoMethodError)
    undefined method `invoke_with_build_args' for nil:NilClass

proj$ ruby -v
ruby 2.4.2p198 (2017-09-14 revision 59899) [x86_64-darwin16]

I already did a bunch of brew update && brew upgrade, but i'm stuck... any pointers?


问:
Turn a col into rownames in a list of dataframes
I have a list of dataframes for which I would like to turn one of their cols into the rownames.
(instead of doing this for every df individually).

Unfortunatly I cant get it to work, maybe someone can help?

```<code>DF1 <- data.frame(A = c("A", "B", "C"),
                  B = 1:3)
DF2 <- data.frame(A = c("A", "B", "C"),
                  B = 1:3)
TheList <- list(DF1 = DF1,
                DF2 = DF2)
col_to_rownames_andDel <- function(df){
  rownames(df) <- df$A
  df$A <- NULL
}

TheList_namedRows <- map(TheList, col_to_rownames_andDel) #not working and empties the dfs
</code>```

Thanks!

Sebastian

答:
We can use column_to_rownames from tibble

```<code>library(tibble)
library(purrr)
map(TheList,  column_to_rownames, "A")
#$DF1
#  B
#A 1
#B 2
#C 3

#$DF2
#  B
#A 1
#B 2
#C 3
</code>```

Body:
I have a list of dataframes for which I would like to turn one of their cols into the rownames.
(instead of doing this for every df individually).

Unfortunatly I cant get it to work, maybe someone can help?

DF1 <- data.frame(A = c("A", "B", "C"),
                  B = 1:3)
DF2 <- data.frame(A = c("A", "B", "C"),
                  B = 1:3)
TheList <- list(DF1 = DF1,
                DF2 = DF2)
col_to_rownames_andDel <- function(df){
  rownames(df) <- df$A
  df$A <- NULL
}

TheList_namedRows <- map(TheList, col_to_rownames_andDel) #not working and empties the dfs

Thanks!

Sebastian

Body:
We can use column_to_rownames from tibble

library(tibble)
library(purrr)
map(TheList,  column_to_rownames, "A")
#$DF1
#  B
#A 1
#B 2
#C 3

#$DF2
#  B
#A 1
#B 2
#C 3


问:
Getting the data in console but not able to see any api call data on the screen React Native
Hi i am new to react native. I am trying to call any api and not able to see any data on the app screen but can see the data on the console. I think this issue is with my state but whenever i am trying to add anything on the state it gives me a response "json.data' is not an object. Please guide me on this.Thanks in advance.

export default App = () => {
    const [isLoading, setLoading] = useState(true);

    const [data, setData] = useState([]);

    useEffect(() => {
      fetch('https://URL', {
        method: 'GET',
        timeout: 10000,
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json'
        },
         body: JSON.stringify({
            "this": "",
            "this 2": ""
        })
      })
      .then((response) => response.text())
      .then((responseData) => { console.log(responseData); })
      .then((json)=> setData(text(json.data)))
      .catch((error) => console.error(error))
      .finally(() => setLoading(false)); [];
    }, []);

    return (
        <ScrollView style={styles.container}>
            {isLoading ? <ActivityIndicator /> : (

               <Text> {data.text} </Text>

               <FlatList
                 data={data}
                 renderItem={({ item }) => (
                   <Text>{item.skill}</Text>
                 )}
               />
            )}
        </ScrollView>
    );
};
```

答:
You have to parse the JSON before displaying:

Edit: I replaced response.text() with response.json() to handle the JSON (eg: parse) correctly.

export default App = () => {
    const [isLoading, setLoading] = useState(true);

    const [data, setData] = useState([]);

    useEffect(() => {
      fetch('https://URL', {
        method: 'GET',
        timeout: 10000,
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json'
        },
         body: JSON.stringify({
            "this": "",
            "this 2": ""
        })
      })
      .then((response) => response.json())
      .then((data) => setData(json.data))
      .catch((error) => console.error(error))
      .finally(() => setLoading(false)); [];
    }, []);

    return (
        <ScrollView style={styles.container}>
            {isLoading ? <ActivityIndicator /> : (
               <FlatList
                 data={data}
                 renderItem={({ item }) => (
                   <Text>{item.skill}</Text>
                 )}
               />
            )}
        </ScrollView>
    );
};
```


问:
How to remove a deleted file from git history - including rev-list
I have tried filter-branch, and got to the point where it is removed from git log, but still in rev-list. Then I tried bfg repo cleaner and it still is listed in rev-list. Ultimately I need it to be removed from rev-list because the file is missing from our git lfs server, which causes a git lfs fetch --all to fail...</p>

答: Aha! I found that there were some really old branches that had the file still in HEAD - so I had to use --no-blob-protection. Of course I will now go and check those branches as I know this is actually a dangerous action, but at least bfg shows me these branches. For any future searchers I would suggest running with protection to clear all normal branches - THEN run without protection so that you get ONLY the branches that have the file(s) in head.</p>


问:
Move horizontal Victory Native bar chart to the left
In my React Native app I need to display some bar charts without an axis. However, all the bars are off to the right, as if there was an axis displayed which makes the screen look unbalanced. This is what my screen currently looks like:

I want to pull all those bar charts to the left, so that they are aligned with their labels. Can't seem to figure out how to do such a simple operation. I've tried playing around with the padding, domainPadding and all that to no avail. This is what my code currently looks like:

const MyChart = () => (
  <VictoryGroup
    domainPadding={{ x: 30, y: 0 }}
    theme={VictoryTheme.material}
    domain={{ y: [0, 110] }}
  >
    <VictoryStack>
      {dataSet.map((data, index) => (
          <VictoryBar
            horizontal
            key={index}
            data={data}
            domainPadding={{ x: 0, y: 30 }}
            labels={d => 'Test Bar'}}
            labelComponent={<VictoryLabel dy={-40} x={0} />}
          />
        )
      )}
    </VictoryStack>
  </VictoryGroup>
)
```

答:
My colleague figured this one out and I thought I may as well post the solution in case anyone stumbles upon this with the same issue.

The previously set padding was on the VictoryGroup, and you can't change it using the style prop and need to do so through the padding prop which I had overlooked in the docs.

So basically the lesson taken here was:

1- Was looking at the wrong place for the padding (my focus was on VictoryBar)

2- Do not use the style prop and use the padding prop.

Basically for the example given in the initial post, the solution for the problem would be the following:

const MyChart = () => (
  <VictoryGroup
    domainPadding={{ x: 30, y: 0 }}
    theme={VictoryTheme.material}
    domain={{ y: [0, 110] }}
    padding={{ top: 30, right: 100, bottom: 30, left: 0 }}
  >
    <VictoryStack>
      {dataSet.map((data, index) => (
          <VictoryBar
            horizontal
            key={index}
            data={data}
            domainPadding={{ x: 0, y: 30 }}
            labels={d => 'Test Bar'}}
            labelComponent={<VictoryLabel dy={-40} x={0} />}
          />
        )
      )}
    </VictoryStack>
  </VictoryGroup>
)
```


问:
Redirect if query has no result
I've made a page with an input which connects to this view:

```<code>class SearchResultView(ListView):
    model = RecipeSet

    template_name = 'core/set_result.html'
    context_object_name = 'recipe_set'

    def get_queryset(self):
        query = self.request.GET.get('q')
        object_list = RecipeSet.objects.filter(
            Q(set_name__exact=query)
        )
        if object_list.exists():
            return object_list
        else:
            return redirect('core:dashboard')
</code>```

I've used set_name__exact for this query and want to redirect users if the search returned no objects, how do I go about this? I've tried to use an if/else statement to check the objects but that doesn't seem to work.

答:
The .get_queryset(…) [Django-doc] method should return a QuerySet, not a list, tuple, HttpResponse, etc.

You can however alter the behavior, by setting the allow_empty attribute to allow_empty = False, and override the dispatch method such that in case of a Http404, you redirect:

```<code>from django.http import Http404
from django.shortcuts import redirect

class SearchResultView(ListView):
    <b>allow_empty = False</b>
    model = RecipeSet
    template_name = 'core/set_result.html'
    context_object_name = 'recipe_set'

    def get_queryset(self):
        return RecipeSet.objects.filter(
            set_name=self.request.GET.get('q')
        )

    def <b>dispatch</b>(self, *args, **kwargs):
        try:
            return super().dispatch(*args, **kwargs)
        except <b>Http404</b>:
            return redirect(<i>'core:dashboard'</i>)</code>```

Title: Redirect if query has no result

Body:
I've made a page with an input which connects to this view:

class SearchResultView(ListView):
    model = RecipeSet

    template_name = 'core/set_result.html'
    context_object_name = 'recipe_set'

    def get_queryset(self):
        query = self.request.GET.get('q')
        object_list = RecipeSet.objects.filter(
            Q(set_name__exact=query)
        )
        if object_list.exists():
            return object_list
        else:
            return redirect('core:dashboard')

I've used set_name__exact for this query and want to redirect users if the search returned no objects, how do I go about this? I've tried to use an if/else statement to check the objects but that doesn't seem to work.

Body:
The .get_queryset(…) [Django-doc] method should return a QuerySet, not a list, tuple, HttpResponse, etc.

You can however alter the behavior, by setting the allow_empty attribute to allow_empty = False, and override the dispatch method such that in case of a Http404, you redirect:

from django.http import Http404
from django.shortcuts import redirect

class SearchResultView(ListView):
    allow_empty = False
    model = RecipeSet
    template_name = 'core/set_result.html'
    context_object_name = 'recipe_set'

    def get_queryset(self):
        return RecipeSet.objects.filter(
            set_name=self.request.GET.get('q')
        )

    def dispatch(self, *args, **kwargs):
        try:
            return super().dispatch(*args, **kwargs)
        except Http404:
            return redirect('core:dashboard')


问:
Error submitting Monotouch application - "Unable to locate the metadata-template.xml file within the application"
I'm trying to submit an iPhone application developed in MonoTouch and I'm getting the cryptic error "Unable to locate the metadata-template.xml file within the application".

I'm using the Application Loader and the application runs fine on the simulator and an iPhone.

Any help or pointing me in the right direction would be greatly appreciated.  I don't even know where to start looking...

答: I received this problem and believe it was cause by my incorrectly saving over an Info.plist file in a framework in my post-build script.  After fixing this, I needed to quit Application Loader and resubmit the app for it to go through.</p>

ContentLicense: CC BY-SA 2.5


问:
KeyError on Discord.Py
```<code>@client.command(description="Pauses the current playing track. Can be resumed with `!resume`.",
brief="Pauses current track.",aliases=['PAUSE'])
async def pause(ctx):
    guild_id = ctx.message.guild.id
    players[guild_id].pause()

@client.command(description="Resumes the current playing track. Can only be used if current track has
been paused.",
    brief="Resumes current track.",
    aliases=['RESUME','continue','CONTINUE'])
async def resume(ctx):
    guild_id = ctx.message.guild.id
    players[guild_id].resume()

@client.command(description="Stops the current playing track.",
     brief="Stops current track.",
     aliases=['STOP'])
async def stop(ctx):
    guild_id = ctx.message.guild.id
    players[guild_id].stop()
</code>```

When i try to use the pause, stop and resume command it gives me the KeyError. The whole code that triggers that error is up there. And the error lokks like this:

Ignoring exception in command stop:
Traceback (most recent call last):
  File "C:\Users\emirs\PycharmProjects\discordmasterbot\venv\lib\site-packages\discord\ext\commands\core.py", line 83, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:/Users/emirs/PycharmProjects/discordmasterbot/MASTERBOT.py", line 163, in stop
    players[guild_id].stop()
KeyError: 708748879079932016

And there is an another type of that error:

Traceback (most recent call last):
  File "C:\Users\emirs\PycharmProjects\discordmasterbot\venv\lib\site-packages\discord\ext\commands\bot.py", line 892, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\emirs\PycharmProjects\discordmasterbot\venv\lib\site-packages\discord\ext\commands\core.py", line 797, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\emirs\PycharmProjects\discordmasterbot\venv\lib\site-packages\discord\ext\commands\core.py", line 92, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 708748879079932016

答:
A KeyError means that a key for this object was not found. In this case the guild ID 708748879079932016 does not exist in players.

Try adding a try/except block here to catch any of this.

@client.command(description="Pauses the current playing track. Can be resumed with `!resume`.",
brief="Pauses current track.",aliases=['PAUSE'])
async def pause(ctx):
    try:
        guild_id = ctx.message.guild.id
        players[guild_id].pause()
    except KeyError:
        # do something that adds the guild ID to players #

@client.command(description="Resumes the current playing track. Can only be used if current track has
been paused.",
    brief="Resumes current track.",
    aliases=['RESUME','continue','CONTINUE'])
async def resume(ctx):
    try:
        guild_id = ctx.message.guild.id
        players[guild_id].resume()
    except KeyError:
        # do something that adds the guild ID to players #

@client.command(description="Stops the current playing track.",
     brief="Stops current track.",
     aliases=['STOP'])
async def stop(ctx):
    try:
        guild_id = ctx.message.guild.id
        players[guild_id].stop()
    except KeyError:
        # do something that adds the guild ID to players #
```

Title: KeyError on Discord.Py

Body:
@client.command(description="Pauses the current playing track. Can be resumed with `!resume`.",
brief="Pauses current track.",aliases=['PAUSE'])
async def pause(ctx):
    guild_id = ctx.message.guild.id
    players[guild_id].pause()

@client.command(description="Resumes the current playing track. Can only be used if current track has
been paused.",
    brief="Resumes current track.",
    aliases=['RESUME','continue','CONTINUE'])
async def resume(ctx):
    guild_id = ctx.message.guild.id
    players[guild_id].resume()

@client.command(description="Stops the current playing track.",
     brief="Stops current track.",
     aliases=['STOP'])
async def stop(ctx):
    guild_id = ctx.message.guild.id
    players[guild_id].stop()

When i try to use the pause, stop and resume command it gives me the KeyError. The whole code that triggers that error is up there. And the error lokks like this:

Ignoring exception in command stop:
Traceback (most recent call last):
  File "C:\Users\emirs\PycharmProjects\discordmasterbot\venv\lib\site-packages\discord\ext\commands\core.py", line 83, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:/Users/emirs/PycharmProjects/discordmasterbot/MASTERBOT.py", line 163, in stop
    players[guild_id].stop()
KeyError: 708748879079932016

And there is an another type of that error:

Traceback (most recent call last):
  File "C:\Users\emirs\PycharmProjects\discordmasterbot\venv\lib\site-packages\discord\ext\commands\bot.py", line 892, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\emirs\PycharmProjects\discordmasterbot\venv\lib\site-packages\discord\ext\commands\core.py", line 797, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\emirs\PycharmProjects\discordmasterbot\venv\lib\site-packages\discord\ext\commands\core.py", line 92, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 708748879079932016


问:
how to remove duplicates from Combobox in Javascript?
I fill a combobox via Javascript as follows:

```<code>let option = document.createElement("option");
    option.innerHTML = elem.businessObject.get('id');
    option.value = elem.businessObject.get('id');
    taskTypeEl.appendChild(option);
</code>```

whereby taskTypeE1 refers to the select - tag from my html-code

but unfortunately, I fill my combobox with a lot of duplicates. Is there an easy way
to get rid of that, such that every item only appears once?
Thanks in advance and kind regards

答:
You can define a dictionary before starting the insertion of options, and only add the ones with the values that were not added before:

```<code>    let dictionary = {}; //initiate
</code>```

So when iterating to add the options, you can check if it is unique like this:

```<code>    if(!dictionary[elem.businessObject.get('id')]){ //check for prev insertion
         let option = document.createElement("option");
         option.innerHTML = elem.businessObject.get('id');
         option.value = elem.businessObject.get('id');
         taskTypeEl.appendChild(option);
         dictionary[elem.businessObject.get('id')] = option; //add option
    }
</code>```

Body:
I fill a combobox via Javascript as follows:

let option = document.createElement("option");
    option.innerHTML = elem.businessObject.get('id');
    option.value = elem.businessObject.get('id');
    taskTypeEl.appendChild(option);

whereby taskTypeE1 refers to the select - tag from my html-code

but unfortunately, I fill my combobox with a lot of duplicates. Is there an easy way
to get rid of that, such that every item only appears once?
Thanks in advance and kind regards

Body:
You can define a dictionary before starting the insertion of options, and only add the ones with the values that were not added before:

    let dictionary = {}; //initiate

So when iterating to add the options, you can check if it is unique like this:

    if(!dictionary[elem.businessObject.get('id')]){ //check for prev insertion
         let option = document.createElement("option");
         option.innerHTML = elem.businessObject.get('id');
         option.value = elem.businessObject.get('id');
         taskTypeEl.appendChild(option);
         dictionary[elem.businessObject.get('id')] = option; //add option
    }


问:
How to change the position of HTML elements with JavaScript
I have a site in WordPress and a widget generates this login, but I want to change the position of these two elements, it is a pity that I cannot edit the html code and I can only make the change with JavaScript

I'm trying to get the red down and the green up

I deal with CSS, but not responsive, now I am dealing with JavaScript but I am not very skilled with it

these are the two elements of the HTML

```<code><div class='mo-openid-app-icons'>
<p style='color:#000000; width: fit-content;'> Conectar con Google</p>Login with Google</span></a>
</div> <br><br/>
<a class="lost-pass-link" href="" title="Contraseña perdida">¿Perdiste tu contraseña?</a>
<p class="forgetmenot login-remember">
    <label for="popupRememberme"><input name="rememberme" type="checkbox" value="forever" id="popupRememberme"/>
        Recuérdame
    </label>
</p>
<p class="submit login-submit">
    <input type="submit" name="wp-submit"
    class="button button-primary button-large"
    value="Iniciar sesión"/>

    <input type="hidden" name="redirect_to"
    value="https://bloque10.unimagdalena.edu.co/ovateca/"/>
    <input type="hidden" name="testcookie" value="1"/>
    <input type="hidden" name="nonce" value="77ba00d276"/>
    <input type="hidden" name="eduma_login_user">
</p>
</code>```

I really appreciate any help

答:
You can just take the element and append it to the form, because appendChild(), doesn't create a new element, just take it from its place to the end of parent.

let login = document.querySelector('#loginform');
let google = document.querySelector('.mo-openid-app-icons');
// Move login with google to bottom of the form
login.appendChild(google);
// Do you need to delete those
?
let brs = login.querySelectorAll('br');
brs.forEach((br) => { br.remove(); });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="loginform">
<div class='mo-openid-app-icons'>
<p style='color:#000000; width: fit-content;'> Conectar con Google</p>Login with Google</span></a>
</div> <br><br/>
¿Perdiste tu contraseña?
<p class="forgetmenot login-remember">
    <label for="popupRememberme"><input name="rememberme" type="checkbox" value="forever" id="popupRememberme"/>
        Recuérdame
    </label>
</p>
<p class="submit login-submit">
    <input type="submit" name="wp-submit"
    class="button button-primary button-large"
    value="Iniciar sesión"/>

    <input type="hidden" name="redirect_to"
    value="https://bloque10.unimagdalena.edu.co/ovateca/"/>
    <input type="hidden" name="testcookie" value="1"/>
    <input type="hidden" name="nonce" value="77ba00d276"/>
    <input type="hidden" name="eduma_login_user">
</p>
</form></code>```

Body:
I have a site in WordPress and a widget generates this login, but I want to change the position of these two elements, it is a pity that I cannot edit the html code and I can only make the change with JavaScript

I'm trying to get the red down and the green up

I deal with CSS, but not responsive, now I am dealing with JavaScript but I am not very skilled with it

these are the two elements of the HTML

 Conectar con Google
Login with Google

¿Perdiste tu contraseña?

    <input name="rememberme" type="checkbox" value="forever" id="popupRememberme"/>
        Recuérdame

    <input type="submit" name="wp-submit"
    class="button button-primary button-large"
    value="Iniciar sesión"/>

    <input type="hidden" name="redirect_to"
    value="https://bloque10.unimagdalena.edu.co/ovateca/"/>
    <input type="hidden" name="testcookie" value="1"/>
    <input type="hidden" name="nonce" value="77ba00d276"/>
    <input type="hidden" name="eduma_login_user">

I really appreciate any help

Body:
You can just take the element and append it to the form, because appendChild(), doesn't create a new element, just take it from its place to the end of parent.

let login = document.querySelector('#loginform');
let google = document.querySelector('.mo-openid-app-icons');
// Move login with google to bottom of the form
login.appendChild(google);
// Do you need to delete those <br>?
let brs = login.querySelectorAll('br');
brs.forEach((br) => { br.remove(); });

<form id="loginform">
<div class='mo-openid-app-icons'>
<p style='color:#000000; width: fit-content;'> Conectar con Google</p>Login with Google</span></a>
</div> <br><br/>
<a class="lost-pass-link" href="" title="Contraseña perdida">¿Perdiste tu contraseña?</a>
<p class="forgetmenot login-remember">
    <label for="popupRememberme"><input name="rememberme" type="checkbox" value="forever" id="popupRememberme"/>
        Recuérdame
    </label>
</p>
<p class="submit login-submit">
    <input type="submit" name="wp-submit"
    class="button button-primary button-large"
    value="Iniciar sesión"/>

    <input type="hidden" name="redirect_to"
    value="https://bloque10.unimagdalena.edu.co/ovateca/"/>
    <input type="hidden" name="testcookie" value="1"/>
    <input type="hidden" name="nonce" value="77ba00d276"/>
    <input type="hidden" name="eduma_login_user">
</p>
</form>


问:
Import from other module
I write project using Java and Maven. In project I have many modules. My problem is that I can not import classes from other module.

My project structure looks like this:

```<code>Project
 |_ module1
    |_ src
       |_ com.xyz.project.md1
          |_ Person.java
    |_ pom.xml <- pom of module1
 |_ module2
    |_ src
       |_ com.xyz.project.md2
          |_ Robot.java
    |_ pom.xml <- pom of module2
 |_ pom.xml <- main Project pom
</code>```

module1 and module2 are Modules in my project, which are registred in pom.xml - main Project pom

And when I am in Person.java from module1 I want import the Robot.java from module2 but I can not do this with import com.xyz.project.md2.Robot. Why ?

答:
In build.gradle of module 2:

```<code>dependencies {
    compile(project(":module1")) {
        transitive = false
    }
     ...
     //Other dependencies
     ...
}
</code>```

transitive = false ensures dependencies of dependencies are not imported . Only your source part is imported

N.B. - Though the question uses Maven, but most of us use Gradle.

Title: Import from other module

Body:
I write project using Java and Maven. In project I have many modules. My problem is that I can not import classes from other module.

My project structure looks like this:

Project
 |_ module1
    |_ src
       |_ com.xyz.project.md1
          |_ Person.java
    |_ pom.xml <- pom of module1
 |_ module2
    |_ src
       |_ com.xyz.project.md2
          |_ Robot.java
    |_ pom.xml <- pom of module2
 |_ pom.xml <- main Project pom

module1 and module2 are Modules in my project, which are registred in pom.xml - main Project pom

And when I am in Person.java from module1 I want import the Robot.java from module2 but I can not do this with import com.xyz.project.md2.Robot. Why ?

Body:
In build.gradle of module 2:

dependencies {
    compile(project(":module1")) {
        transitive = false
    }
     ...
     //Other dependencies
     ...
}

transitive = false ensures dependencies of dependencies are not imported . Only your source part is imported

N.B. - Though the question uses Maven, but most of us use Gradle.


问:
Associate color with number in matplotlib scatterplot
I'm using sklearn to do a kmeans cluster based on some retail data.
 We're using this cluster behind the scenes to segment customers (e.g., Blue customers are great, green customers have such-and-such a need, etc.).
 The datapoints shown are a different color based on which of 4 clusters a customer has been put into.  But I can't find a way to directly infer which color is which segment number (or how to force certain segment numbers to be a certain color).

c=y in the scatter is where it's using the value of y (i.e., the predicted segment for an observation) to pick the color.  There are 4 segments.  I just don't know which of those 4 gets mapped to which color!
Can someone please advise on how I can add a legend, or force the color myself?

```<code>kmeans=kmeans.fit(X)
y=kmeans.predict(X)

fig = plt.figure()
ax = Axes3D(fig)
ax.view_init(30)
ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=y)
ax.set_xlabel(vx)
ax.set_ylabel(vy)
ax.set_zlabel(vz)
</code>```

答:
You need to return a handle from scatter and plot colorbar,

```<code>cm = ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=y)
plt.colorbar(cm)
</code>```

As a minimal example

```<code>import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

X = np.random.randn(100,3)
y = np.random.randn(100)

fig = plt.figure()
ax = Axes3D(fig)
ax.view_init(30)
cm = ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=y)
plt.colorbar(cm)
plt.show()
</code>```

Body:
I'm using sklearn to do a kmeans cluster based on some retail data.
 We're using this cluster behind the scenes to segment customers (e.g., Blue customers are great, green customers have such-and-such a need, etc.).
 The datapoints shown are a different color based on which of 4 clusters a customer has been put into.  But I can't find a way to directly infer which color is which segment number (or how to force certain segment numbers to be a certain color).

c=y in the scatter is where it's using the value of y (i.e., the predicted segment for an observation) to pick the color.  There are 4 segments.  I just don't know which of those 4 gets mapped to which color!
Can someone please advise on how I can add a legend, or force the color myself?

kmeans=kmeans.fit(X)
y=kmeans.predict(X)

fig = plt.figure()
ax = Axes3D(fig)
ax.view_init(30)
ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=y)
ax.set_xlabel(vx)
ax.set_ylabel(vy)
ax.set_zlabel(vz)

Body:
You need to return a handle from scatter and plot colorbar,

cm = ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=y)
plt.colorbar(cm)

As a minimal example

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

X = np.random.randn(100,3)
y = np.random.randn(100)

fig = plt.figure()
ax = Axes3D(fig)
ax.view_init(30)
cm = ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=y)
plt.colorbar(cm)
plt.show()


问:
How can I delete all texts in my data using dplyr?
If my data looks like this:

```<code>q2_3  q2_4  q2_5
<chr> <chr> <chr>
1    1A    2B   3C
2    4D    5E   6F
</code>```

How can I delete only texts?

I want only numbers to remain!

答:
Another option with mutate/across

```<code>library(dplyr)
library(stringr)
df1 %>%
    mutate(across(everything(), str_remove_all, "\\D+"))
#    q2_3 q2_4 q2_5
#1    1    2    3
#2    4    5    6
</code>```

data

```<code>df1 <-  structure(list(q2_3 = c("1A", "4D"), q2_4 = c("2B", "5E"), q2_5 = c("3C",
"6F")), class = "data.frame", row.names = c("1", "2"))
</code>```

Body:
If my data looks like this:

q2_3  q2_4  q2_5
<chr> <chr> <chr>
1    1A    2B   3C
2    4D    5E   6F

How can I delete only texts?

I want only numbers to remain!

Body:
Another option with mutate/across

library(dplyr)
library(stringr)
df1 %>%
    mutate(across(everything(), str_remove_all, "\\D+"))
#    q2_3 q2_4 q2_5
#1    1    2    3
#2    4    5    6

data

df1 <-  structure(list(q2_3 = c("1A", "4D"), q2_4 = c("2B", "5E"), q2_5 = c("3C",
"6F")), class = "data.frame", row.names = c("1", "2"))


问:
Solving function containing gamma in Python
I'm quite new to programming with python.

I was wondering, if there is a smart way to solve a function, which includes a gamma function with a certain shape and scale.

I already created a function G(x), which is the cdf of a gamma function up to a variable x. Now I want to solve another function including G(x). It should look like: 0=x+2*G(x)-b. Where b is a constant.

My code looks like that:

```<code>b= 10

def G(x):
  return gamma.cdf(x,a=4,scale=25)

f = solve(x+2*G(x)-b,x,dict=True)
</code>```

How is it possible to get a real value for G(x) in my solve function?

Thanks in advance!

答:
To get roots from a function there are several tools in the scipy module.

Here is a solution with the method fsolve()

```<code>from scipy.stats import gamma
from scipy.optimize import fsolve

def G(x):
  return gamma.cdf(x,a=4,scale=25)

# we define the function to solve
def f(x,b):
  return x+2*G(x)-b

b = 10
init = 0. # The starting estimate for the roots of f(x) = 0.
roots = fsolve(f,init,args=(b))

print roots
</code>```

Gives output :

```<code>[9.99844838]
</code>```

Given that G(10) is close to zero this solution seems likely

Sorry, I didn't take into account your dict=True option but I guess you are able to put the result in whatever structure you want without my help.

Body:
I'm quite new to programming with python.

I was wondering, if there is a smart way to solve a function, which includes a gamma function with a certain shape and scale.

I already created a function G(x), which is the cdf of a gamma function up to a variable x. Now I want to solve another function including G(x). It should look like: 0=x+2*G(x)-b. Where b is a constant.

My code looks like that:

b= 10

def G(x):
  return gamma.cdf(x,a=4,scale=25)

f = solve(x+2*G(x)-b,x,dict=True)

How is it possible to get a real value for G(x) in my solve function?

Thanks in advance!

Body:
To get roots from a function there are several tools in the scipy module.

Here is a solution with the method fsolve()

from scipy.stats import gamma
from scipy.optimize import fsolve

def G(x):
  return gamma.cdf(x,a=4,scale=25)

# we define the function to solve
def f(x,b):
  return x+2*G(x)-b

b = 10
init = 0. # The starting estimate for the roots of f(x) = 0.
roots = fsolve(f,init,args=(b))

print roots

Gives output :

[9.99844838]

Given that G(10) is close to zero this solution seems likely

Sorry, I didn't take into account your dict=True option but I guess you are able to put the result in whatever structure you want without my help.


问:
Multiplying characters in a vector in R
Suppose I have the vector:

```<code>x = c("a","b","c")
</code>```

I would like to create a function that returns the following:

```<code>[1] "a*b" "a*c" "b*c"
</code>```

I assume we would use the paste0() function or use some sort of for loop to loop through the characters in the vector but I am not fully sure how to go about this. Just to clarify, I am looking for an output that takes two characters from the vector at a time and uses some sort of paste0(...,sep="*") to get the desired output above. I do not want to multiply all the characters in the vector at once, just two characters at a time.

答:
You can use a recursion function which may be faster.</p>

```<code>foo = function(x, sep = "*") {
    if (length(x) < 2) {
        return(x)
    }

    ans = paste(x[1], x[-1], sep = sep)

    if (length(x) > 2) {
        ans = c(ans, Recall(x[-1]))
    }

    return(ans)
}

foo(c("a", "b", "c"))
#[1] "a*b" "a*c" "b*c"
</code>```

Title: Multiplying characters in a vector in R

Body:
Suppose I have the vector:

x = c("a","b","c")

I would like to create a function that returns the following:

[1] "a*b" "a*c" "b*c"

I assume we would use the paste0() function or use some sort of for loop to loop through the characters in the vector but I am not fully sure how to go about this. Just to clarify, I am looking for an output that takes two characters from the vector at a time and uses some sort of paste0(...,sep="*") to get the desired output above. I do not want to multiply all the characters in the vector at once, just two characters at a time.

Body:
You can use a recursion function which may be faster.

foo = function(x, sep = "*") {
    if (length(x) < 2) {
        return(x)
    }

    ans = paste(x[1], x[-1], sep = sep)

    if (length(x) > 2) {
        ans = c(ans, Recall(x[-1]))
    }

    return(ans)
}

foo(c("a", "b", "c"))
#[1] "a*b" "a*c" "b*c"


问:
Local git repo creation
I have code base checked out from svn. (code_base). I want to create a local git repo from this code base and then use git branches to play with it. So, I am expecting a structure like follows:

currently available code = c:/code_base

git repo on same machine = c:/repo_head  (Based on c:/code_base)

git clients from newly repo = c:/repo_client1 c:/repo_client2

I am trying to create a bare repo (repo_head) and then trying to add code_base but it does not seem to work. I am getting lot of errors.
What is the best way to go about it?

答:
If your svn repo contains tags and branches you could consider using git svn to import your svn repo to a git repo. In any case it's also great to keep the history of your project.

git svn clone -s svn_url dir_for_git

Title: Local git repo creation


问:
Conditional ForeColor of GridView Label in javascript
I have the following in my asp Label:

```<code>ForeColor='<%# Eval("Comportement").Equals(3) ? System.Drawing.ColorTranslator.FromHtml("#ff4c4c") : System.Drawing.Color.Empty %>
</code>```

It works fine if the value equals 3 but I want to format if the value is lower than 3. Plus I need to manage a possible null, which is throwing me an error with the above.

Code behind would be ok if simpler.

答:
I found it.</p>

```<code>ForeColor='<%# !Convert.IsDBNull(Eval("Comportement")) && Convert.ToInt32(Eval("Comportement")) < 3 ? System.Drawing.ColorTranslator.FromHtml("#ff4c4c") : System.Drawing.Color.Empty %>'
</code>```

Body:
I have the following in my asp Label:

ForeColor='<%# Eval("Comportement").Equals(3) ? System.Drawing.ColorTranslator.FromHtml("#ff4c4c") : System.Drawing.Color.Empty %>

It works fine if the value equals 3 but I want to format if the value is lower than 3. Plus I need to manage a possible null, which is throwing me an error with the above.

Code behind would be ok if simpler.

Body:
I found it.

ForeColor='<%# !Convert.IsDBNull(Eval("Comportement")) && Convert.ToInt32(Eval("Comportement")) < 3 ? System.Drawing.ColorTranslator.FromHtml("#ff4c4c") : System.Drawing.Color.Empty %>'


答:
Personally I would just change the .exists to .count:</p>

```<code>class SearchResultView(ListView):
model = RecipeSet

template_name = 'core/set_result.html'
context_object_name = 'recipe_set'

def get_queryset(self):
    query = self.request.GET.get('q')
    object_list = RecipeSet.objects.filter(
        Q(set_name__exact=query)
    )
    if object_list.count():
        return object_list
    else:
        return redirect('core:dashboard')
</code>```

Title: Redirect if query has no result

Body:
I've made a page with an input which connects to this view:

class SearchResultView(ListView):
    model = RecipeSet

    template_name = 'core/set_result.html'
    context_object_name = 'recipe_set'

    def get_queryset(self):
        query = self.request.GET.get('q')
        object_list = RecipeSet.objects.filter(
            Q(set_name__exact=query)
        )
        if object_list.exists():
            return object_list
        else:
            return redirect('core:dashboard')

I've used set_name__exact for this query and want to redirect users if the search returned no objects, how do I go about this? I've tried to use an if/else statement to check the objects but that doesn't seem to work.

Body:
Personally I would just change the .exists to .count:

class SearchResultView(ListView):
model = RecipeSet

template_name = 'core/set_result.html'
context_object_name = 'recipe_set'

def get_queryset(self):
    query = self.request.GET.get('q')
    object_list = RecipeSet.objects.filter(
        Q(set_name__exact=query)
    )
    if object_list.count():
        return object_list
    else:
        return redirect('core:dashboard')


问:
When using Yad, can a button be made the default?
The title sets the question.
If it can, what is the coding?
Present coding is:-
yad --center --on-top --text-align=center --buttons-layout=center --title ${0##*/} --width=150 --height=60 --text "Do you want tea?" --button=gtk-no:1 --button=gtk-yes:0
I want to make the yes button the default, so even if I just close the box the yes button is selected.
Many thanks
John</p>

答:
Found out that $? for Yes=0, for No=1 and Close=252,
so coding externally allowed to make the Yes button
the default.
:-</p>

```<code>if [[ $? == 0 || $? == 252 ]]
then
echo "Default"
else
echo "No"
fi
</code>```

Body:
Found out that $? for Yes=0, for No=1 and Close=252,
so coding externally allowed to make the Yes button
the default.
:-

if [[ $? == 0 || $? == 252 ]]
then
echo "Default"
else
echo "No"
fi


问:
VSCode intellisense not work when you click "Tab"
Can someone help me with my problem?
HOW do I fix this EMMET VSCode so that when I write "log" and click " tab "I get" intellisense " and can select a variable?

On the video in the first version of the error, "intellisense" is missing. Then in the video, the second version of "intellisense" appears. I don't want to write every time to the manual console.log(), but if I press "Tab", "intellisense" doesn't appear automatically, I have to press CTRL + Space.

Don't ask me to manually press CTRL + Space every time, I want to know how to do everything automatically?

Here is an example in the video

答:
When I write log and press TAB I get console.log(<text Focus is here>) as a result.

If I immediately start writing the name of the variable st.. then intellisense does not appear. The video clearly shows this.


问:
Why can't Bundler locate this gem?
Why can't bundler locate the Mechanize gem?

The following is in my Rails project's Gemfile:

```<code>gem 'mechanize', :git => 'git://github.com/tenderlove/mechanize.git'
</code>```

Running bundle install throws the following error:

```<code>Updating git://github.com/tenderlove/mechanize.git
Fetching source index for http://rubygems.org/
Could not find gem 'mechanize (>= 0)' in git://github.com/tenderlove/mechanize.git (at master).
Source does not contain any versions of 'mechanize (>= 0)'
</code>```

I arrived at this problem after forking the project to make some small changes, but was not able to get bundler to use the github location nor a local path. Why is it that it cannot locate the gem?

If I remove all instructions and simply do gem 'mechanize' then it works flawlessly.

Versions: Bundler 1.0.14 + Rails 3.1 Release Canditate + Ruby 1.8.7 (via RVM) + Debian 5

答:
In case someone stumbles upon this thread in the future, here's what I did to make it work..

I forked the project, made my changes then ran the following to generate a .gemspec:

```<code>rake debug_gem | grep -v "(in " > `basename \`pwd\``.gemspec
</code>```

I had to make a slight modification because the gemspec was trying to include a .gemtest file which did not exist.

I then modified my Gemfile to source from the path:

```<code>gem 'mechanize', :path => '/my_rails_app/vendor/gems/mechanize'
</code>```

I then ran bundle install and everything went through without a hitch.

Title: Why can't Bundler locate this gem?

Body:
Why can't bundler locate the Mechanize gem?

The following is in my Rails project's Gemfile:

gem 'mechanize', :git => 'git://github.com/tenderlove/mechanize.git'

Running bundle install throws the following error:

Updating git://github.com/tenderlove/mechanize.git
Fetching source index for http://rubygems.org/
Could not find gem 'mechanize (>= 0)' in git://github.com/tenderlove/mechanize.git (at master).
Source does not contain any versions of 'mechanize (>= 0)'

I arrived at this problem after forking the project to make some small changes, but was not able to get bundler to use the github location nor a local path. Why is it that it cannot locate the gem?

If I remove all instructions and simply do gem 'mechanize' then it works flawlessly.

Versions: Bundler 1.0.14 + Rails 3.1 Release Canditate + Ruby 1.8.7 (via RVM) + Debian 5

Body:
In case someone stumbles upon this thread in the future, here's what I did to make it work..

I forked the project, made my changes then ran the following to generate a .gemspec:

rake debug_gem | grep -v "(in " > `basename \`pwd\``.gemspec

I had to make a slight modification because the gemspec was trying to include a .gemtest file which did not exist.

I then modified my Gemfile to source from the path:

gem 'mechanize', :path => '/my_rails_app/vendor/gems/mechanize'

I then ran bundle install and everything went through without a hitch.


问:
Is it possible to have efficient timestamp ordered queries in spanner?
I have followed this article https://cloud.google.com/blog/products/gcp/sharding-of-timestamp-ordered-data-in-cloud-spanner and created a somewhat similar schema just without companyID:

```<code>CREATE TABLE Foo (
  random_id       STRING(22) NOT NULL,
  shard_id              INT64 NOT NULL,
  timestamp_order    TIMESTAMP NOT NULL OPTIONS (allow_commit_timestamp=true),
) PRIMARY KEY(random_id);
CREATE INDEX OrderIndex ON Foo(shard_id, timestamp_order);
</code>```

shard_id is a random number from 0 to 49. Then I am running a bunch of selects against it:

```<code>1: SELECT * FROM Foo@{FORCE_INDEX=OrderIndex} where shard_id=0 order by timestamp_order limit 1;
# this correctly scans 1 row

2: SELECT * FROM Foo@{FORCE_INDEX=OrderIndex} where shard_id<1 order by timestamp_order limit 1;
# this scans 192 rows

3: SELECT * FROM Foo@{FORCE_INDEX=OrderIndex} where shard_id BETWEEEN 1 AND 1 order by timestamp_order limit 1;
# this scans 185 rows

4: SELECT * FROM Foo@{FORCE_INDEX=OrderIndex} where shard_id BETWEEN 0 AND 1 order by timestamp_order limit 1;
# this scans 377 rows
</code>```

I expected something like this:

```<code>Query #2 should scan 1 row
Query #3 should scan 1 row
Query #4 should scan 2 rows.
</code>```

Question: what am I doing wrong here? Is it possible to have efficient timestamp ordered queries in spanner?

答:
I saw the comment about an arbitrary LIMIT.  This was too long for a followup comment (not permitted) so I added another answer.

For an arbitrary LIMIT, a more complex query is required to get the highest efficiency.  Here is a template using the filter "shard_id < 1000" and LIMIT x.

The first side of the join will efficiently extract the qualifying shard_id values, very like the original query with LIMIT 1.  The second side of the join will go back to the table and fetch the top x rows for each shard_id.  The parent will then select the top x across all the qualifying shard_is values.  If there are many timestamps per shard_id then this will be very efficient.

```<code>SELECT ff.*
FROM
(
  SELECT shard_id
  FROM Foo@{FORCE_INDEX=OrderIndex,
  GROUPBY_SCAN_OPTIMIZATION=true}
  WHERE shard_id < 1000
  GROUP BY shard_id
) shards
JOIN UNNEST(ARRAY
(
  SELECT AS STRUCT *
  FROM Foo@{FORCE_INDEX=OrderIndex} AS f
  WHERE f.shard_id = shards.shard_id
  ORDER BY timestamp_order
  LIMIT x
)) AS ff
ORDER BY ff.timestamp_order
LIMIT x;
</code>```

Body:
I have followed this article https://cloud.google.com/blog/products/gcp/sharding-of-timestamp-ordered-data-in-cloud-spanner and created a somewhat similar schema just without companyID:

CREATE TABLE Foo (
  random_id       STRING(22) NOT NULL,
  shard_id              INT64 NOT NULL,
  timestamp_order    TIMESTAMP NOT NULL OPTIONS (allow_commit_timestamp=true),
) PRIMARY KEY(random_id);
CREATE INDEX OrderIndex ON Foo(shard_id, timestamp_order);

shard_id is a random number from 0 to 49. Then I am running a bunch of selects against it:

1: SELECT * FROM Foo@{FORCE_INDEX=OrderIndex} where shard_id=0 order by timestamp_order limit 1;
# this correctly scans 1 row

2: SELECT * FROM Foo@{FORCE_INDEX=OrderIndex} where shard_id<1 order by timestamp_order limit 1;
# this scans 192 rows

3: SELECT * FROM Foo@{FORCE_INDEX=OrderIndex} where shard_id BETWEEEN 1 AND 1 order by timestamp_order limit 1;
# this scans 185 rows

4: SELECT * FROM Foo@{FORCE_INDEX=OrderIndex} where shard_id BETWEEN 0 AND 1 order by timestamp_order limit 1;
# this scans 377 rows

I expected something like this:

Query #2 should scan 1 row
Query #3 should scan 1 row
Query #4 should scan 2 rows.

Question: what am I doing wrong here? Is it possible to have efficient timestamp ordered queries in spanner?

Body:
I saw the comment about an arbitrary LIMIT.  This was too long for a followup comment (not permitted) so I added another answer.

For an arbitrary LIMIT, a more complex query is required to get the highest efficiency.  Here is a template using the filter "shard_id < 1000" and LIMIT x.

The first side of the join will efficiently extract the qualifying shard_id values, very like the original query with LIMIT 1.  The second side of the join will go back to the table and fetch the top x rows for each shard_id.  The parent will then select the top x across all the qualifying shard_is values.  If there are many timestamps per shard_id then this will be very efficient.

SELECT ff.*
FROM
(
  SELECT shard_id
  FROM Foo@{FORCE_INDEX=OrderIndex,
  GROUPBY_SCAN_OPTIMIZATION=true}
  WHERE shard_id < 1000
  GROUP BY shard_id
) shards
JOIN UNNEST(ARRAY
(
  SELECT AS STRUCT *
  FROM Foo@{FORCE_INDEX=OrderIndex} AS f
  WHERE f.shard_id = shards.shard_id
  ORDER BY timestamp_order
  LIMIT x
)) AS ff
ORDER BY ff.timestamp_order
LIMIT x;


问:
SwiftUI - Conditional based on ObservedObject doesn't work in subsequent Views
I have a very simple app which contains two views that are tied together with a NavigationLink. In the first view, ContentView, I can see updates to my ObservedObject as expected. However, when I go to the next View, it seems that the code based on the ObservedObject does not recognize changes.

ContentView.swift (The working view):

```<code>import SwiftUI

struct ContentView: View {
    @ObservedObject var toggleObject = ToggleObject()

    var body: some View {
        NavigationView {
            VStack(spacing: 15) {
                Toggle(isOn: self.$toggleObject.isToggled) {
                    Text("Toggle:")
                }

                if self.toggleObject.isToggled == true {
                    Text("ON")
                }
                else {
                    Text("OFF")
                }

                NavigationLink(destination: ShowToggleView()) {
                    Text("Show Toggle Status")
                }
            }
        }
    }
}
</code>```

ShowToggleView.swift (The view that does not behave as I expect it to):

```<code>import SwiftUI

struct ShowToggleView: View {
    @ObservedObject var toggleObject = ToggleObject()

    var body: some View {
        Form {
            Section {
                if self.toggleObject.isToggled {
                    Text("Toggled on")
                }
                else {
                    Text("Toggled off")
                }
            }
        }
    }
}
</code>```

All of this data is stored in a simple file, ToggleObject.swift:

```<code>import SwiftUI

class ToggleObject: ObservableObject {
    @Published var isToggled = false
}
</code>```

When I toggle it on in the first View I see the text "ON" which is expected, but when I go into the next view it shows "Toggled off" no matter what I do in the first View... Why is that?

Using Xcode 11.5 and Swift 5

答:
You are almost doing everything correct. However, you are creating another instance of ToggleObject() in your second view, which overrides the data. You basically only create one ObservedObject and then pass it to your subview, so they both access the same data.

Change it to this:

```<code>struct ShowToggleView: View {
    @ObservedObject var toggleObject : ToggleObject
</code>```

And then pass the object to that view in your navigation link...

```<code>NavigationLink(destination: ShowToggleView(toggleObject: self.toggleObject)) {
    Text("Show Toggle Status")
}
</code>```

Body:
I have a very simple app which contains two views that are tied together with a NavigationLink. In the first view, ContentView, I can see updates to my ObservedObject as expected. However, when I go to the next View, it seems that the code based on the ObservedObject does not recognize changes.

ContentView.swift (The working view):

import SwiftUI

struct ContentView: View {
    @ObservedObject var toggleObject = ToggleObject()

    var body: some View {
        NavigationView {
            VStack(spacing: 15) {
                Toggle(isOn: self.$toggleObject.isToggled) {
                    Text("Toggle:")
                }

                if self.toggleObject.isToggled == true {
                    Text("ON")
                }
                else {
                    Text("OFF")
                }

                NavigationLink(destination: ShowToggleView()) {
                    Text("Show Toggle Status")
                }
            }
        }
    }
}

ShowToggleView.swift (The view that does not behave as I expect it to):

import SwiftUI

struct ShowToggleView: View {
    @ObservedObject var toggleObject = ToggleObject()

    var body: some View {
        Form {
            Section {
                if self.toggleObject.isToggled {
                    Text("Toggled on")
                }
                else {
                    Text("Toggled off")
                }
            }
        }
    }
}

All of this data is stored in a simple file, ToggleObject.swift:

import SwiftUI

class ToggleObject: ObservableObject {
    @Published var isToggled = false
}

When I toggle it on in the first View I see the text "ON" which is expected, but when I go into the next view it shows "Toggled off" no matter what I do in the first View... Why is that?

Using Xcode 11.5 and Swift 5

Body:
You are almost doing everything correct. However, you are creating another instance of ToggleObject() in your second view, which overrides the data. You basically only create one ObservedObject and then pass it to your subview, so they both access the same data.

Change it to this:

struct ShowToggleView: View {
    @ObservedObject var toggleObject : ToggleObject

And then pass the object to that view in your navigation link...

NavigationLink(destination: ShowToggleView(toggleObject: self.toggleObject)) {
    Text("Show Toggle Status")
}


问:
Practical difference between a struct with only operator() and a normal function
I have seen code that looks like this:

struct foo_functor {
  template <typename T, typename U>
  constexpr auto operator()(T t, U u) const -> decltype(t | u) {
    return t | u;
  }
};

constexpr foo_functor foo;
```

<p>As far as I can tell, it's the same as the following:</p>

<pre class="lang-cpp prettyprint-override"><code>template <typename T, typename U>
constexpr auto foo(T t, U u) -> decltype(t | u) {
  return t | u;
}
</code>```

Why would you want to do the first one? Are there any differences? As far as I could see from the compiler output, at least with constexpr, there wasn't. What about if they weren't constexpr, would there be any differences in that case?

Edit: As a note, code very similar to the first example was seemingly being used in place of normal functions. 6 different structures, all with only operator() templates, all were instantiated like the last line of the example. Each was then used exactly like a normal function.

答:
Someone suggested in the comments that a function object can have additional state. While this is true, I would be a bit more specific: you can create multiple copies of a function object with varying state. If the function object is singleton, then this point is moot; a function can also have state in the form of global variables.

And if your function object is declared constexpr, then none of its internal state can be mutable. This puts it in the same position as a constexpr function: calling it can be a constant expression but only as long as it doesn't access any non-constant-expression global state.

One important difference before C++17 is that functions could be inline, whereas objects could not be. In C++14, if you defined the functor foo in a header, then there would be one copy of it per translation unit. If you needed foo to have the same address in all translation units, you would need to declare it as an inline function. But in C++17, function objects can be inline too.

But even if you only have a single instance of the function object, and it has no state, and you are using C++17 or later, there is still at least one important difference between that and a function: functions can be found by argument-dependent lookup, whereas function objects cannot. This is the reason why some "functions" in the C++20 Ranges library actually cannot be functions at all, and must be function objects. These are informally referred to as niebloids.

Body:
I have seen code that looks like this:

struct foo_functor {
  template <typename T, typename U>
  constexpr auto operator()(T t, U u) const -> decltype(t | u) {
    return t | u;
  }
};

constexpr foo_functor foo;

As far as I can tell, it's the same as the following:

template <typename T, typename U>
constexpr auto foo(T t, U u) -> decltype(t | u) {
  return t | u;
}

Why would you want to do the first one? Are there any differences? As far as I could see from the compiler output, at least with constexpr, there wasn't. What about if they weren't constexpr, would there be any differences in that case?

Edit: As a note, code very similar to the first example was seemingly being used in place of normal functions. 6 different structures, all with only operator() templates, all were instantiated like the last line of the example. Each was then used exactly like a normal function.


问:
How do I include a custom JS (JQuery) file in a .tpl?
So I have an HTML page that I want to take apart and put into my website in a more developer friendly manner. I was using Iframes but now I decided to integrate it into my .tpl file. For the life of me I can't figure out how to include a custom js file in the .tpl The way other files are included is in a php file but this is just to include the config file. I managed to put the HTML in the .tpl fine, the last part I need is the javascript. I believe the issue is that the JS is uses Jquery so I need to include that library but I can't seem to make it work. Any ideas? I've used literal and that didn't work either....

I can provide code examples on reqeust

答:
I suspect when you say "tpl" you mean a Smarty template. (Which is a more popular tag than "tpl")

Ideally, your existing template system should be set up so that there is either some convention (ex. {capture}) or some other facility (like a plugin) that lets you to "retroactively" place  into the  of the document.

However, you can also put the  tags into the body of the page at an appropriate spot.

If you are trying to directly enter javascript directly, you will almost certainly require Smarty {literal} protection, but that is only because otherwise Smarty will explode trying to handle all of Javascript's { and } if they are directly inside the tpl file.

Body:
I suspect when you say "tpl" you mean a Smarty template. (Which is a more popular tag than "tpl")

Ideally, your existing template system should be set up so that there is either some convention (ex. {capture}) or some other facility (like a plugin) that lets you to "retroactively" place <script type="text/javascript" src="xxx.js"></script> into the <head> of the document.

However, you can also put the <script></script> tags into the body of the page at an appropriate spot.

If you are trying to directly enter javascript directly, you will almost certainly require Smarty {literal} protection, but that is only because otherwise Smarty will explode trying to handle all of Javascript's { and } if they are directly inside the tpl file.


问:
Identify duplicate rows with pandas and convert such rows into one row, creating a new columns as a result
I have a dataset of stations

```<code>    map_id  longitude   latitude  zip_code
0   40830 -87.669147  41.857908     60608
1   40830 -87.669147  41.857908     60608
2   40120 -87.680622  41.829353     60609
3   40120 -87.680622  41.829353     60609
4   41120 -87.625826  41.831677     60616
</code>```

As you can see, the first four rows are duplications and it is not an accident. They are the same stations, which are treated as separate stations of different lines.

I would like to eliminate such duplicates (it can be 2 or even 5 rows for some stations) and treat it as one station.

Moreover, I would like to create a new column "Hub", where aggregated rows will be treated a hub station. For example, as a boolean (0 for a regular station, 1 for a hub).

The desired output for the sample above with two cases of duplication -> transformed into 3 rows with 2 hubs.

```<code>    map_id  longitude   latitude  zip_code    hub
0   40830 -87.669147  41.857908     60608      1
1   40120 -87.680622  41.829353     60609      1
1   41120 -87.625826  41.831677     60616      0
</code>```

I appreciate any tips!

Body:
I have a dataset of stations

    map_id  longitude   latitude  zip_code
0   40830 -87.669147  41.857908     60608
1   40830 -87.669147  41.857908     60608
2   40120 -87.680622  41.829353     60609
3   40120 -87.680622  41.829353     60609
4   41120 -87.625826  41.831677     60616

As you can see, the first four rows are duplications and it is not an accident. They are the same stations, which are treated as separate stations of different lines.

I would like to eliminate such duplicates (it can be 2 or even 5 rows for some stations) and treat it as one station.

Moreover, I would like to create a new column "Hub", where aggregated rows will be treated a hub station. For example, as a boolean (0 for a regular station, 1 for a hub).

The desired output for the sample above with two cases of duplication -> transformed into 3 rows with 2 hubs.

    map_id  longitude   latitude  zip_code    hub
0   40830 -87.669147  41.857908     60608      1
1   40120 -87.680622  41.829353     60609      1
1   41120 -87.625826  41.831677     60616      0

I appreciate any tips!

Body:
df = df.groupby(['map_id','longitude','latitude','zip_code']).size().reset_index(name='hub')

df['hub'] = df['hub'].replace(1,0).apply(lambda x:min(x,1))

Output

   map_id  longitude   latitude  zip_code  hub
0   40120 -87.680622  41.829353     60609    1
1   40830 -87.669147  41.857908     60608    1
2   41120 -87.625826  41.831677     60616    0


问:
How to change UIButton image in Swift
I am trying to change the image of a UIButton using Swift...
What should I do

This is OBJ-C code.but I don't know with Swift:

```<code>[playButton setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];
</code>```

答:
Swift 5 and ensures the image scales to the size of the button but stays within the buttons bounds.</p>

```<code>yourButton.clipsToBounds = true
yourButton.contentMode = .scaleAspectFill

// Use setBackgroundImage or setImage
yourButton.setBackgroundImage(UIImage(named: "yourImage"), for: .normal)
</code>```

Title: How to change UIButton image in Swift

Body:
I am trying to change the image of a UIButton using Swift...
What should I do

This is OBJ-C code.but I don't know with Swift:

[playButton setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];

Body:
Swift 5 and ensures the image scales to the size of the button but stays within the buttons bounds.

yourButton.clipsToBounds = true
yourButton.contentMode = .scaleAspectFill

// Use setBackgroundImage or setImage
yourButton.setBackgroundImage(UIImage(named: "yourImage"), for: .normal)


问:
How can I increase the disk space in AWS Fargate container?
I am deploying containers via AWS Fargate but I am running into "No Space left on device". Is there a way I can specify the volume size in task_definitions:

```<code>task_size:
    mem_limit: 2GB
    cpu_limit: 256
</code>```

答:
As of Fargate platform 1.4, released on 04/2020, ephemeral storage is now 20 GB, instead of 10 GB.
Additionally, you can now mount persistent EFS storage volumes in Fargate tasks.

For example:

```<code>{
    "containerDefinitions": [
        {
            "name": "container-using-efs",
            "image": "amazonlinux:2",
            "entryPoint": [
                "sh",
                "-c"
            ],
            "command": [
                "ls -la /mount/efs"
            ],
            "mountPoints": [
                {
                    "sourceVolume": "myEfsVolume",
                    "containerPath": "/mount/efs",
                    "readOnly": true
                }
            ]
        }
    ],
    "volumes": [
        {
            "name": "myEfsVolume",
            "efsVolumeConfiguration": {
                "fileSystemId": "fs-1234",
                "rootDirectory": "/path/to/my/data",
                "transitEncryption": "ENABLED",
                "transitEncryptionPort": integer,
                "authorizationConfig": {
                    "accessPointId": "fsap-1234",
                    "iam": "ENABLED"
                }
            }
        }
    ]
}
</code>```

Taken from:
efs-volumes in Fargate

Body:
I am deploying containers via AWS Fargate but I am running into "No Space left on device". Is there a way I can specify the volume size in task_definitions:

task_size:
    mem_limit: 2GB
    cpu_limit: 256

Body:
As of Fargate platform 1.4, released on 04/2020, ephemeral storage is now 20 GB, instead of 10 GB.
Additionally, you can now mount persistent EFS storage volumes in Fargate tasks.

For example:

{
    "containerDefinitions": [
        {
            "name": "container-using-efs",
            "image": "amazonlinux:2",
            "entryPoint": [
                "sh",
                "-c"
            ],
            "command": [
                "ls -la /mount/efs"
            ],
            "mountPoints": [
                {
                    "sourceVolume": "myEfsVolume",
                    "containerPath": "/mount/efs",
                    "readOnly": true
                }
            ]
        }
    ],
    "volumes": [
        {
            "name": "myEfsVolume",
            "efsVolumeConfiguration": {
                "fileSystemId": "fs-1234",
                "rootDirectory": "/path/to/my/data",
                "transitEncryption": "ENABLED",
                "transitEncryptionPort": integer,
                "authorizationConfig": {
                    "accessPointId": "fsap-1234",
                    "iam": "ENABLED"
                }
            }
        }
    ]
}

Taken from:
efs-volumes in Fargate


问:
Getting heroku-app url for images instead of s3.amazonaws in Active storage Rails API
I am having difficulty in understanding the image url of active storage in rails.
I am using amazon s3 bucket for uploading images in production with proper configuration in storage.yml file.

When I run url_for(User.user_image), it generates this link:

http://my-heroku-app/rails/active_storage/blobs/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBBdVFCIiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--1207b8339755bdc5391cb96548181a27dd9565fc/testing_image.jpg

and when I run User.user_image.service_url, the generated link is

https://my-app.s3.amazonaws.com/ySMyXZUWDnQGexvvNwKjZKpb......

Are my images being stored at 2 places? one is Heroku-PostgreSQL and second is aws-s3 or is it just aws-s3 where my images are being stored and active storage is somehow binding it the s3 link.

Actually, I want http://s3.amazonaws.com in url_for to return it in the API response.

Application Behavior: I have Rails API application in which images/videos first comes to the rails app from the front-end and from there they are pushed to the s3 bucket.

答:
The way you would want to generate the url is actually

```<code>rails_blob_url(User.find({id of user}).user_image)
</code>```

As far as how this works, activestorage just holds a pointer to where the file is located and will redirect to the S3 bucket as necessary. It's actually impossible on Heroku to store files locally the way their service is constructed, some sort of external storage container is required.

Rails documentation on the linking portion: https://edgeguides.rubyonrails.org/active_storage_overview.html#linking-to-files

Body:
The way you would want to generate the url is actually

rails_blob_url(User.find({id of user}).user_image)

As far as how this works, activestorage just holds a pointer to where the file is located and will redirect to the S3 bucket as necessary. It's actually impossible on Heroku to store files locally the way their service is constructed, some sort of external storage container is required.

Rails documentation on the linking portion: https://edgeguides.rubyonrails.org/active_storage_overview.html#linking-to-files


问:
Python logger setLevel ignoring the given level
I am trying to write a logger in Python, but the .setLevel method seems to not care which logging level I pass to it. Here's a minimally reproducible example:

import logging

logger = logging.getLogger("test")
logger.setLevel(logging.DEBUG)

logger.debug("debug")
logger.info("info")
logger.warning("warning")
logger.error("error")
logger.critical("critical")
```

<p>Output:</p>

<pre class="lang-sh prettyprint-override"><code>warning
error
critical
</code>```

As shown, I've set the level of my logger object to DEBUG, and yet only messages with levels WARNING and above are emitted.

From the documentation of setLevel:

Sets the threshold for this logger to level. Logging messages which are less severe than level will be ignored; logging messages which have severity level or higher will be emitted by whichever handler or handlers service this logger, unless a handler’s level has been set to a higher severity level than level.

In my code I've called setLevel to set the level of this specific logger object so it should have respected that level. Whats the explanation for this behaviour?

I've looked at the following stackoverflow questions and neither solutions apply to my case.

Python logger not respecting setLevel?

python logging: logger setLevel() is not enforced?

I'm using CPython 3.8.2

答:
Ah you hit the nail on the head without realizing:

unless a handler’s level has been set to a higher severity level than level.

The root logger is of level logging.WARNING and its default handler is what you're using with logger unless you specify otherwise by explicitly giving logger a handler.

Running logging.basicConfig() will create an explicit handler for the root logger, which doesn't have the same limitation as the root handler.

import logging
logger = logging.getLogger('test')
logger.setLevel(logging.DEBUG)

logger.debug('invisible')
logger.warning('visible')

logging.basicConfig()

logger.debug('visible')
logger.warning('visible')
```

Body:
I am trying to write a logger in Python, but the .setLevel method seems to not care which logging level I pass to it. Here's a minimally reproducible example:

import logging

logger = logging.getLogger("test")
logger.setLevel(logging.DEBUG)

logger.debug("debug")
logger.info("info")
logger.warning("warning")
logger.error("error")
logger.critical("critical")

Output:

warning
error
critical

As shown, I've set the level of my logger object to DEBUG, and yet only messages with levels WARNING and above are emitted.

From the documentation of setLevel:

Sets the threshold for this logger to level. Logging messages which are less severe than level will be ignored; logging messages which have severity level or higher will be emitted by whichever handler or handlers service this logger, unless a handler’s level has been set to a higher severity level than level.

In my code I've called setLevel to set the level of this specific logger object so it should have respected that level. Whats the explanation for this behaviour?

I've looked at the following stackoverflow questions and neither solutions apply to my case.

Python logger not respecting setLevel?

python logging: logger setLevel() is not enforced?

I'm using CPython 3.8.2