问:
Is it possible to have hostname based routing for MySQL in kubernetes?
I have a scenario where I have multiple mysql servers running in different namespaces in single kubernetes cluster. All mysql servers belong to different departments.

My requirement is I should be able to connect to different mysql servers using hostname, i.e.,

mysqlServerA running in ServerA namespace should be reachable from outside the cluster using:

```<code>mysql -h mysqlServerA.mydomain.com -A
</code>```

mysqlServerB running in ServerB namespace should be reachable from outside the cluster using:

```<code>mysql -h mysqlServerB.mydomain.com -A
</code>```

and so on.

I have tried TCP based routing using config maps of Nginx Ingress controller, where I am routing traffic from clients to different mysql servers by assigning different port numbers:

for mysqlServerA:

```<code>mysql -h mysqlServer.mydomain.com -A -P 3301
</code>```

for mysqlServerB:

```<code>mysql -h mysqlServer.mydomain.com -A -P 3302
</code>```

this works perfectly. But I want to know if hostname based routing is possible or not, because I don't want separate load balancer for each mysql service.

Thanks

答:
General info

I  routing traffic by  different port numbers

You are right, the reason for that is that connection to Mysql is done via TCP. That is why it is definitely not possible to have two simultaneous connections to two servers on the same IP:port.

Unlike HTTP, the TCP don't have headers that allows distinguishing the host the traffic shall be routed to. However, still there are at least two ways to achieve the functionality you'd like to achieve :) I'll describe that later.

I want to know if hostname based routing is possible or not
  I don't want separate load balancer for each mysql service.

K8s allows a few methods for service to be reachable outside the cluster (namely  hostNetwork, hostPort, NodePort , LoadBalancer, Ingress   )

The LoadBalancer is the simplest way to serve traffic on LoadBalancerIP:port ; however, due to TCP nature of connection you'll have to use one LoadBalancer per one mysql instance.

```<code>kind: Service
apiVersion: v1
metadata:
  name: mysql
spec:
  type: LoadBalancer
  ports:
    - port: 3306
  selector:
    name: my-mysql
</code>```

The NodePort looks good, but it allows you connecting only when you know port (which can be tedious work for clients)

Proposed solutions

External IPs

If there are external IPs that route to one or more cluster nodes, Kubernetes Services can be exposed on those  externalIPs. Traffic that ingresses into the cluster with the external IP (as destination IP), on the Service port, will be routed to one of the Service endpoints.  externalIPs  are not managed by Kubernetes and are the responsibility of the cluster administrator.

In the Service spec,  externalIPs  can be specified along with any of the  ServiceTypes. In the example below, mysql-1 can be accessed by clients on 1.2.3.4:3306 (externalIP:port) and mysql-2 can be accessed by clients on 4.3.2.1:3306

```<code>$ cat stereo-mysql-3306.yaml
apiVersion: v1
kind: Service
metadata:
  name: mysql-1234-inst-1
spec:
  selector:
    app: mysql-prod
  ports:
    - name: mysql
      protocol: TCP
      port: 3306
      targetPort: 3306
  externalIPs:
    - 1.2.3.4
---
apiVersion: v1
kind: Service
metadata:
  name: mysql-4321-inst-1
spec:
  selector:
    app: mysql-repl
  ports:
    - name: mysql
      protocol: TCP
      port: 3306
      targetPort: 3306
  externalIPs:
    - 4.3.2.1
</code>```

Note: you need to have 1.2.3.4 and 4.3.2.1 assigned to your Nodes (and resolve mysqlServerA / mysqlserverB at mydomain.comto these IPs as well). I've tested that solution on my GKE cluster and it works :).

With that config all the requests for mysqlServerA.mydomain.com:3306 that resolves to 1.2.3.4 are going to be routed to the Endpoints for service mysql-1234-inst-1 with the app: mysql-prod selector, and mysqlServerA.mydomain.com:3306 will be served by app: mysql-repl.

Of course it is possible to split that config for 2 namespaces (one namespace - one mysql - one service per one namespace).

ClusterIP+OpenVPN

Taking into consideration that your mysql pods have ClusterIPs, it is possible to spawn additional VPN pod in cluster and connect to mysqls through it.

As a result, you can establish VPN connection and have access to all the cluster resources. That is very limited solution which requires establishing the VPN connection for anyone who needs access to mysql.

Good practice is to add a bastion server on top of that solution. That server will be responsible for providing access to cluster services via VPN.

Hope that helps.

Body:
I have a scenario where I have multiple mysql servers running in different namespaces in single kubernetes cluster. All mysql servers belong to different departments.

My requirement is I should be able to connect to different mysql servers using hostname, i.e.,

mysqlServerA running in ServerA namespace should be reachable from outside the cluster using:

mysql -h mysqlServerA.mydomain.com -A

mysqlServerB running in ServerB namespace should be reachable from outside the cluster using:

mysql -h mysqlServerB.mydomain.com -A

and so on.

I have tried TCP based routing using config maps of Nginx Ingress controller, where I am routing traffic from clients to different mysql servers by assigning different port numbers:

for mysqlServerA:

mysql -h mysqlServer.mydomain.com -A -P 3301

for mysqlServerB:

mysql -h mysqlServer.mydomain.com -A -P 3302

this works perfectly. But I want to know if hostname based routing is possible or not, because I don't want separate load balancer for each mysql service.

Thanks

Body:
General info

I  routing traffic by  different port numbers

You are right, the reason for that is that connection to Mysql is done via TCP. That is why it is definitely not possible to have two simultaneous connections to two servers on the same IP:port.

Unlike HTTP, the TCP don't have headers that allows distinguishing the host the traffic shall be routed to. However, still there are at least two ways to achieve the functionality you'd like to achieve :) I'll describe that later.

I want to know if hostname based routing is possible or not
  I don't want separate load balancer for each mysql service.

K8s allows a few methods for service to be reachable outside the cluster (namely  hostNetwork, hostPort, NodePort , LoadBalancer, Ingress   )

The LoadBalancer is the simplest way to serve traffic on LoadBalancerIP:port ; however, due to TCP nature of connection you'll have to use one LoadBalancer per one mysql instance.

kind: Service
apiVersion: v1
metadata:
  name: mysql
spec:
  type: LoadBalancer
  ports:
    - port: 3306
  selector:
    name: my-mysql

The NodePort looks good, but it allows you connecting only when you know port (which can be tedious work for clients)

Proposed solutions

External IPs

If there are external IPs that route to one or more cluster nodes, Kubernetes Services can be exposed on those  externalIPs. Traffic that ingresses into the cluster with the external IP (as destination IP), on the Service port, will be routed to one of the Service endpoints.  externalIPs  are not managed by Kubernetes and are the responsibility of the cluster administrator.

In the Service spec,  externalIPs  can be specified along with any of the  ServiceTypes. In the example below, mysql-1 can be accessed by clients on 1.2.3.4:3306 (externalIP:port) and mysql-2 can be accessed by clients on 4.3.2.1:3306

$ cat stereo-mysql-3306.yaml
apiVersion: v1
kind: Service
metadata:
  name: mysql-1234-inst-1
spec:
  selector:
    app: mysql-prod
  ports:
    - name: mysql
      protocol: TCP
      port: 3306
      targetPort: 3306
  externalIPs:
    - 1.2.3.4
---
apiVersion: v1
kind: Service
metadata:
  name: mysql-4321-inst-1
spec:
  selector:
    app: mysql-repl
  ports:
    - name: mysql
      protocol: TCP
      port: 3306
      targetPort: 3306
  externalIPs:
    - 4.3.2.1

Note: you need to have 1.2.3.4 and 4.3.2.1 assigned to your Nodes (and resolve mysqlServerA / mysqlserverB at mydomain.comto these IPs as well). I've tested that solution on my GKE cluster and it works :).

With that config all the requests for mysqlServerA.mydomain.com:3306 that resolves to 1.2.3.4 are going to be routed to the Endpoints for service mysql-1234-inst-1 with the app: mysql-prod selector, and mysqlServerA.mydomain.com:3306 will be served by app: mysql-repl.

Of course it is possible to split that config for 2 namespaces (one namespace - one mysql - one service per one namespace).

ClusterIP+OpenVPN

Taking into consideration that your mysql pods have ClusterIPs, it is possible to spawn additional VPN pod in cluster and connect to mysqls through it.

As a result, you can establish VPN connection and have access to all the cluster resources. That is very limited solution which requires establishing the VPN connection for anyone who needs access to mysql.

Good practice is to add a bastion server on top of that solution. That server will be responsible for providing access to cluster services via VPN.

Hope that helps.


来源: stackexchange

问:
sqlalchemy.exc.NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:bigquery
Trying to create a bigquery connector using sqlalchemy

```<code>from sqlalchemy import create_engine
engine = create_engine('bigquery://<project_id>/<project_name>',
                   credentials_path=GCP_KEY)
conn = engine.connect()
</code>```

Error:

```<code>sqlalchemy.exc.NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:bigquery
</code>```

答:
Your error is generally related to the lack of some required module to use SQLAlchemy.

Therefore, after going though the documentation, I found out that you should install the requirements in you environment using:

```<code>pip3 install pybigquery
</code>```

In addition, within your script you should import the following modules:

SQLAchemy

from sqlalchemy import *
from sqlalchemy.engine import create_engine
from sqlalchemy.schema import *

API Client

from pybigquery.api import ApiClient

Afterwards, you should have all the necessary packages to execute your code.

If you have any more question about using the SQLAlchemy and API client for BigQuery, you can consult the provided documentation above or I would also be glad to help.

ContentLicense: CC BY-SA 4.0

Body:
Trying to create a bigquery connector using sqlalchemy

from sqlalchemy import create_engine
engine = create_engine('bigquery://<project_id>/<project_name>',
                   credentials_path=GCP_KEY)
conn = engine.connect()

Error:

sqlalchemy.exc.NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:bigquery

Body:
Your error is generally related to the lack of some required module to use SQLAlchemy.

Therefore, after going though the documentation, I found out that you should install the requirements in you environment using:

pip3 install pybigquery

In addition, within your script you should import the following modules:

SQLAchemy

from sqlalchemy import *
from sqlalchemy.engine import create_engine
from sqlalchemy.schema import *

API Client

from pybigquery.api import ApiClient

Afterwards, you should have all the necessary packages to execute your code.

If you have any more question about using the SQLAlchemy and API client for BigQuery, you can consult the provided documentation above or I would also be glad to help.


问:
Looking for suggestions for planning out a potentially very large database (mysql)
I currently have a database which is already >15GB in size, and will grow to much larger. I'm not aiming to add in an extra table purely for "api" data that gets pulled in (which is related somewhat to the other tables data but only by a single ID reference).

I have some "api" data from external sources that gets imported and I've calculated it could grow to around 300GB in size. This data can be re-fetched and isn't as critical to be backed up, so in order to keep backups more manageable I thought why not put that api data into a different database?

However, after reading (here) it sounds like this is bad practice.

I just wanted to get some opinions on this. The API data is just JSON "mediumblob"s that get stored and could even potentially be stored as flat files instead, but I think maybe a secondary database for "more disposable" data is appropriate?

Thoughts/ideas/recommendations?

Thank you!

答: I would not be worried for a 300 GB database. As of todays standard that is not a large database, and with the correct indexes it will not be a problem. I would go a head with one database. </p>


问:
share cookies between subdomains using express/angularjs
I've been trying to accomplish this task for quite some time but haven't got any breakthrough yet. I would be really thankful if anyone can help me out in this.

Current Situation:

I've two applications that I'm running in two sub-domains as

st.localhost:8080 and acm.localhost:8080

When a user tries to access either of the URLs, I search for a cookie named 'auth' using Angular $cookies service. If the cookie is defined or present, the user is redirected to original application. However, if the cookie is undefined, user is redirected to a login page(the login page resides in both the applications).

From the login page, after successful credentials check, I set the 'auth' cookie again with a random value. This cookie is supposed to be shared between the two sub-domains.

Express:

```<code>var express = require('express');
var httpProxy = require('http-proxy');
var vhost = require('vhost');

var app = express();
var proxy = httpProxy.createProxyServer();

app.get('/login', function(req, res) {
    var randomNumber=Math.random().toString();
    randomNumber=randomNumber.substring(2,randomNumber.length);
    var expireDate = new Date();
    expireDate.setDate(expireDate.getDate() + 1);
    res.cookie('auth', randomNumber, { maxAge: 90000000, domain: 'localhost', httpOnly: false });
    console.log('cookie created successfully');
    res.send('Login successful');
});

app.use('/api', function(req, res) {
    req.headers[ 'Authorization' ] = 'Basic dXNlcjpwYXNzd29yZA==';
    console.log("Request cookies: " + req.cookie);
    proxy.web(req, res, { target: 'restApiTarget' });
});

// ST application
app.use(vhost('st.localhost', express.static('./st')));

// ACM application
app.use(vhost('acm.localhost', express.static('./acm')));

app.listen(8080, function () {
    console.log('Fweb server running on port 8080!');
});
</code>```

Angular

Below login function is shared by both ST and ACM applications

```<code>    $scope.login = function(formValid){
        $scope.incorrectCredentials = false;
        if(formValid){
            $http.get('/login',
                {
                    params: {
                        username: $scope.username,
                        password: $scope.password
                    },
                    headers : {
                        'Accept' : 'application/json'
                    }
                }
            ).then(function(response){
                $scope.incorrectCredentials = false;
                var obj = $cookies.getObject('auth');
                console.log("auth is: " + obj);
                $state.go($stateParams.origin);
            }, function(response){
                $scope.incorrectCredentials = true;
            });
        }
    }
</code>```

Express is able to successfully create the cookie 'auth' as I can see the Set-Cookie header in the /login service response. However, the browser is not attaching this cookie to the subsequent API requests that I'm making from my application(say st.localhost). I'm not able to read this cookie through Angular as well.

```<code>     var obj = $cookies.getObject('auth');
     console.log("auth is: " + obj);
</code>```

results in obj being undefined.

I've a feeling that there is something wrong in the way I'm setting the domain of the cookie as 'localhost' from one of the sub-domains.

Any suggestions on what I may be doing wrong?

Thanks in advance.

答: Cookies is domain specific , if you want access across domain, you need to use some cross store like cross-storage etc.</p>

ContentLicense: CC BY-SA 3.0

Body:
I've been trying to accomplish this task for quite some time but haven't got any breakthrough yet. I would be really thankful if anyone can help me out in this.

Current Situation:

I've two applications that I'm running in two sub-domains as

st.localhost:8080 and acm.localhost:8080

When a user tries to access either of the URLs, I search for a cookie named 'auth' using Angular $cookies service. If the cookie is defined or present, the user is redirected to original application. However, if the cookie is undefined, user is redirected to a login page(the login page resides in both the applications).

From the login page, after successful credentials check, I set the 'auth' cookie again with a random value. This cookie is supposed to be shared between the two sub-domains.

Express:

var express = require('express');
var httpProxy = require('http-proxy');
var vhost = require('vhost');

var app = express();
var proxy = httpProxy.createProxyServer();

app.get('/login', function(req, res) {
    var randomNumber=Math.random().toString();
    randomNumber=randomNumber.substring(2,randomNumber.length);
    var expireDate = new Date();
    expireDate.setDate(expireDate.getDate() + 1);
    res.cookie('auth', randomNumber, { maxAge: 90000000, domain: 'localhost', httpOnly: false });
    console.log('cookie created successfully');
    res.send('Login successful');
});

app.use('/api', function(req, res) {
    req.headers[ 'Authorization' ] = 'Basic dXNlcjpwYXNzd29yZA==';
    console.log("Request cookies: " + req.cookie);
    proxy.web(req, res, { target: 'restApiTarget' });
});

// ST application
app.use(vhost('st.localhost', express.static('./st')));

// ACM application
app.use(vhost('acm.localhost', express.static('./acm')));

app.listen(8080, function () {
    console.log('Fweb server running on port 8080!');
});

Angular

Below login function is shared by both ST and ACM applications

    $scope.login = function(formValid){
        $scope.incorrectCredentials = false;
        if(formValid){
            $http.get('/login',
                {
                    params: {
                        username: $scope.username,
                        password: $scope.password
                    },
                    headers : {
                        'Accept' : 'application/json'
                    }
                }
            ).then(function(response){
                $scope.incorrectCredentials = false;
                var obj = $cookies.getObject('auth');
                console.log("auth is: " + obj);
                $state.go($stateParams.origin);
            }, function(response){
                $scope.incorrectCredentials = true;
            });
        }
    }

Express is able to successfully create the cookie 'auth' as I can see the Set-Cookie header in the /login service response. However, the browser is not attaching this cookie to the subsequent API requests that I'm making from my application(say st.localhost). I'm not able to read this cookie through Angular as well.

     var obj = $cookies.getObject('auth');
     console.log("auth is: " + obj);

results in obj being undefined.

I've a feeling that there is something wrong in the way I'm setting the domain of the cookie as 'localhost' from one of the sub-domains.

Any suggestions on what I may be doing wrong?

Thanks in advance.


问:
How to solve FATAL EXCEPTION java.lang.RuntimeException: An error occured while executing doInBackground()
i am developing chat related similar application i am using backgrouund synchronous class some times force close is appear i am using .net webservices back ground i am recieve the messages and images background download process updating to ui

error is:

```<code>05-17 05:24:17.925: ERROR/AndroidRuntime(1618): FATAL EXCEPTION: AsyncTask #1
05-17 05:24:17.925: ERROR/AndroidRuntime(1618): java.lang.RuntimeException: An error occured while executing doInBackground()
05-17 05:24:17.925: ERROR/AndroidRuntime(1618):     at android.os.AsyncTask$3.done(AsyncTask.java:200)
05-17 05:24:17.925: ERROR/AndroidRuntime(1618):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
05-17 05:24:17.925: ERROR/AndroidRuntime(1618):     at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
05-17 05:24:17.925: ERROR/AndroidRuntime(1618):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
05-17 05:24:17.925: ERROR/AndroidRuntime(1618):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
05-17 05:24:17.925: ERROR/AndroidRuntime(1618):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
05-17 05:24:17.925: ERROR/AndroidRuntime(1618):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
05-17 05:24:17.925: ERROR/AndroidRuntime(1618):     at java.lang.Thread.run(Thread.java:1096)
05-17 05:24:17.925: ERROR/AndroidRuntime(1618): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
05-17 05:24:17.925: ERROR/AndroidRuntime(1618):     at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:257)
05-17 05:24:17.925: ERROR/AndroidRuntime(1618):     at java.util.ArrayList.get(ArrayList.java:311)
05-17 05:24:17.925: ERROR/AndroidRuntime(1618):     at com.fitzgeraldsoftware.shout.presentationLayer.Shout$LatestMessage.doInBackground(Shout.java:1923)
05-17 05:24:17.925: ERROR/AndroidRuntime(1618):     at android.os.AsyncTask$2.call(AsyncTask.java:185)
05-17 05:24:17.925: ERROR/AndroidRuntime(1618):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
05-17 05:24:17.925: ERROR/AndroidRuntime(1618):     ... 4 more
05-17 05:24:17.956: WARN/ActivityManager(1105):   Force finishing activity com.fitzgeraldsoftware.shout.presentationLayer/.Shout
05-17 05:24:18.097: WARN/IInputConnectionWrapper(1618): showStatusIcon on inactive InputConnection
</code>```

答:
You have ArrayIndexOutOfBoundsException thrown. Check the code executed on 1923 in Shout.java for array access. The exception is thrown if you try to read element by index which is more than array size(1). For example it is thrown if:

```<code>String [] strings = new String[0];
strings[0];// exception thrown!
</code>```

Body:
i am developing chat related similar application i am using backgrouund synchronous class some times force close is appear i am using .net webservices back ground i am recieve the messages and images background download process updating to ui

error is:

05-17 05:24:17.925: ERROR/AndroidRuntime(1618): FATAL EXCEPTION: AsyncTask #1
05-17 05:24:17.925: ERROR/AndroidRuntime(1618): java.lang.RuntimeException: An error occured while executing doInBackground()
05-17 05:24:17.925: ERROR/AndroidRuntime(1618):     at android.os.AsyncTask$3.done(AsyncTask.java:200)
05-17 05:24:17.925: ERROR/AndroidRuntime(1618):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
05-17 05:24:17.925: ERROR/AndroidRuntime(1618):     at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
05-17 05:24:17.925: ERROR/AndroidRuntime(1618):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
05-17 05:24:17.925: ERROR/AndroidRuntime(1618):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
05-17 05:24:17.925: ERROR/AndroidRuntime(1618):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
05-17 05:24:17.925: ERROR/AndroidRuntime(1618):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
05-17 05:24:17.925: ERROR/AndroidRuntime(1618):     at java.lang.Thread.run(Thread.java:1096)
05-17 05:24:17.925: ERROR/AndroidRuntime(1618): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
05-17 05:24:17.925: ERROR/AndroidRuntime(1618):     at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:257)
05-17 05:24:17.925: ERROR/AndroidRuntime(1618):     at java.util.ArrayList.get(ArrayList.java:311)
05-17 05:24:17.925: ERROR/AndroidRuntime(1618):     at com.fitzgeraldsoftware.shout.presentationLayer.Shout$LatestMessage.doInBackground(Shout.java:1923)
05-17 05:24:17.925: ERROR/AndroidRuntime(1618):     at android.os.AsyncTask$2.call(AsyncTask.java:185)
05-17 05:24:17.925: ERROR/AndroidRuntime(1618):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
05-17 05:24:17.925: ERROR/AndroidRuntime(1618):     ... 4 more
05-17 05:24:17.956: WARN/ActivityManager(1105):   Force finishing activity com.fitzgeraldsoftware.shout.presentationLayer/.Shout
05-17 05:24:18.097: WARN/IInputConnectionWrapper(1618): showStatusIcon on inactive InputConnection

Body:
You have ArrayIndexOutOfBoundsException thrown. Check the code executed on 1923 in Shout.java for array access. The exception is thrown if you try to read element by index which is more than array size(1). For example it is thrown if:

String [] strings = new String[0];
strings[0];// exception thrown!


问:
In the vis.js library, how do I get the max value in the "id" field?
I'm discovering vis.js, especially the network module.

I need to get the max value of the "id" field of my nodes dataset:

```<code>var nodes = new vis.DataSet([ {id: 1, label: "Node 1"}, {id: 2, label: "Node 2"}, {id: 3, label: "Node 3"}]);
</code>```

The best I've been able to do so far is using a forEach loop:

```<code>var max=0;
nodes.forEach(function(el){j=parseInt(el.id);if(j!=NaN && j>max){max=j;}});
console.log("max: ", max);
</code>```

It seems to me it can't be THE way to do this.
I saw a max(field) method documented in the doc for vis' DataSet (https://visjs.github.io/vis-data/data/dataset.html):

max(field) [Object|null]  Find the item with maximum value of specified field. Returns null if no item is found.

But as stupid as i may sound, I just can't get it to work.
I tried :

```<code>console.log("max: ", nodes.max('id'));
console.log("max: ", nodes.max(node => node.id));
console.log("max: ", nodes.max(node => node['id']));
</code>```

How can I simply get the max value of the field 'id' of all entries of a DataSet?

[Edit] The ID's in the example here above are numeric ({id: 1, ...}).

In my case, they were strings ({id: '1', ...}), and exactly that seemed to be the problem.

答:
try this line:

```<code>nodes.max('id').id
</code>```

nodes.max('id') will return the node with the max id value.

Body:
I'm discovering vis.js, especially the network module.

I need to get the max value of the "id" field of my nodes dataset:

var nodes = new vis.DataSet([ {id: 1, label: "Node 1"}, {id: 2, label: "Node 2"}, {id: 3, label: "Node 3"}]);

The best I've been able to do so far is using a forEach loop:

var max=0;
nodes.forEach(function(el){j=parseInt(el.id);if(j!=NaN && j>max){max=j;}});
console.log("max: ", max);

It seems to me it can't be THE way to do this.
I saw a max(field) method documented in the doc for vis' DataSet (https://visjs.github.io/vis-data/data/dataset.html):

max(field) [Object|null]  Find the item with maximum value of specified field. Returns null if no item is found.

But as stupid as i may sound, I just can't get it to work.
I tried :

console.log("max: ", nodes.max('id'));
console.log("max: ", nodes.max(node => node.id));
console.log("max: ", nodes.max(node => node['id']));

How can I simply get the max value of the field 'id' of all entries of a DataSet?

[Edit] The ID's in the example here above are numeric ({id: 1, ...}).

In my case, they were strings ({id: '1', ...}), and exactly that seemed to be the problem.

Body:
try this line:

nodes.max('id').id

nodes.max('id') will return the node with the max id value.


问:
Optimizing SQL INSERT query
I have recently been looking into possible ways how to optimize my INSERT queries. I am doing usually an INSERT with a batch size of 100.

My current example query:

```<code>IF EXISTS (SELECT * FROM [db].[Prices] WHERE Source = 'Cars' AND TradeDate = convert(datetime,'18-02-20',5) AND Product = 'Audi' AND Price=NULLIF('5.00000',''))

BEGIN DELETE FROM [db].[Prices] WHERE Source = 'Cars' AND TradeDate = convert(datetime,'18-02-20',5) AND Product = 'Audi' AND Price=NULLIF('5.00000','') END;

INSERT INTO [db].[Prices] VALUES( 'Cars', convert(datetime,'18-02-20',5), 'APR25', NULL, 'Audi', NULLIF('5.00000',''), convert(datetime,'15-04-25',5), '1', GETUTCDATE(), convert(date,NULL,105), convert(date,NULL,105));
</code>```

The possible optimizations that I have found from research are as following:

Replace * with fields

Replace WHERE with INNER JOIN

As this is rather new to me, any suggestions are welcome. It seems like the highest potential is in changing the core structure (IF EXISTS - DELETE - INSERT INTO).

Thank you for any help.

答:
Consider using MERGE statement. Instead of DELETE followed by INSERT, you can do UPDATE / INSERT:
https://learn.microsoft.com/en-us/sql/t-sql/statements/merge-transact-sql</p>

Title: Optimizing SQL INSERT query

Body:
I have recently been looking into possible ways how to optimize my INSERT queries. I am doing usually an INSERT with a batch size of 100.

My current example query:

IF EXISTS (SELECT * FROM [db].[Prices] WHERE Source = 'Cars' AND TradeDate = convert(datetime,'18-02-20',5) AND Product = 'Audi' AND Price=NULLIF('5.00000',''))

BEGIN DELETE FROM [db].[Prices] WHERE Source = 'Cars' AND TradeDate = convert(datetime,'18-02-20',5) AND Product = 'Audi' AND Price=NULLIF('5.00000','') END;

INSERT INTO [db].[Prices] VALUES( 'Cars', convert(datetime,'18-02-20',5), 'APR25', NULL, 'Audi', NULLIF('5.00000',''), convert(datetime,'15-04-25',5), '1', GETUTCDATE(), convert(date,NULL,105), convert(date,NULL,105));

The possible optimizations that I have found from research are as following:

Replace * with fields

Replace WHERE with INNER JOIN

As this is rather new to me, any suggestions are welcome. It seems like the highest potential is in changing the core structure (IF EXISTS - DELETE - INSERT INTO).

Thank you for any help.


问:
What is the way to make kubernetes nodes have `providerID` spec after creation (manually)?
I'm expecting that kubectl get nodes <node> -o yaml to show the spec.providerID (see reference below) once the kubelet has been provided the additional flag --provider-id=provider://nodeID.  I've used /etc/default/kubelet file to add more flags to the command line when kubelet is start/restarted.  (On a k8s 1.16 cluster)  I see the additional flags via a systemctl status kubelet --no-pager call, so the file is respected.

However, I've not seen the value get returned by kubectl get node <node> -o yaml call.  I was thinking it had to be that the node was already registered, but I think kubectl re-registers when it starts up.  I've seen the log line via journalctl -u kubelet suggest that it has gone through registration.

How can I add a provider ID to a node manually?

https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.17/#nodespec-v1-core

答:
How a kubelet is configured on the node itself is separate (AFAIK) from its definition in the master control plane, which is responsible for updating state in the central etcd store; so it's possible for these to fall out of sync. i.e., you need to communicate to the control place to update its records.

In addition to Subramanian's suggestion, kubectl patch node would also work, and has the added benefit of being easily reproducible/scriptable compared to manually editing the YAML manifest; it also leaves a "paper trail" in your shell history should you need to refer back. Take your pick :) For example,

$ kubectl patch node my-node -p '{"spec":{"providerID":"foo"}}'
node/my-node patched
$ kubectl describe node my-node | grep ProviderID
ProviderID:                   foo
```

Hope this helps!

Body:
How a kubelet is configured on the node itself is separate (AFAIK) from its definition in the master control plane, which is responsible for updating state in the central etcd store; so it's possible for these to fall out of sync. i.e., you need to communicate to the control place to update its records.

In addition to Subramanian's suggestion, kubectl patch node would also work, and has the added benefit of being easily reproducible/scriptable compared to manually editing the YAML manifest; it also leaves a "paper trail" in your shell history should you need to refer back. Take your pick :) For example,

$ kubectl patch node my-node -p '{"spec":{"providerID":"foo"}}'
node/my-node patched
$ kubectl describe node my-node | grep ProviderID
ProviderID:                   foo

Hope this helps!


问:
How to get the corresponding row based on the current date for tax calculation in mysql
I have a table called tax calculation as follows

```
effective_date     c_gst     s_gst
01-03-2019         5%        5%
01-08-2019         8%        8%
01-05-2020         9%        9%
```

how to get the row based on the current date ie. 19-02-2020, this is for tax calculation the effective date is used to search the tax %. the row has to >= to the effective date.

The output should be:

```<code>01-08-2019    8%    8%
</code>```

答:
If you want the row with the latest date that is less than or equal to '2020-02-19':

```<code>select *
from tablename
where effective_date = (
  select max(effective_date)
  from tablename
  where effective_date <= '2020-02-19'
)
</code>```

Body:
I have a table called tax calculation as follows

effective_date     c_gst     s_gst
01-03-2019         5%        5%
01-08-2019         8%        8%
01-05-2020         9%        9%

how to get the row based on the current date ie. 19-02-2020, this is for tax calculation the effective date is used to search the tax %. the row has to >= to the effective date.

The output should be:

01-08-2019    8%    8%

Body:
If you want the row with the latest date that is less than or equal to '2020-02-19':

select *
from tablename
where effective_date = (
  select max(effective_date)
  from tablename
  where effective_date <= '2020-02-19'
)


问:
How to know where is Libreoffice installed in a Docker image?
I am trying to convert a docx document to PDF by using libreoffice as follows:

```<code>from subprocess import  Popen
LIBRE_OFFICE = r"C:\Program Files\LibreOffice\program\soffice.exe"

def convert_to_pdf(input_docx, out_folder):
    p = Popen([LIBRE_OFFICE, '--headless', '--convert-to', 'pdf', '--outdir',
               out_folder, input_docx])
    print([LIBRE_OFFICE, '--convert-to', 'pdf', input_docx])
    p.communicate()

sample_doc = 'file.docx'
out_folder = 'some_folder'
convert_to_pdf(sample_doc, out_folder)
</code>```

However, I am working on a Linux Docker image. So I don't need what route should I specify in the LIBRE_OFFICE variable. Does anybody knows it?

The command I am using in my Dockerfile to install libreoffice is RUN apt-get update && apt-get -y install libreoffice

答:
On linux the which command will tell you where an executible is installed. For example on my system

$ which libreoffice
/usr/bin/libreoffice
```

You can generally do this for every executable, and also to check IF an executable is installed. This approach will work even if the output of the which command is a symbolic link.

Body:
I am trying to convert a docx document to PDF by using libreoffice as follows:

from subprocess import  Popen
LIBRE_OFFICE = r"C:\Program Files\LibreOffice\program\soffice.exe"

def convert_to_pdf(input_docx, out_folder):
    p = Popen([LIBRE_OFFICE, '--headless', '--convert-to', 'pdf', '--outdir',
               out_folder, input_docx])
    print([LIBRE_OFFICE, '--convert-to', 'pdf', input_docx])
    p.communicate()

sample_doc = 'file.docx'
out_folder = 'some_folder'
convert_to_pdf(sample_doc, out_folder)

However, I am working on a Linux Docker image. So I don't need what route should I specify in the LIBRE_OFFICE variable. Does anybody knows it?

The command I am using in my Dockerfile to install libreoffice is RUN apt-get update && apt-get -y install libreoffice

Body:
On linux the which command will tell you where an executible is installed. For example on my system

$ which libreoffice
/usr/bin/libreoffice

You can generally do this for every executable, and also to check IF an executable is installed. This approach will work even if the output of the which command is a symbolic link.


问:
Azure Pipelines Conditional and Persistent Variables
I'm trying to setup an Azure Pipeline that automatically updates version numbers based on which branch is being built. Given a master branch, a develop branch, and a version in the form {major.minor.patch.build} I want to achieve the following:

Whenever the pipeline is triggered by master:

patch is incremented by 1

build is reset to 0

Whenever the pipeline is triggered by develop:

build is incremented by 1

An example of what I expect the version numbers to look like after multiple runs assuming a starting version of 1.0.0.0:

Run 1 on develop: 1.0.0.1

Run 2 on develop: 1.0.0.2

Run 3 on master: 1.0.1.0

Run 4 on master: 1.0.2.0

Run 5 on develop: 1.0.2.1

Run 6 on develop: 1.0.2.2

Run 7 on master: 1.0.3.0

My first thought was to use a counter for the patch and build values but there doesn't seem to be a way of conditionally incrementing them or resetting the counter. My next thought was to use a couple script tasks that execute conditionally based on the branch, such as:

```<code>    #Update build
    - powershell: echo "##vso[task.setvariable variable=version.build;isOutput=true]$(version.build + 1)"
      condition: eq(variables['Build.SourceBranch'], 'refs/heads/develop')

    #Reset build number
    - powershell: echo "##vso[task.setvariable variable=version.build;isOutput=true]0"
      condition: eq(variables['Build.SourceBranch'], 'refs/heads/master')

    #Update patch
    - powershell: echo "##vso[task.setvariable variable=version.patch;isOutput=true]$(version.patch + 1)"
      condition: eq(variables['Build.SourceBranch'], 'refs/heads/master')
</code>```

However that approach isn't persistent across runs (not to mention $(version.patch + 1) doesn't work. I can't find any information on how to actually increment a variable in this way). My last idea was to have a version file in the repository and use that but I really don't want to have to go down that route.

Is there a way to achieve what I'm looking for using Pipelines or am I barking up the wrong tree trying to go about it this way?

Edit
I should have mentioned in the question that at this point I have a pipeline setup that builds my application but does nothing with versioning. What I'm looking for at this point is a way to dynamically update a few persistent variables/values (specifically patch and build).

答:
I have a workaround to achieve this with restful api.

For example you want to add above version tag to the build. You can first get the tag of the previous build with get tag api. Then you can update the version with the scripts and update it with updated tag. You can refer to below scripts in the powershell task.

```<code># first get previous build id

$url = "$(System.TeamFoundationCollectionUri)$(System.TeamProject)/_apis/build/builds?definitions={pipeline Id}&`$top=2&api-version=5.1"

$result = Invoke-RestMethod -Uri $url -Headers @{authorization = "Bearer $(System.AccessToken)"} -Method get

$builds = $result.value
$bid = $builds[1].id

# get the build tag with get build tag api

$urltag ="$(System.TeamFoundationCollectionUri)$(System.TeamProject)/_apis/build/builds/$bid/tags?api-version=5.1"

$tagResult = Invoke-RestMethod -Uri $urltag -Headers @{authorization = "Bearer $(System.AccessToken)"} -Method get

# get the tag and update it

if($tagResult.value)
{
   $tagarr = [regex]::split($result.value, '\.')
   $patch = $tagarr[2]
   $build = $tagarr[3]
   $tag=""
   if("$(Build.SourceBranch)" -eq "refs/heads/master")
   {
      $patch = [int]$patch + 1
      # update the variables version.patch and version.build with below scripts, so that it can be referenced in the following tasks.
      #echo "##vso[task.setvariable variable=version.patch;isOutput=true]$patch"
      #echo "##vso[task.setvariable variable=version.build;isOutput=true]0"

     $tag = "$(version.major).$(version.minor).$patch.0"
   }
   if("$(Build.SourceBranch)" -eq "refs/heads/dev")
   {
      $build= [int]$build+ 1
      #echo "##vso[task.setvariable variable=version.patch;isOutput=true]$patch"
      #echo "##vso[task.setvariable variable=version.build;isOutput=true]$build"
      $tag = "$(version.major).$(version.minor).$patch.$build"
   }

 #add $tag to current build.
  $urltagupdate = "$(System.TeamFoundationCollectionUri)$(System.TeamProject)/_apis/build/builds/$(Build.BuildId)/tags/$($tag)?api-version=5.1"

  Invoke-RestMethod -Uri $urltagupdate -Headers @{authorization = "Bearer $(System.AccessToken)"} -Method put

}else
{
  #if the build is run for the first time and the tag is not exist.
  #you can omit this part by manually creating a initial tag for the build.

  $tag = ""
  if("$(Build.SourceBranchName)" -eq "refs/heads/master")
  {
    $tag = "1.0.1.0"
  }
  if("$(Build.SourceBranchName)" -eq "refs/heads/dev")
  {
    $tag="1.0.0.1"
  }

 #add $tag to current build.

  $urltagupdate = "$(System.TeamFoundationCollectionUri)$(System.TeamProject)/_apis/build/builds/$(Build.BuildId)/tags/$($tag)?api-version=5.1"

  Invoke-RestMethod -Uri $urltagupdate -Headers @{authorization = "Bearer $(System.AccessToken)"} -Method put

}
</code>```

Above is an example for build tags. If you want to tag repo branch you can use refs tag api.

The main idea is to get the previous tag via api and update the version.patch and version.build according to the build.sourcebranch in a powershell task.

Body:
I'm trying to setup an Azure Pipeline that automatically updates version numbers based on which branch is being built. Given a master branch, a develop branch, and a version in the form {major.minor.patch.build} I want to achieve the following:

Whenever the pipeline is triggered by master:

patch is incremented by 1

build is reset to 0

Whenever the pipeline is triggered by develop:

build is incremented by 1

An example of what I expect the version numbers to look like after multiple runs assuming a starting version of 1.0.0.0:

Run 1 on develop: 1.0.0.1

Run 2 on develop: 1.0.0.2

Run 3 on master: 1.0.1.0

Run 4 on master: 1.0.2.0

Run 5 on develop: 1.0.2.1

Run 6 on develop: 1.0.2.2

Run 7 on master: 1.0.3.0

My first thought was to use a counter for the patch and build values but there doesn't seem to be a way of conditionally incrementing them or resetting the counter. My next thought was to use a couple script tasks that execute conditionally based on the branch, such as:

    #Update build
    - powershell: echo "##vso[task.setvariable variable=version.build;isOutput=true]$(version.build + 1)"
      condition: eq(variables['Build.SourceBranch'], 'refs/heads/develop')

    #Reset build number
    - powershell: echo "##vso[task.setvariable variable=version.build;isOutput=true]0"
      condition: eq(variables['Build.SourceBranch'], 'refs/heads/master')

    #Update patch
    - powershell: echo "##vso[task.setvariable variable=version.patch;isOutput=true]$(version.patch + 1)"
      condition: eq(variables['Build.SourceBranch'], 'refs/heads/master')

However that approach isn't persistent across runs (not to mention $(version.patch + 1) doesn't work. I can't find any information on how to actually increment a variable in this way). My last idea was to have a version file in the repository and use that but I really don't want to have to go down that route.

Is there a way to achieve what I'm looking for using Pipelines or am I barking up the wrong tree trying to go about it this way?

Edit
I should have mentioned in the question that at this point I have a pipeline setup that builds my application but does nothing with versioning. What I'm looking for at this point is a way to dynamically update a few persistent variables/values (specifically patch and build).

Body:
I have a workaround to achieve this with restful api.

For example you want to add above version tag to the build. You can first get the tag of the previous build with get tag api. Then you can update the version with the scripts and update it with updated tag. You can refer to below scripts in the powershell task.

# first get previous build id

$url = "$(System.TeamFoundationCollectionUri)$(System.TeamProject)/_apis/build/builds?definitions={pipeline Id}&`$top=2&api-version=5.1"

$result = Invoke-RestMethod -Uri $url -Headers @{authorization = "Bearer $(System.AccessToken)"} -Method get

$builds = $result.value
$bid = $builds[1].id

# get the build tag with get build tag api

$urltag ="$(System.TeamFoundationCollectionUri)$(System.TeamProject)/_apis/build/builds/$bid/tags?api-version=5.1"

$tagResult = Invoke-RestMethod -Uri $urltag -Headers @{authorization = "Bearer $(System.AccessToken)"} -Method get

# get the tag and update it

if($tagResult.value)
{
   $tagarr = [regex]::split($result.value, '\.')
   $patch = $tagarr[2]
   $build = $tagarr[3]
   $tag=""
   if("$(Build.SourceBranch)" -eq "refs/heads/master")
   {
      $patch = [int]$patch + 1
      # update the variables version.patch and version.build with below scripts, so that it can be referenced in the following tasks.
      #echo "##vso[task.setvariable variable=version.patch;isOutput=true]$patch"
      #echo "##vso[task.setvariable variable=version.build;isOutput=true]0"

     $tag = "$(version.major).$(version.minor).$patch.0"
   }
   if("$(Build.SourceBranch)" -eq "refs/heads/dev")
   {
      $build= [int]$build+ 1
      #echo "##vso[task.setvariable variable=version.patch;isOutput=true]$patch"
      #echo "##vso[task.setvariable variable=version.build;isOutput=true]$build"
      $tag = "$(version.major).$(version.minor).$patch.$build"
   }

 #add $tag to current build.
  $urltagupdate = "$(System.TeamFoundationCollectionUri)$(System.TeamProject)/_apis/build/builds/$(Build.BuildId)/tags/$($tag)?api-version=5.1"

  Invoke-RestMethod -Uri $urltagupdate -Headers @{authorization = "Bearer $(System.AccessToken)"} -Method put

}else
{
  #if the build is run for the first time and the tag is not exist.
  #you can omit this part by manually creating a initial tag for the build.

  $tag = ""
  if("$(Build.SourceBranchName)" -eq "refs/heads/master")
  {
    $tag = "1.0.1.0"
  }
  if("$(Build.SourceBranchName)" -eq "refs/heads/dev")
  {
    $tag="1.0.0.1"
  }

 #add $tag to current build.

  $urltagupdate = "$(System.TeamFoundationCollectionUri)$(System.TeamProject)/_apis/build/builds/$(Build.BuildId)/tags/$($tag)?api-version=5.1"

  Invoke-RestMethod -Uri $urltagupdate -Headers @{authorization = "Bearer $(System.AccessToken)"} -Method put

}

Above is an example for build tags. If you want to tag repo branch you can use refs tag api.

The main idea is to get the previous tag via api and update the version.patch and version.build according to the build.sourcebranch in a powershell task.


问:
Kotlin addTextChangeListener lambda?
How do you build a lambda expression for the EditText addTextChangeListener in Kotlin? Below gives an error:</p>

```<code>passwordEditText.addTextChangedListener { charSequence  ->
    try {
        password = charSequence.toString()
    } catch (error: Throwable) {
        raise(error)
    }
}
</code>```

答:
Sorry for being late!

If you add implementation 'androidx.core:core-ktx:1.1.0' to your module's build.gradle file then you can use

```<code>etPlayer1.doOnTextChanged { text, start, count, after -> // Do stuff }
</code>```

Title: Kotlin addTextChangeListener lambda?

Body:
How do you build a lambda expression for the EditText addTextChangeListener in Kotlin? Below gives an error:

passwordEditText.addTextChangedListener { charSequence  ->
    try {
        password = charSequence.toString()
    } catch (error: Throwable) {
        raise(error)
    }
}

Body:
Sorry for being late!

If you add implementation 'androidx.core:core-ktx:1.1.0' to your module's build.gradle file then you can use

etPlayer1.doOnTextChanged { text, start, count, after -> // Do stuff }


问:
How can I access the current executing module or class name in Python?
I would like to be able to dynamically retrieve the current executing module or class name from within an imported module.  Here is some code:

foo.py:

```<code>def f():
    print __name__
</code>```

bar.py:

```<code>from foo import f

def b(): f()
</code>```

This obviously does not work as __name__ is the name of the module that contains the function.  What I would like to be access inside the foo module is the name of the current executing module that is using foo.  So in the case above it would be bar but if any other module imported foo I would like foo to dynamically have access to the name of that module.

Edit: The inspect module looks quite promising but it is not exactly what I was looking for.  What I was hoping for was some sort of global or environment-level variable that I could access that would contain the name of the current executing module.  Not that I am unwilling to traverse the stack to find that information - I just thought that Python may have exposed that data already.

Edit: Here is how I am trying to use this.  I have two different Django applications that both need to log errors to file.  Lets say that they are called "AppOne" and "AppTwo".  I also have a place to which I would like to log these files: "/home/hare/app_logs".  In each application at any given point I would like to be able to import my logger module and call the log function which writes the log string to file.  However what I would like to do is create a directory under app_logs that is the name of the current application ("AppOne" or "AppTwo") so that each application's log files will go in their respective logging directories.

In order to do this I thought that the best way would be for the logger module to have access to some sort of global variable that denotes the current application's name as it is responsible for knowing the location of the parent logging directory and creating the application's logging directory if it does not yet exist.

答:
The "currently executing module" clearly is foo, as that's what contains the function currently running - I think a better description as to what you want is the module of foo's immediate caller (which may itself be foo if you're calling a f() from a function in foo called by a function in bar.  How far you want to go up depends on what you want this for.

In any case, assuming you want the immediate caller, you can obtain this by walking up the call stack.  This can be accomplished by calling sys._getframe, with the aprropriate number of levels to walk.

```<code>def f():
    caller = sys._getframe(1)  # Obtain calling frame
    print "Called from module", caller.f_globals['__name__']
</code>```

[Edit]:  Actually, using the inspect module as suggested above is probably a cleaner way of obtaining the stack frame.  The equivalent code is:

```<code>def f():
    caller = inspect.currentframe().f_back
    print "Called from module", caller.f_globals['__name__']
</code>```

(sys._getframe is documented as being for internal use - the inspect module is a more reliable API)

OwnerDisplayName: Andrew Hare

ContentLicense: CC BY-SA 2.5

Body:
I would like to be able to dynamically retrieve the current executing module or class name from within an imported module.  Here is some code:

foo.py:

def f():
    print __name__

bar.py:

from foo import f

def b(): f()

This obviously does not work as __name__ is the name of the module that contains the function.  What I would like to be access inside the foo module is the name of the current executing module that is using foo.  So in the case above it would be bar but if any other module imported foo I would like foo to dynamically have access to the name of that module.

Edit: The inspect module looks quite promising but it is not exactly what I was looking for.  What I was hoping for was some sort of global or environment-level variable that I could access that would contain the name of the current executing module.  Not that I am unwilling to traverse the stack to find that information - I just thought that Python may have exposed that data already.

Edit: Here is how I am trying to use this.  I have two different Django applications that both need to log errors to file.  Lets say that they are called "AppOne" and "AppTwo".  I also have a place to which I would like to log these files: "/home/hare/app_logs".  In each application at any given point I would like to be able to import my logger module and call the log function which writes the log string to file.  However what I would like to do is create a directory under app_logs that is the name of the current application ("AppOne" or "AppTwo") so that each application's log files will go in their respective logging directories.

In order to do this I thought that the best way would be for the logger module to have access to some sort of global variable that denotes the current application's name as it is responsible for knowing the location of the parent logging directory and creating the application's logging directory if it does not yet exist.

LastEditorDisplayName: Andrew Hare

Body:
The "currently executing module" clearly is foo, as that's what contains the function currently running - I think a better description as to what you want is the module of foo's immediate caller (which may itself be foo if you're calling a f() from a function in foo called by a function in bar.  How far you want to go up depends on what you want this for.

In any case, assuming you want the immediate caller, you can obtain this by walking up the call stack.  This can be accomplished by calling sys._getframe, with the aprropriate number of levels to walk.

def f():
    caller = sys._getframe(1)  # Obtain calling frame
    print "Called from module", caller.f_globals['__name__']

[Edit]:  Actually, using the inspect module as suggested above is probably a cleaner way of obtaining the stack frame.  The equivalent code is:

def f():
    caller = inspect.currentframe().f_back
    print "Called from module", caller.f_globals['__name__']

(sys._getframe is documented as being for internal use - the inspect module is a more reliable API)

OwnerDisplayName: Brian

LastEditorDisplayName: Brian


问:
Why are by-value parameters excluded from NRVO?
Imagine:

```<code>S f(S a) {
  return a;
}
</code>```

Why is it not allowed to alias a and the return value slot?

```<code>S s = f(t);
S s = t; // can't generally transform it to this :(
</code>```

The spec doesn't allow this transformation if the copy constructor of S has side effects. Instead, it requires at least two copies (one from t to a, and one from a to the return value, and another from the return value to s, and only that last one can be elided. Note that I wrote = t above to represent the fact of a copy of t to f's a, the only copy which would still be mandatory in the presence of side effects of move/copy constructor).

Why is that?

答:
David Rodríguez - dribeas answer to my question 'How to allow copy elision construction for C++ classes' gave me the following idea. The trick is to use lambdas to delay evaluation til inside the function body:

```<code>#include <iostream>

struct S
{
  S() {}
  S(const S&) { std::cout << "Copy" << std::endl; }
  S(S&&) { std::cout << "Move" << std::endl; }
};

S f1(S a) {
  return a;
}

S f2(const S& a) {
  return a;
}

#define DELAY(x) [&]{ return x; }

template <class F>
S f3(const F& a) {
  return a();
}

int main()
{
  S t;
  std::cout << "Without delay:" << std::endl;
  S s1 = f1(t);
  std::cout << "With delay:" << std::endl;
  S s2 = f3(DELAY(t));
  std::cout << "Without delay pass by ref:" << std::endl;
  S s3 = f2(t);
  std::cout << "Without delay pass by ref (temporary) (should have 0 copies, will get 1):" << std::endl;
  S s4 = f2(S());
  std::cout << "With delay (temporary) (no copies, best):" << std::endl;
  S s5 = f3(DELAY(S()));
}
</code>```

This outputs on ideone GCC 4.5.1:

Without delay:

  Copy

  Copy

  With delay:

  Copy

Now this is good, but one could suggest that the DELAY version is just like passing by const reference, as below:

Without delay pass by ref:

  Copy

But if we pass a temporary by const reference, we still get a copy:

Without delay pass by ref (temporary) (should have 0 copies, will get 1):

  Copy

Where the delayed version elides the copy:

With delay (temporary) (no copies, best):

As you can see, this elides all copies in the temporary case.

The delayed version produces one copy in the non-temporary case, and no copies in the case of a temporary. I don't know any way to achieve this other than lambdas, but I'd be interested if there is.

Body:
Imagine:

S f(S a) {
  return a;
}

Why is it not allowed to alias a and the return value slot?

S s = f(t);
S s = t; // can't generally transform it to this :(

The spec doesn't allow this transformation if the copy constructor of S has side effects. Instead, it requires at least two copies (one from t to a, and one from a to the return value, and another from the return value to s, and only that last one can be elided. Note that I wrote = t above to represent the fact of a copy of t to f's a, the only copy which would still be mandatory in the presence of side effects of move/copy constructor).

Why is that?

Body:
David Rodríguez - dribeas answer to my question 'How to allow copy elision construction for C++ classes' gave me the following idea. The trick is to use lambdas to delay evaluation til inside the function body:

#include <iostream>

struct S
{
  S() {}
  S(const S&) { std::cout << "Copy" << std::endl; }
  S(S&&) { std::cout << "Move" << std::endl; }
};

S f1(S a) {
  return a;
}

S f2(const S& a) {
  return a;
}

#define DELAY(x) [&]{ return x; }

template <class F>
S f3(const F& a) {
  return a();
}

int main()
{
  S t;
  std::cout << "Without delay:" << std::endl;
  S s1 = f1(t);
  std::cout << "With delay:" << std::endl;
  S s2 = f3(DELAY(t));
  std::cout << "Without delay pass by ref:" << std::endl;
  S s3 = f2(t);
  std::cout << "Without delay pass by ref (temporary) (should have 0 copies, will get 1):" << std::endl;
  S s4 = f2(S());
  std::cout << "With delay (temporary) (no copies, best):" << std::endl;
  S s5 = f3(DELAY(S()));
}

This outputs on ideone GCC 4.5.1:

Without delay:

  Copy

  Copy

  With delay:

  Copy

Now this is good, but one could suggest that the DELAY version is just like passing by const reference, as below:

Without delay pass by ref:

  Copy

But if we pass a temporary by const reference, we still get a copy:

Without delay pass by ref (temporary) (should have 0 copies, will get 1):

  Copy

Where the delayed version elides the copy:

With delay (temporary) (no copies, best):

As you can see, this elides all copies in the temporary case.

The delayed version produces one copy in the non-temporary case, and no copies in the case of a temporary. I don't know any way to achieve this other than lambdas, but I'd be interested if there is.


问:
How are neural networks, loss and optimizer connected in PyTorch?
I've seen answers to this question, but I still don't understand it at all. As far as I know, this is the most basic setup:

```<code>net = CustomClassInheritingFromModuleWithDefinedInitAndForward()
criterion = nn.SomeLossClass()
optimizer = optim.SomeOptimizer(net.parameters(), ...)
for _, data in enumerate(trainloader, 0):
    inputs, labels = data
    optimizer.zero_grad()
    outputs = net(inputs)
    loss = criterion(outputs, labels)
    loss.backward()
    optimizer.step()
</code>```

What I don't understand is:

Optimizer is initialized with net.parameters(), which I thought are internal weights of the net.

Loss does not access these parameters nor the net itself. It only has access to net's outputs and input labels.

Optimizer does not access loss either.

So if loss only works on outputs and optimizer only on net.parameters, how can they be connected?

答:
Optimizer is initialized with net.parameters(), which I thought are internal weights of the net.

This is because the optimizer will modify the parameters of your net during the training.

Loss does not access these parameters nor the net itself. It only has access to net's outputs and input labels.

The loss only computes an error between a prediction and the truth.

Optimizer does not access loss either.

It accesses the tensors that were computed during loss.backward

Body:
I've seen answers to this question, but I still don't understand it at all. As far as I know, this is the most basic setup:

net = CustomClassInheritingFromModuleWithDefinedInitAndForward()
criterion = nn.SomeLossClass()
optimizer = optim.SomeOptimizer(net.parameters(), ...)
for _, data in enumerate(trainloader, 0):
    inputs, labels = data
    optimizer.zero_grad()
    outputs = net(inputs)
    loss = criterion(outputs, labels)
    loss.backward()
    optimizer.step()

What I don't understand is:

Optimizer is initialized with net.parameters(), which I thought are internal weights of the net.

Loss does not access these parameters nor the net itself. It only has access to net's outputs and input labels.

Optimizer does not access loss either.

So if loss only works on outputs and optimizer only on net.parameters, how can they be connected?


问:
Flutter : Unable to redirect to specific screen on Notification click when app is in background but not terminated in iOS
I have used firebase_messaging plugin for notifications, on both platforms notifications works fine,

However, I want to redirect user to specific screen on Notification click event. For Android side, it's working fine. But for IOS, it does not work if app is in background and is not terminated (Works fine if app is terminated).

Here's my code sample for notification integration:

_firebaseMessaging.configure(
  onMessage: (Map<String, dynamic> message) async {
    print("onMessage: $message");
    gotoTempPage();
  },
  onLaunch: (Map<String, dynamic> message) async {
    print("onLaunch: $message");
    gotoTempPage();
  },
  onResume: (Map<String, dynamic> message) async {
    print("onResume: $message");
    gotoTempPage();
  },
);
```

I am using plugin version firebase_messaging: ^6.0.9, and flutter version v1.12.13+hotfix.5

Already referred these issues 935, 1757, 1677 but nothing helped me.

答:
Hi i had exactly the same issue. So, according to the current documentation of the plugin (firebase_messaging), you should make some modification to your Appdelegate.m/Appdelegate.swift file.

This modification is the problem.

Remove the following code from your AppDelegate.swift or similar in AppDelegate.m

```<code>if #available(iOS 10.0, *) {
          UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
}
</code>```

It seems to be a bug or issue with this version of firebase_messaging (6.0.9) as in here

Body:
I have used firebase_messaging plugin for notifications, on both platforms notifications works fine,

However, I want to redirect user to specific screen on Notification click event. For Android side, it's working fine. But for IOS, it does not work if app is in background and is not terminated (Works fine if app is terminated).

Here's my code sample for notification integration:

_firebaseMessaging.configure(
  onMessage: (Map<String, dynamic> message) async {
    print("onMessage: $message");
    gotoTempPage();
  },
  onLaunch: (Map<String, dynamic> message) async {
    print("onLaunch: $message");
    gotoTempPage();
  },
  onResume: (Map<String, dynamic> message) async {
    print("onResume: $message");
    gotoTempPage();
  },
);

I am using plugin version firebase_messaging: ^6.0.9, and flutter version v1.12.13+hotfix.5

Already referred these issues 935, 1757, 1677 but nothing helped me.

Body:
Hi i had exactly the same issue. So, according to the current documentation of the plugin (firebase_messaging), you should make some modification to your Appdelegate.m/Appdelegate.swift file.

This modification is the problem.

Remove the following code from your AppDelegate.swift or similar in AppDelegate.m

if #available(iOS 10.0, *) {
          UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
}

It seems to be a bug or issue with this version of firebase_messaging (6.0.9) as in here


问:
Eliminate Errors
Here is what I am struggling with.

This is a clocking system and I want to take out the errors.

Trying a select statment to get all the records where there is a duplicate "clock in" or duplicate "clock out" for the same user.

You have an employee_ID and a direction.

The data looks something like this:

```<code>ID.......employee_ID.........Direction

 1. .........1..................In
 2. .........2..................In
 3. .........3..................In
 4. .........1..................Out
 5. .........2..................Out
 6. .........3..................In
</code>```

So record 6 would be an error.

答: as you say its a clocking system, you need to have a timestamp or a auto increment id column, based on which you can check the last event (latest timestamp or the max id) for every emp Id before inserting (as part of trigger). </p>

Title: Eliminate Errors

Body:
Here is what I am struggling with.

This is a clocking system and I want to take out the errors.

Trying a select statment to get all the records where there is a duplicate "clock in" or duplicate "clock out" for the same user.

You have an employee_ID and a direction.

The data looks something like this:

ID.......employee_ID.........Direction

 1. .........1..................In
 2. .........2..................In
 3. .........3..................In
 4. .........1..................Out
 5. .........2..................Out
 6. .........3..................In

So record 6 would be an error.


问:
Android Studio change color of the app name
fHow can I change the color of the app name, I have changed the toolbar text color to white but the app name is still in black. I have also noticed if I change the color of the bar to black the app name color becomes white. I want the app name color to be like WhatsApp.

答:
try this

```<code><style name="MyActionBarTitleText"
           parent="@android:style/TextAppearance.Holo.Widget.ActionBar.Title">
        <item name="android:textColor">@android:color/darker_gray</item>
</style>
</code>```

I hope it will help you .

Body:
try this

<style name="MyActionBarTitleText"
           parent="@android:style/TextAppearance.Holo.Widget.ActionBar.Title">
        <item name="android:textColor">@android:color/darker_gray</item>
</style>

I hope it will help you .


问:
Override default Spring-Boot application.properties settings in Junit Test
I have a Spring-Boot application where the default properties are set in an application.properties file in the classpath (src/main/resources/application.properties).

I would like to override some default settings in my JUnit test with properties declared in a test.properties file (src/test/resources/test.properties)

I usualy have a dedicated Config Class for my Junit Tests, e.g.

```<code>package foo.bar.test;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@Import(CoreConfig.class)
@EnableAutoConfiguration
public class TestConfig {

}
</code>```

I first thought that using @PropertySource("classpath:test.properties") in  the TestConfig class would do the trick, but these properties will not overwrite the application.properties settings (see Spring-Boot Reference Doc - 23. Externalized Configuration).

Then I tried to use -Dspring.config.location=classpath:test.properties when invoking the test. That was successful - but I don't want to set this system property for each test execution. Thus I put it in the code

```<code>@Configuration
@Import(CoreConfig.class)
@EnableAutoConfiguration
public class TestConfig {

  static {
    System.setProperty("spring.config.location", "classpath:test.properties");
  }

}
</code>```

which unfortunatly was again not successful.

There must be a simple solution on how to override application.properties settings in JUnit tests with test.properties that I must have overlooked.

答:
If you are like me and you have the same application.properties in src/main/resources and src/test/resources, and you are wondering why the application.properties in your test folder is not overriding the application.properties in your main resources, read on...

Simple explanation:

If you have application.properties under src/main/resources and the same application.properties under src/test/resources, which application.properties gets picked up, depends on how you are running your tests. The folder structure src/main/resources and src/test/resources, is a Maven architectural convention, so if you run your test like mvnw test or even gradlew test, the application.properties in src/test/resources will get picked up, as test classpath will precede main classpath. But, if you run your test like Run as JUnit Test in Eclipse/STS, the application.properties in src/main/resources will get picked up, as main classpath precedes test classpath.

You can check it out by opening the menu bar Run > Run Configurations > JUnit > *your_run_configuration* > Click on "Show Command Line".

You will see something like this:

XXXbin\javaw.exe -ea -Dfile.encoding=UTF-8 -classpath

XXX\workspace-spring-tool-suite-4-4.5.1.RELEASE\project_name\bin\main;

XXX\workspace-spring-tool-suite-4-4.5.1.RELEASE\project_name\bin\test;

Do you see that classpath xxx\main comes first, and then xxx\test? Right, it's all about classpath :-)

Side-note:
Be mindful that properties overridden in the Launch Configuration(In Spring Tool Suite IDE, for example) takes priority over application.properties.

Change the order:

Now, everything is configurable in Spring. You can change the build classpath, so that xxx\test comes first, and then xxx\main.

Simply go to Project > Properties > Java Build Path > Order and Export, change the build class path order by putting any of the test folder first such as:

And that's it!

Better solution

A better solution though, when testing, would be to activate the src/test/resources/application-{profile}.properties (where profile can be test), such as the following in src/main/resources/application.properties:

spring.profiles.active=test

This is neater, and gives you complete control on what profile to activate when doing what.

Body:
I have a Spring-Boot application where the default properties are set in an application.properties file in the classpath (src/main/resources/application.properties).

I would like to override some default settings in my JUnit test with properties declared in a test.properties file (src/test/resources/test.properties)

I usualy have a dedicated Config Class for my Junit Tests, e.g.

package foo.bar.test;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@Import(CoreConfig.class)
@EnableAutoConfiguration
public class TestConfig {

}

I first thought that using @PropertySource("classpath:test.properties") in  the TestConfig class would do the trick, but these properties will not overwrite the application.properties settings (see Spring-Boot Reference Doc - 23. Externalized Configuration).

Then I tried to use -Dspring.config.location=classpath:test.properties when invoking the test. That was successful - but I don't want to set this system property for each test execution. Thus I put it in the code

@Configuration
@Import(CoreConfig.class)
@EnableAutoConfiguration
public class TestConfig {

  static {
    System.setProperty("spring.config.location", "classpath:test.properties");
  }

}

which unfortunatly was again not successful.

There must be a simple solution on how to override application.properties settings in JUnit tests with test.properties that I must have overlooked.


问:
Linq: How can I get a result in a grouping query which is value agnostic and has dynamic columns?
I have a table called Foo and I have two columns: Lorem and Ipsum, so the scheme of the table is:

```<code>Foo(Lorem, IpsumID)
</code>```

I also have a table called IpsumTypes, which looks like this:

```<code>IpsumTypes(IpsumID, IpsumName)
</code>```

I would like to write a LINQ query which will have the following result:

Headers: Lorem, IpsumName1, IpsumName2, ..., IpsumNamen
Values: Loremi, count(IpsumName1), ..., count(IpsumNamen)

Each row represents a group of Lorem value and the number of each possible IpsumID in the group. New rows can be added to the IpsumTypes table, rows can be deleted too, so I need dynamically generated columns, because at the time of writing the code I'm not aware of the possible values of Ipsum. How can I achieve this? Is there a magical Linq query which solves this problem, or should I get the values from the database and parse them separately, if speed counts?

Thank you in advance for your responses.

答: I think you are looking for PIVOT SQL statement. But there is no LINQ equivalent, so you should use SQL instead and parse the returned data yourself.</p>

Body:
I have a table called Foo and I have two columns: Lorem and Ipsum, so the scheme of the table is:

Foo(Lorem, IpsumID)

I also have a table called IpsumTypes, which looks like this:

IpsumTypes(IpsumID, IpsumName)

I would like to write a LINQ query which will have the following result:

Headers: Lorem, IpsumName1, IpsumName2, ..., IpsumNamen
Values: Loremi, count(IpsumName1), ..., count(IpsumNamen)

Each row represents a group of Lorem value and the number of each possible IpsumID in the group. New rows can be added to the IpsumTypes table, rows can be deleted too, so I need dynamically generated columns, because at the time of writing the code I'm not aware of the possible values of Ipsum. How can I achieve this? Is there a magical Linq query which solves this problem, or should I get the values from the database and parse them separately, if speed counts?

Thank you in advance for your responses.


问:
Libqmi - glib callback function not getting called
I am new to libqmi and wanted to start by just opening a new device. But the callback function is never getting called and therefore no device object returned.

I running the code on Ubuntu 64 Bit.

On this website: https://developer.gnome.org/gio/stable/GAsyncResult.html

I found how this should be handled and programmed it that way, but it still doesn't work.

```<code>#include <iostream>
#include <libqmi-glib/libqmi-glib.h>
#include <gio/gio.h>

using namespace std;

void device_create_start(const char* device_file);
void device_create_stop(GObject* obj, GAsyncResult* res, gpointer data);

int something = 0;

int main()
{
    cout << "Start\n";
    device_create_start("/dev/cdc-wdm0");

    cout << "DEBUG: Something: " << something << "\n";
    cout << "Stop\n";

    return 0;
}

void device_create_start(const char* device_file)
{
    GFile* file = g_file_new_for_path(device_file);

    if(file)
    {
        GCancellable* cancellable = g_cancellable_new();
        GAsyncReadyCallback callback = device_create_stop;
        gpointer user_data = NULL;

        cout << "INFO: qmi_device_new starting!\n";
        qmi_device_new(file, cancellable, callback, user_data);
        cout << "INFO: qmi_device_new started!\n";

        cout <<  "INFO: Waiting!\n";
        usleep(10000);

        cout <<  "INFO: Is cancelled?: " << g_cancellable_is_cancelled(cancellable) << "\n";
        cout <<  "INFO: canceling!\n";
        g_cancellable_cancel(cancellable);
        cout <<  "INFO: Waiting again!\n";
        usleep(100000);
        cout <<  "INFO: Is cancelled?: " << g_cancellable_is_cancelled(cancellable) << "\n";

        something = 1;
    }
    else
    {
        cout << "ERROR: Could not create device file!\n";
    }
}
void device_create_stop(GObject* obj, GAsyncResult* res, gpointer data)
{
    cout << "INFO: device_create_stop\n";

    something = 2;

    cout << "INFO: qmi_device_new_finish starting\n";
    GError *error;
    QmiDevice* device = qmi_device_new_finish(res, &error);
    cout << "INFO: qmi_device_new_finish started\n";

    if(device == NULL)
    {
         cout << "ERROR: Could not create device!\n";
    }
    else
    {
        cout << "INFO: Device created!\n";
        //device_open(device);
    }
}
</code>```

When I run this code the output is:

```<code>Start
INFO: qmi_device_new starting!
INFO: qmi_device_new started!
INFO: Waiting!
INFO: Is cancelled?: 0
INFO: canceling!
INFO: Waiting again!
INFO: Is cancelled?: 1
DEBUG: Something: 1
Stop
</code>```

The code in the callback function is never called.

Update 1

I simplified the code and changed some things that I oversaw on the gnome reference site, like a static callback function. But this doesn't work either

```<code>#include <iostream>
#include <libqmi-glib/libqmi-glib.h>
#include <gio/gio.h>
#include <glib/gprintf.h>

using namespace std;

void device_create_start(const char* device_file);
static void device_create_stop(GObject* obj, GAsyncResult* res, gpointer data);

int something = 0;

int main()
{
    g_printf ("Start\n");
    device_create_start("/dev/cdc-wdm0");

    cout << "DEBUG: Something: " << something << "\n";

    while(true)
    {
        ;
    }

    cout << "Stop\n";

    return 0;
}
void device_create_start(const char* device_file)
{
    GFile* file = g_file_new_for_path(device_file);

    if(file)
    {
        cout << "INFO: qmi_device_new starting!\n";
        qmi_device_new(file, NULL, device_create_stop, NULL);
        cout << "INFO: qmi_device_new started!\n";
        something = 1;
    }
    else
    {
        cout << "ERROR: Could not create device!\n";
    }
}
static void device_create_stop(GObject* obj, GAsyncResult* res, gpointer data)
{
    g_printf ("Hurray!\n");
    something = 2;
}
</code>```

The new output:

```<code>Start
INFO: qmi_device_new starting!
INFO: qmi_device_new started!
DEBUG: Something: 1
</code>```

Does anyone has a clue why this is not working?

答: As Philip said (hey Philip!), you're missing the main loop. The qmi_device_new() function is an method that finishes asynchronously, and once finished, the result of the operation is provided in the callback function you provide. In order for the asynchronous function to even do something, you need to have a GMainLoop running for as long as your program logic runs.

Body:
I am new to libqmi and wanted to start by just opening a new device. But the callback function is never getting called and therefore no device object returned.

I running the code on Ubuntu 64 Bit.

On this website: https://developer.gnome.org/gio/stable/GAsyncResult.html

I found how this should be handled and programmed it that way, but it still doesn't work.

#include <iostream>
#include <libqmi-glib/libqmi-glib.h>
#include <gio/gio.h>

using namespace std;

void device_create_start(const char* device_file);
void device_create_stop(GObject* obj, GAsyncResult* res, gpointer data);

int something = 0;

int main()
{
    cout << "Start\n";
    device_create_start("/dev/cdc-wdm0");

    cout << "DEBUG: Something: " << something << "\n";
    cout << "Stop\n";

    return 0;
}

void device_create_start(const char* device_file)
{
    GFile* file = g_file_new_for_path(device_file);

    if(file)
    {
        GCancellable* cancellable = g_cancellable_new();
        GAsyncReadyCallback callback = device_create_stop;
        gpointer user_data = NULL;

        cout << "INFO: qmi_device_new starting!\n";
        qmi_device_new(file, cancellable, callback, user_data);
        cout << "INFO: qmi_device_new started!\n";

        cout <<  "INFO: Waiting!\n";
        usleep(10000);

        cout <<  "INFO: Is cancelled?: " << g_cancellable_is_cancelled(cancellable) << "\n";
        cout <<  "INFO: canceling!\n";
        g_cancellable_cancel(cancellable);
        cout <<  "INFO: Waiting again!\n";
        usleep(100000);
        cout <<  "INFO: Is cancelled?: " << g_cancellable_is_cancelled(cancellable) << "\n";

        something = 1;
    }
    else
    {
        cout << "ERROR: Could not create device file!\n";
    }
}
void device_create_stop(GObject* obj, GAsyncResult* res, gpointer data)
{
    cout << "INFO: device_create_stop\n";

    something = 2;

    cout << "INFO: qmi_device_new_finish starting\n";
    GError *error;
    QmiDevice* device = qmi_device_new_finish(res, &error);
    cout << "INFO: qmi_device_new_finish started\n";

    if(device == NULL)
    {
         cout << "ERROR: Could not create device!\n";
    }
    else
    {
        cout << "INFO: Device created!\n";
        //device_open(device);
    }
}

When I run this code the output is:

Start
INFO: qmi_device_new starting!
INFO: qmi_device_new started!
INFO: Waiting!
INFO: Is cancelled?: 0
INFO: canceling!
INFO: Waiting again!
INFO: Is cancelled?: 1
DEBUG: Something: 1
Stop

The code in the callback function is never called.

Update 1

I simplified the code and changed some things that I oversaw on the gnome reference site, like a static callback function. But this doesn't work either

#include <iostream>
#include <libqmi-glib/libqmi-glib.h>
#include <gio/gio.h>
#include <glib/gprintf.h>

using namespace std;

void device_create_start(const char* device_file);
static void device_create_stop(GObject* obj, GAsyncResult* res, gpointer data);

int something = 0;

int main()
{
    g_printf ("Start\n");
    device_create_start("/dev/cdc-wdm0");

    cout << "DEBUG: Something: " << something << "\n";

    while(true)
    {
        ;
    }

    cout << "Stop\n";

    return 0;
}
void device_create_start(const char* device_file)
{
    GFile* file = g_file_new_for_path(device_file);

    if(file)
    {
        cout << "INFO: qmi_device_new starting!\n";
        qmi_device_new(file, NULL, device_create_stop, NULL);
        cout << "INFO: qmi_device_new started!\n";
        something = 1;
    }
    else
    {
        cout << "ERROR: Could not create device!\n";
    }
}
static void device_create_stop(GObject* obj, GAsyncResult* res, gpointer data)
{
    g_printf ("Hurray!\n");
    something = 2;
}

The new output:

Start
INFO: qmi_device_new starting!
INFO: qmi_device_new started!
DEBUG: Something: 1

Does anyone has a clue why this is not working?


问:
How to manage editable shared libraries with poetry?
I have 2 python projects A and B

A depends on B

B is a shared library that is used by other projects

B takes a long time to build and install

Previously, when I have to set up my development environment on a fresh computer the workflow was:

create a virtual environment

git clone A and B

run B's setup develop

run A's setup develop

Now I can edit A and B and push the changes to git without having to rerun setup on A and B every time.

Now, I want to integrate poetry into my workflow. Ideally I want to be able to git clone A and run poetry install A and have it mirror my above setup and but I am having trouble installing B through A's setup while still keeping B editable. Based on this thread it seems like sharing venv between two project is not possible.

My stopgap workaround is:

git clone A and B

poetry install B

edit A's pyproject.toml to point to the B directory that I manually installed (B = {path = "../B/"})

poetry install A

I really don't like this workflow since A's pyproject.toml now only works on my computer. I looked through issue threads and poetry documentation and could not find solution dealing with this situation. Any and all advises are greatly appreciated.

A's pyproject.toml

```<code>[tool.poetry.dependencies]
python = "^3.7"
# B = {git = "https://repo.com/myrepo/B.git"}
B = {path = "../B/"}
</code>```

Edit: I realized that if I install B before A and edited pyproject before installing A I can prevent 2 installation of B

答:
I'm not sure if this solves your problem but you might be able to use one venv for two projects (is that what you want?) by creating the virtual environment first and then install both project's dependencies in it.

I can't verify it now but something like this might help:

```<code># create the virtual environment and activate
$ python3 -mvenv .venv
$ . .venv/bin/activate

# install dependencies of both projects in it
$ cd B
$ poetry install
$ cd ../A
$ poetry install
</code>```

Body:
I have 2 python projects A and B

A depends on B

B is a shared library that is used by other projects

B takes a long time to build and install

Previously, when I have to set up my development environment on a fresh computer the workflow was:

create a virtual environment

git clone A and B

run B's setup develop

run A's setup develop

Now I can edit A and B and push the changes to git without having to rerun setup on A and B every time.

Now, I want to integrate poetry into my workflow. Ideally I want to be able to git clone A and run poetry install A and have it mirror my above setup and but I am having trouble installing B through A's setup while still keeping B editable. Based on this thread it seems like sharing venv between two project is not possible.

My stopgap workaround is:

git clone A and B

poetry install B

edit A's pyproject.toml to point to the B directory that I manually installed (B = {path = "../B/"})

poetry install A

I really don't like this workflow since A's pyproject.toml now only works on my computer. I looked through issue threads and poetry documentation and could not find solution dealing with this situation. Any and all advises are greatly appreciated.

A's pyproject.toml

[tool.poetry.dependencies]
python = "^3.7"
# B = {git = "https://repo.com/myrepo/B.git"}
B = {path = "../B/"}

Edit: I realized that if I install B before A and edited pyproject before installing A I can prevent 2 installation of B

Body:
I'm not sure if this solves your problem but you might be able to use one venv for two projects (is that what you want?) by creating the virtual environment first and then install both project's dependencies in it.

I can't verify it now but something like this might help:

# create the virtual environment and activate
$ python3 -mvenv .venv
$ . .venv/bin/activate

# install dependencies of both projects in it
$ cd B
$ poetry install
$ cd ../A
$ poetry install


问:
Remove rows which nothing in more than one columns
```<code>data.frame(id = c(1,2,3,4), text1 = c("sth","","another",""), text2 = c("more","another","add",""), text3 = c("final","and","where",""), stringsAsFactors = FALSE)
</code>```

How is it possible to check for text1, text2, text3 column if all of them have cells with nothing written how to remove it?

Example of expected output

```<code>data.frame(id = c(1,2,3), text1 = c("sth","","another"), text2 = c("more","another","add"), text3 = c("final","and","where"), stringsAsFactors = FALSE)
</code>```

答:
Here is another base R solution using nchar + rowSums

```<code>subset(df,rowSums(nchar(as.matrix(df[-1])))>0)
</code>```

such that

```<code>  id   text1   text2 text3
1  1     sth    more final
2  2         another   and
3  3 another     add where
</code>```

Body:
data.frame(id = c(1,2,3,4), text1 = c("sth","","another",""), text2 = c("more","another","add",""), text3 = c("final","and","where",""), stringsAsFactors = FALSE)

How is it possible to check for text1, text2, text3 column if all of them have cells with nothing written how to remove it?

Example of expected output

data.frame(id = c(1,2,3), text1 = c("sth","","another"), text2 = c("more","another","add"), text3 = c("final","and","where"), stringsAsFactors = FALSE)

Body:
Here is another base R solution using nchar + rowSums

subset(df,rowSums(nchar(as.matrix(df[-1])))>0)

such that

  id   text1   text2 text3
1  1     sth    more final
2  2         another   and
3  3 another     add where


问:
What is the best practice for adding constants in laravel? (Long List)
I am rather new to laravel. I have a basic question, What is the best way to add constants in laravel.
I know the .env method that we use to add the constants.
Also I have made one constants file to use them for my project.
For example:

```<code>define('OPTION_ATTACHMENT', 13);
define('OPTION_EMAIL', 14);
define('OPTION_MONETERY', 15);
define('OPTION_RATINGS', 16);
define('OPTION_TEXTAREA', 17);
</code>```

And so on. It can reach upto 100 or more records. So What should be the best approach to write the constants. The .env method. Or adding the constant.php file?

Thanks

答:
```<code>require app_path().'/constants.php';

define('ADMIN',  'administrator');
</code>```

or  -

You can also move more sensitive info

```<code>return [
   'hash_salt' => env('HASH_SALT'),
 ];
</code>```

And use it like before:

```<code> echo Config::get('constants.hash_salt');
</code>```

Body:
I am rather new to laravel. I have a basic question, What is the best way to add constants in laravel.
I know the .env method that we use to add the constants.
Also I have made one constants file to use them for my project.
For example:

define('OPTION_ATTACHMENT', 13);
define('OPTION_EMAIL', 14);
define('OPTION_MONETERY', 15);
define('OPTION_RATINGS', 16);
define('OPTION_TEXTAREA', 17);

And so on. It can reach upto 100 or more records. So What should be the best approach to write the constants. The .env method. Or adding the constant.php file?

Thanks

Body:
require app_path().'/constants.php';

define('ADMIN',  'administrator');

or  -

You can also move more sensitive info

return [
   'hash_salt' => env('HASH_SALT'),
 ];

And use it like before:

 echo Config::get('constants.hash_salt');