问:
d3.json method doesn't return my data array
I'm using d3.json to load a JSON file containing my data, like this:

```<code>var data = d3.json(url, callback)
</code>```

If I do a console.log(data) I can see that data is neither empty nor null. However, it doesn't seem to contain my data array, but something else instead.

What am I doing wrong here?

Note: this is a self-answered question, trying to provide a "canonical" Q&A on a subject that has been touched on by many previous questions and not (clearly) explained by the API. The answer below was written as a general guidance to those questions.

答:
TL;DR

d3.json (as well as d3.csv, d3.tsv etc) does not return the content of the loaded/parsed file. Instead of that, it returns an object related to the request in D3 v4 or lower, and a promise in D3 v5 or higher.

What does d3.json return? (v4 or lower)

d3.json is one of the alternatives to XMLHttpRequest provided by D3. According to the API, d3.json...

Returns a new request to get the JSON file at the specified url with the default mime type application/json.

... which, we can agree, is not particularly clear. Because of that, you probably thought that you could return the loaded data using var data = d3.json(url, callback), but that's incorrect. What d3.json returns is an object (not an array), associated with the request. Let's see it.

I have this JSON in a file:

```<code>{"foo": "42"}
</code>```

What happens if we use d3.json the way you used it in your question? Click "run code snippet" to see:

var data = d3.json("https://api.npoint.io/5b22a0474c99d3049d2e", function() {});

console.log(data)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.min.js"></script></code>```

As you can see in the console, we have an object like this:

```<code>{header: ƒ, mimeType: ƒ, responseType: ƒ, timeout: ƒ, user: ƒ, …}
</code>```

Well, this is not our data array.

The same thing happens if you use a function:

function getData() {
  return d3.json("https://api.npoint.io/5b22a0474c99d3049d2e", function() {})
}

var data = getData()

console.log(data)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.min.js"></script></code>```

Also, it's worth mentioning that the same thing happens with d3.csv, d3.tsv and the other request methods:

var data = d3.csv("https://www.ibm.com/support/knowledgecenter/SVU13_7.2.1/com.ibm.ismsaas.doc/reference/AssetsImportCompleteSample.csv", function() {});

console.log(data)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.min.js"></script></code>```

How to use d3.json?

The correct way to load the data with d3.json, as you can see in several online examples, is using its callback:

```<code>d3.json(url, function(data){
    //use data here...
});
</code>```

And here is the snippet with our JSON file:

d3.json("https://api.npoint.io/5b22a0474c99d3049d2e", function(data) {
  console.log(data)
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.min.js"></script></code>```

You can also call another function: the data will be passed as the first argument. Here is a demo:

d3.json("https://api.npoint.io/5b22a0474c99d3049d2e", callback)

function callback(data) {
  console.log(data)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.min.js"></script></code>```

What does d3.json return? (v5 or higher)

In D3 v5, d3.json (as well as d3.csv, d3.tsv etc) returns a promise:

var data = d3.json("https://api.npoint.io/5b22a0474c99d3049d2e");

console.log(data)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v5.min.js"></script></code>```

Check it in your browser's console, not the Stack snippet console.

ContentLicense: CC BY-SA 4.0

Body:
I'm using d3.json to load a JSON file containing my data, like this:

var data = d3.json(url, callback)

If I do a console.log(data) I can see that data is neither empty nor null. However, it doesn't seem to contain my data array, but something else instead.

What am I doing wrong here?

Note: this is a self-answered question, trying to provide a "canonical" Q&A on a subject that has been touched on by many previous questions and not (clearly) explained by the API. The answer below was written as a general guidance to those questions.

Body:
TL;DR

d3.json (as well as d3.csv, d3.tsv etc) does not return the content of the loaded/parsed file. Instead of that, it returns an object related to the request in D3 v4 or lower, and a promise in D3 v5 or higher.

What does d3.json return? (v4 or lower)

d3.json is one of the alternatives to XMLHttpRequest provided by D3. According to the API, d3.json...

Returns a new request to get the JSON file at the specified url with the default mime type application/json.

... which, we can agree, is not particularly clear. Because of that, you probably thought that you could return the loaded data using var data = d3.json(url, callback), but that's incorrect. What d3.json returns is an object (not an array), associated with the request. Let's see it.

I have this JSON in a file:

{"foo": "42"}

What happens if we use d3.json the way you used it in your question? Click "run code snippet" to see:

var data = d3.json("https://api.npoint.io/5b22a0474c99d3049d2e", function() {});

console.log(data)

<script src="https://d3js.org/d3.v4.min.js"></script>

As you can see in the console, we have an object like this:

{header: ƒ, mimeType: ƒ, responseType: ƒ, timeout: ƒ, user: ƒ, …}

Well, this is not our data array.

The same thing happens if you use a function:

function getData() {
  return d3.json("https://api.npoint.io/5b22a0474c99d3049d2e", function() {})
}

var data = getData()

console.log(data)

<script src="https://d3js.org/d3.v4.min.js"></script>

Also, it's worth mentioning that the same thing happens with d3.csv, d3.tsv and the other request methods:

var data = d3.csv("https://www.ibm.com/support/knowledgecenter/SVU13_7.2.1/com.ibm.ismsaas.doc/reference/AssetsImportCompleteSample.csv", function() {});

console.log(data)

<script src="https://d3js.org/d3.v4.min.js"></script>

How to use d3.json?

The correct way to load the data with d3.json, as you can see in several online examples, is using its callback:

d3.json(url, function(data){
    //use data here...
});

And here is the snippet with our JSON file:

d3.json("https://api.npoint.io/5b22a0474c99d3049d2e", function(data) {
  console.log(data)
})

<script src="https://d3js.org/d3.v4.min.js"></script>

You can also call another function: the data will be passed as the first argument. Here is a demo:

d3.json("https://api.npoint.io/5b22a0474c99d3049d2e", callback)

function callback(data) {
  console.log(data)
}

<script src="https://d3js.org/d3.v4.min.js"></script>

What does d3.json return? (v5 or higher)

In D3 v5, d3.json (as well as d3.csv, d3.tsv etc) returns a promise:

var data = d3.json("https://api.npoint.io/5b22a0474c99d3049d2e");

console.log(data)

<script src="https://d3js.org/d3.v5.min.js"></script>

Check it in your browser's console, not the Stack snippet console.


来源: stackexchange

问:
"curl: (8) Weird server reply" from kubernetes
I am trying to consume Python Rest API call from a container running inside the Kubernetes.
I am able to consume the service inside the pod

```<code>*curl http://localhost:5002/analyst_rating -v
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 5002 (#0)
> GET /analyst_rating HTTP/1.1
> Host: localhost:5002
> User-Agent: curl/7.47.0
> Accept: */*
>
* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK
< Content-Type: application/json
< Content-Length: 37
< Server: Werkzeug/0.12.2 Python/2.7.12
< Date: Tue, 05 Dec 2017 17:02:00 GMT
<
{
  "Analyst Rating": "Hello World"
* Closing connection 0*
</code>```

When I am running the curl command from outside the cluster, I am getting the below error:

```<code>    curl -I http://184.173.44.62:30484/analyst_rating -v
*   Trying 184.173.44.62...
* TCP_NODELAY set
* Connected to 184.173.44.62 (184.173.44.62) port 30484 (#0)
> HEAD /analyst_rating HTTP/1.1
> Host: 184.173.44.62:30484
> User-Agent: curl/7.54.0
> Accept: */*
>
* Closing connection 0
curl: (8) Weird server reply
</code>```

My Cluster IP is 184.173.44.62 and my service node port is 30484.
I am able to make connections but not able to receive any response.
Also, I have checked inside the pod, I am not getting any GET request.

Also, Following is my deployment info:

```<code>kubectl describe deployment
Name:                   sunlife-analystrating-deployment
Namespace:              default
CreationTimestamp:      Tue, 05 Dec 2017 10:53:53 -0500
Labels:                 app=sunlife-analystrating-deployment
Annotations:            deployment.kubernetes.io/revision=1
Selector:               app=sunlife-analystrating-deployment
Replicas:               1 desired | 1 updated | 1 total | 1 available | 0 unavailable
StrategyType:           RollingUpdate
MinReadySeconds:        0
RollingUpdateStrategy:  1 max unavailable, 1 max surge
Pod Template:
  Labels:  app=sunlife-analystrating-deployment
  Containers:
   sunlife-analystrating-deployment:
    Image:        registry.ng.bluemix.net/dockerservice/tensorflowrunningimage:02
    Port:         5002/TCP
    Environment:  <none>
    Mounts:       <none>
  Volumes:        <none>
Conditions:
  Type           Status  Reason
  ----           ------  ------
  Available      True    MinimumReplicasAvailable
OldReplicaSets:  <none>
NewReplicaSet:   sunlife-analystrating-deployment-3230069030 (1/1 replicas created)
Events:          <none>
</code>```

and Following is my Service info:

```<code>kubectl describe service
Name:              kubernetes
Namespace:         default
Labels:            component=apiserver
                   provider=kubernetes
Annotations:       <none>
Selector:          <none>
Type:              ClusterIP
IP:                172.21.0.1
Port:              https  443/TCP
TargetPort:        32444/TCP
Endpoints:         184.173.44.62:32444
Session Affinity:  ClientIP
Events:            <none>

Name:                     sunlife-analystrating-svc
Namespace:                default
Labels:                   <none>
Annotations:              <none>
Selector:                 app=sunlife-analystrating-deployment
Type:                     NodePort
IP:                       172.21.210.178
Port:                     <unset>  5002/TCP
TargetPort:               5002/TCP
NodePort:                 <unset>  30484/TCP
Endpoints:                172.30.111.147:5002
Session Affinity:         None
External Traffic Policy:  Cluster
Events:                   <none>
</code>```

Following is the code snippet, that I have used to expose the rest client inside container

```<code>-------
def get(self):
        print("Hello World")
        response="Hello World"
        result_dict = { 'Analyst Rating': str(response) }
        return jsonify(result_dict)
-------
if __name__ == '__main__':
     app.run(port='5002')
-------
</code>```

答:
You can't get any GET request because it seems that you use POST method

```<code>*curl -I -X  POST http://184.173.44.62:30484/analyst_rating -v
</code>```

Also, why do you use -I parameter? Try to execute:

```<code>curl http://184.173.44.62:30484/analyst_rating -v
</code>```

If this doesn't work, you'll have to provide more details about your k8s service specification

ContentLicense: CC BY-SA 3.0

Body:
I am trying to consume Python Rest API call from a container running inside the Kubernetes.
I am able to consume the service inside the pod

*curl http://localhost:5002/analyst_rating -v
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 5002 (#0)
> GET /analyst_rating HTTP/1.1
> Host: localhost:5002
> User-Agent: curl/7.47.0
> Accept: */*
>
* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK
< Content-Type: application/json
< Content-Length: 37
< Server: Werkzeug/0.12.2 Python/2.7.12
< Date: Tue, 05 Dec 2017 17:02:00 GMT
<
{
  "Analyst Rating": "Hello World"
* Closing connection 0*

When I am running the curl command from outside the cluster, I am getting the below error:

    curl -I http://184.173.44.62:30484/analyst_rating -v
*   Trying 184.173.44.62...
* TCP_NODELAY set
* Connected to 184.173.44.62 (184.173.44.62) port 30484 (#0)
> HEAD /analyst_rating HTTP/1.1
> Host: 184.173.44.62:30484
> User-Agent: curl/7.54.0
> Accept: */*
>
* Closing connection 0
curl: (8) Weird server reply

My Cluster IP is 184.173.44.62 and my service node port is 30484.
I am able to make connections but not able to receive any response.
Also, I have checked inside the pod, I am not getting any GET request.

Also, Following is my deployment info:

kubectl describe deployment
Name:                   sunlife-analystrating-deployment
Namespace:              default
CreationTimestamp:      Tue, 05 Dec 2017 10:53:53 -0500
Labels:                 app=sunlife-analystrating-deployment
Annotations:            deployment.kubernetes.io/revision=1
Selector:               app=sunlife-analystrating-deployment
Replicas:               1 desired | 1 updated | 1 total | 1 available | 0 unavailable
StrategyType:           RollingUpdate
MinReadySeconds:        0
RollingUpdateStrategy:  1 max unavailable, 1 max surge
Pod Template:
  Labels:  app=sunlife-analystrating-deployment
  Containers:
   sunlife-analystrating-deployment:
    Image:        registry.ng.bluemix.net/dockerservice/tensorflowrunningimage:02
    Port:         5002/TCP
    Environment:  <none>
    Mounts:       <none>
  Volumes:        <none>
Conditions:
  Type           Status  Reason
  ----           ------  ------
  Available      True    MinimumReplicasAvailable
OldReplicaSets:  <none>
NewReplicaSet:   sunlife-analystrating-deployment-3230069030 (1/1 replicas created)
Events:          <none>

and Following is my Service info:

kubectl describe service
Name:              kubernetes
Namespace:         default
Labels:            component=apiserver
                   provider=kubernetes
Annotations:       <none>
Selector:          <none>
Type:              ClusterIP
IP:                172.21.0.1
Port:              https  443/TCP
TargetPort:        32444/TCP
Endpoints:         184.173.44.62:32444
Session Affinity:  ClientIP
Events:            <none>

Name:                     sunlife-analystrating-svc
Namespace:                default
Labels:                   <none>
Annotations:              <none>
Selector:                 app=sunlife-analystrating-deployment
Type:                     NodePort
IP:                       172.21.210.178
Port:                     <unset>  5002/TCP
TargetPort:               5002/TCP
NodePort:                 <unset>  30484/TCP
Endpoints:                172.30.111.147:5002
Session Affinity:         None
External Traffic Policy:  Cluster
Events:                   <none>

Following is the code snippet, that I have used to expose the rest client inside container

-------
def get(self):
        print("Hello World")
        response="Hello World"
        result_dict = { 'Analyst Rating': str(response) }
        return jsonify(result_dict)
-------
if __name__ == '__main__':
     app.run(port='5002')
-------

Body:
You can't get any GET request because it seems that you use POST method

*curl -I -X  POST http://184.173.44.62:30484/analyst_rating -v

Also, why do you use -I parameter? Try to execute:

curl http://184.173.44.62:30484/analyst_rating -v

If this doesn't work, you'll have to provide more details about your k8s service specification


问:
How to pass varargs into a method as an expanded list?
Given the following Flash method:

```<code>function sendToJava(name:String, ... args)
{
  ExternalInterface.call("sendCommand", name, args);
}
</code>```

How do I ensure that ExternalInterface.call() interprets args in its expanded form? Right now, if I pass a list into "args", that list gets interpreted as a single argument of type "Object[]" by ExternalInterface.call(). When the arguments reach Java, I have no way of differentiating between multiple arguments separated by commas versus a single argument containing commas as part of its value.

答:
One small typo.  It should be:

```<code>function sendToJava(name:String, ... args)
{
  // See Array.unshift()
  args.unshift("sendCommand", name);

  // See Function.apply()
  ExternalInterface.call.apply(null, args);
}
</code>```

Just change "array" to "apply"

Anyways, thanks a ton for posting this.  You're a lifesaver!

OwnerDisplayName: Gili

ContentLicense: CC BY-SA 2.5

Body:
Given the following Flash method:

function sendToJava(name:String, ... args)
{
  ExternalInterface.call("sendCommand", name, args);
}

How do I ensure that ExternalInterface.call() interprets args in its expanded form? Right now, if I pass a list into "args", that list gets interpreted as a single argument of type "Object[]" by ExternalInterface.call(). When the arguments reach Java, I have no way of differentiating between multiple arguments separated by commas versus a single argument containing commas as part of its value.

Body:
One small typo.  It should be:

function sendToJava(name:String, ... args)
{
  // See Array.unshift()
  args.unshift("sendCommand", name);

  // See Function.apply()
  ExternalInterface.call.apply(null, args);
}

Just change "array" to "apply"

Anyways, thanks a ton for posting this.  You're a lifesaver!

OwnerDisplayName: Micah


问:
How do I programmatically scroll a winforms datagridview control?
I'm implementing some drag drop features in one my controls inheriting from a datagridview. Basically I'm dragging a row from somewhere in the DGV and dropping it somewhere else, reordering the rows. I've run into a problem though. If the DGV is too large such that there's a scrollbar, how can I have the DGV scroll up or down while the user is in the middle of a dragdrop?

I know how to get the current mouse position and also get the position of the dgv rectangle and such. So, I can easily find out if i'm in the top or bottom half of the rectangle... I just need a way to programmatically scroll the dgv. I'd prefer if I don't have to keep changing the selected cell to do this.

Any suggestions?

Thanks

Isaac

答:
you can do this by setting HorizontalScrollingOffset / VerticalScrollingOffset of the DataGridView

to set HorizontalScrollingOffset

```<code>dataGridView1.HorizontalScrollingOffset = dataGridView1.HorizontalScrollingOffset + 10;
</code>```

check

DataGridView.HorizontalScrollingOffset Property

and

for VerticalScrollingOffset you can use Reflection

include namespace System.Reflection

```<code>PropertyInfo verticalOffset = dataGridView1.GetType().GetProperty("VerticalOffset", BindingFlags.NonPublic | BindingFlags.Instance);
            verticalOffset.SetValue(this.dataGridView1, 10, null);
</code>```

Body:
you can do this by setting HorizontalScrollingOffset / VerticalScrollingOffset of the DataGridView

to set HorizontalScrollingOffset

dataGridView1.HorizontalScrollingOffset = dataGridView1.HorizontalScrollingOffset + 10;

check

DataGridView.HorizontalScrollingOffset Property

and

for VerticalScrollingOffset you can use Reflection

include namespace System.Reflection

PropertyInfo verticalOffset = dataGridView1.GetType().GetProperty("VerticalOffset", BindingFlags.NonPublic | BindingFlags.Instance);
            verticalOffset.SetValue(this.dataGridView1, 10, null);


问:
JSON parsing - Memory Dependent?
I'm trying to pass very large arrays to JavaScipt to be manipulated client-side, and it's not working. These arrays typically have about 12,000 elements each, and this snippet of code is functioning correctly when I only plug in 2,000 elements.

```<code>    <script type="text/javascript">

        var getLenders = JSON.parse('<?php echo json_encode($getlenders); ?>');
        var discountArray = JSON.parse('<?php echo json_encode($discountArray); ?>');
        var getData = JSON.parse('<?php echo json_encode($sortedArray); ?>');

    </script>
</code>```

I increased the memory requirements of the server to 512MB (4 time as much as before) thinking that'd be more than enough, however it is still not working. Before I crank up the memory to 1024MB, I would like to know if there is any other reason this is not working. Could it be an issue with client-side memory?

Any input is appreciated.

答:
I'm sure this not good idea truly, Because you can't know you client has enough memory to run your page or not and this page freeze the browser or crash it.

first you can optimize this code to:

```<code>    var getLenders = <?php $a =  json_encode($getlenders);  echo $a == null? '{}': $a; ?> ;
    var discountArray = <?php $b =  json_encode($discountArray); echo $b == null? '{}': $b;  ?>;
    var getData = <?php $c = json_encode($sortedArray); echo $c == null? '{}': $c; ?>;
</code>```

because json based on JavaScript and not need convert to string and parse again.

Second but I have one idea: get only needed value with ajax when you need them.

Title: JSON parsing - Memory Dependent?

Body:
I'm trying to pass very large arrays to JavaScipt to be manipulated client-side, and it's not working. These arrays typically have about 12,000 elements each, and this snippet of code is functioning correctly when I only plug in 2,000 elements.

I increased the memory requirements of the server to 512MB (4 time as much as before) thinking that'd be more than enough, however it is still not working. Before I crank up the memory to 1024MB, I would like to know if there is any other reason this is not working. Could it be an issue with client-side memory?

Any input is appreciated.

Body:
I'm sure this not good idea truly, Because you can't know you client has enough memory to run your page or not and this page freeze the browser or crash it.

first you can optimize this code to:

    var getLenders = <?php $a =  json_encode($getlenders);  echo $a == null? '{}': $a; ?> ;
    var discountArray = <?php $b =  json_encode($discountArray); echo $b == null? '{}': $b;  ?>;
    var getData = <?php $c = json_encode($sortedArray); echo $c == null? '{}': $c; ?>;

because json based on JavaScript and not need convert to string and parse again.

Second but I have one idea: get only needed value with ajax when you need them.


问:
Cannon find module. Electron
got a problem which made me stuck for 3 hours. I'm started learning Electron framework.

Everything worked good before i installed independence : ElectronViewRenderer.

This is error : Cannot find module '../js/index.js'

My folder structure: http://puu.sh/yAbnR/1acdb39aa7.png

My Index.ejs (view) :

```<code>    <!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
    <link href="asset://../node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
  </head>

  <body>

    <nav class="navbar navbar-inverse">
      <div class="container-fluid">
        <div class="navbar-header">
          <a id="home" class="navbar-brand" href="#">WebSiteName</a>
        </div>
        <ul class="nav navbar-nav">
          <li class="active" id="home"><a href="#">Home</a></li>
          <li id="page1"><a href="#">Page 1</a></li>
          <li id="page2"><a href="#">Page 2</a></li>
        </ul>
        <ul class="nav navbar-nav navbar-right">
          <li id="register"><a href="#"><span class="glyphicon glyphicon-user"></span> Sign Up</a></li>
          <li><a href="#"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
        </ul>
      </div>
    </nav>

    Test

    <script>
      require('../js/index.js');
      window.$ = window.jQuery = require('jquery');
    </script>
  </body>
</html>
</code>```

Packager.json :

```<code>{
  "name": "electron-quick-start",
  "version": "1.0.0",
  "description": "A minimal Electron application",
  "main": "main.js",
  "scripts": {
    "start": "electron ."
  },
  "repository": "https://github.com/electron/electron-quick-start",
  "keywords": [
    "Electron",
    "quick",
    "start",
    "tutorial",
    "demo"
  ],
  "author": "GitHub",
  "license": "CC0-1.0",
  "devDependencies": {
    "electron": "1.7.9"
  },
  "dependencies": {
    "bootstrap": "^3.3.7",
    "electron-view-renderer": "^1.2.4",
    "jquery": "^3.2.1"
  }
}
</code>```

答: Your trying to require the index.js file from index.js?</p>

Title: Cannon find module. Electron

Body:
got a problem which made me stuck for 3 hours. I'm started learning Electron framework.

Everything worked good before i installed independence : ElectronViewRenderer.

This is error : Cannot find module '../js/index.js'

My folder structure: http://puu.sh/yAbnR/1acdb39aa7.png

My Index.ejs (view) :

    <!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Hello World!</title>
    <link href="asset://../node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

          WebSiteName

Home

Page 1

Page 2

 Sign Up

 Login

    Test

Packager.json :

{
  "name": "electron-quick-start",
  "version": "1.0.0",
  "description": "A minimal Electron application",
  "main": "main.js",
  "scripts": {
    "start": "electron ."
  },
  "repository": "https://github.com/electron/electron-quick-start",
  "keywords": [
    "Electron",
    "quick",
    "start",
    "tutorial",
    "demo"
  ],
  "author": "GitHub",
  "license": "CC0-1.0",
  "devDependencies": {
    "electron": "1.7.9"
  },
  "dependencies": {
    "bootstrap": "^3.3.7",
    "electron-view-renderer": "^1.2.4",
    "jquery": "^3.2.1"
  }
}


问:
Running tests in single Python file with nose
I'm using nose 1.3.7 with Anaconda 4.1.1 (Python 3.5.2). I want to run unit tests in a single file, e.g. foo.py. According to the documentation I should be able to simply run:

```<code>nosetests foo.py
</code>```

But when I do this, nose runs all the tests in all the files in the directory!

And if I do nose --help, the usage documentation doesn't even indicate that there is a  parameter. It only shows [options].

So can I run tests in a single file using nose?

答: Be also sure you don't have nose.run() or nose.main() inside the file to be tested.

Body:
I'm using nose 1.3.7 with Anaconda 4.1.1 (Python 3.5.2). I want to run unit tests in a single file, e.g. foo.py. According to the documentation I should be able to simply run:

nosetests foo.py

But when I do this, nose runs all the tests in all the files in the directory!

And if I do nose --help, the usage documentation doesn't even indicate that there is a  parameter. It only shows [options].

So can I run tests in a single file using nose?


问:
Making save to SD card and Context Menu functions dynamic, or relative to button pressed
Relative to the below code, how do I make

```<code>if (savering(R.raw.sound1)){
</code>```

and

```<code>String filename=”sound1″+”.ogg”;
</code>```

and

```<code>values.put(MediaStore.MediaColumns.TITLE, “sound1″);
</code>```

dynamic instead of static so that the sound file that will be saved is based on the button pressed?

My sound files are in a soundArray saved as sound1, sound2, sound3, etc. There is a button for each sound file. Click to play, long click brings up the below context menu.

Any help or hints would be greatly appreciated.

```<code>//CONTEXT MENU

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
     super.onCreateContextMenu(menu, v, menuInfo);
     menu.setHeaderTitle("Save as...");
     menu.add(0, v.getId(), 0, "Ringtone");
     menu.add(0, v.getId(), 0, "Notification");
    }
    @Override
    public boolean onContextItemSelected(MenuItem item) {
     if(item.getTitle()=="Ringtone"){function1(item.getItemId());}
      else if(item.getTitle()=="Notification"){function2(item.getItemId());}
      else {return false;}
     return true;
    }

    public void function1(int id){
     if
     (savering(R.raw.sound1)){
      // Code if successful
      Toast.makeText(this, "Saved as Ringtone", Toast.LENGTH_SHORT).show();
     }
     else
     {
      // Code if unsuccessful
      Toast.makeText(this, "Failed - Check your SDCard", Toast.LENGTH_SHORT).show();
     }

    }
    public void function2(int id){
     if
     (savenot(R.raw.sound1)){
      // Code if successful
      Toast.makeText(this, "Saved as Notification", Toast.LENGTH_SHORT).show();
     }
     else
     {
      // Code if unsuccessful
      Toast.makeText(this, "Failed - Check your SDCard", Toast.LENGTH_SHORT).show();
     }
    }

//Save into Ring tone Folder

    public boolean savering(int ressound){
     byte[] buffer=null;
     InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
     int size=0;

     try {
       size = fIn.available();
       buffer = new byte[size];
       fIn.read(buffer);
       fIn.close();
     } catch (IOException e) {
      // TODO Auto-generated catch block
      return false;      }

     String path="/sdcard/media/audio/ringtones/";
     String filename="sound1"+".ogg";

     boolean exists = (new File(path)).exists();
     if (!exists){new File(path).mkdirs();}

     FileOutputStream save;
     try {
      save = new FileOutputStream(path+filename);
      save.write(buffer);
      save.flush();
      save.close();
     } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      return false;
     } catch (IOException e) {
      // TODO Auto-generated catch block
      return false;
     }
     sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename)));

     File k = new File(path, filename);
     ContentValues values = new ContentValues();
     values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
     values.put(MediaStore.MediaColumns.TITLE, "sound1 Ringtone");
     values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
     values.put(MediaStore.Audio.Media.ARTIST, "cssounds ");
     values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
     values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
     values.put(MediaStore.Audio.Media.IS_ALARM, true);
     values.put(MediaStore.Audio.Media.IS_MUSIC, false);

     //Insert it into the database
     this.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values);

     return true;
    }

//Save in Notification Folder

    public boolean savenot(int ressound){
     byte[] buffer=null;
     InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
     int size=0;

     try {
       size = fIn.available();
       buffer = new byte[size];
       fIn.read(buffer);
       fIn.close();
     } catch (IOException e) {
      // TODO Auto-generated catch block
      return false;      }

     String path="/sdcard/media/audio/notifications/";
     String filename="sound1"+".ogg";

     boolean exists = (new File(path)).exists();
     if (!exists){new File(path).mkdirs();}

     FileOutputStream save;
     try {
      save = new FileOutputStream(path+filename);
      save.write(buffer);
      save.flush();
      save.close();
     } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      return false;
     } catch (IOException e) {
      // TODO Auto-generated catch block
      return false;
     }
     sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename)));

     File k = new File(path, filename);
     ContentValues values = new ContentValues();
     values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
     values.put(MediaStore.MediaColumns.TITLE, "sound1 Notification");
     values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
     values.put(MediaStore.Audio.Media.ARTIST, "cssounds ");
     values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
     values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
     values.put(MediaStore.Audio.Media.IS_ALARM, true);
     values.put(MediaStore.Audio.Media.IS_MUSIC, false);

     //Insert it into the database
     this.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values);

     return true;
    }
</code>```

答:
I think you can got solution by using following changes:

1: take two arrays. one for storing your ringbuttons ids which you are adding to menu to play and another array respectively with corresponding sound array id for that button's sound;

For example,

```<code>int btnid=new int[count];//count is no of buttons for playing ring
int rawid=ne int[count];
</code>```

Then you can catch the id of button of clicked menuitem and from that you have to compare in function1 with your btnid array and get the index of array of btnid matched.

2: than after with same index you can find rawsource in rawid array.

Your first problem is solved, now for that second prob of filename you just try this:

```<code>String filename="sound"+id+".ogg";//id is index of array
</code>```

Body:
Relative to the below code, how do I make

if (savering(R.raw.sound1)){

and

String filename=”sound1″+”.ogg”;

and

values.put(MediaStore.MediaColumns.TITLE, “sound1″);

dynamic instead of static so that the sound file that will be saved is based on the button pressed?

My sound files are in a soundArray saved as sound1, sound2, sound3, etc. There is a button for each sound file. Click to play, long click brings up the below context menu.

Any help or hints would be greatly appreciated.

//CONTEXT MENU

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
     super.onCreateContextMenu(menu, v, menuInfo);
     menu.setHeaderTitle("Save as...");
     menu.add(0, v.getId(), 0, "Ringtone");
     menu.add(0, v.getId(), 0, "Notification");
    }
    @Override
    public boolean onContextItemSelected(MenuItem item) {
     if(item.getTitle()=="Ringtone"){function1(item.getItemId());}
      else if(item.getTitle()=="Notification"){function2(item.getItemId());}
      else {return false;}
     return true;
    }

    public void function1(int id){
     if
     (savering(R.raw.sound1)){
      // Code if successful
      Toast.makeText(this, "Saved as Ringtone", Toast.LENGTH_SHORT).show();
     }
     else
     {
      // Code if unsuccessful
      Toast.makeText(this, "Failed - Check your SDCard", Toast.LENGTH_SHORT).show();
     }

    }
    public void function2(int id){
     if
     (savenot(R.raw.sound1)){
      // Code if successful
      Toast.makeText(this, "Saved as Notification", Toast.LENGTH_SHORT).show();
     }
     else
     {
      // Code if unsuccessful
      Toast.makeText(this, "Failed - Check your SDCard", Toast.LENGTH_SHORT).show();
     }
    }

//Save into Ring tone Folder

    public boolean savering(int ressound){
     byte[] buffer=null;
     InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
     int size=0;

     try {
       size = fIn.available();
       buffer = new byte[size];
       fIn.read(buffer);
       fIn.close();
     } catch (IOException e) {
      // TODO Auto-generated catch block
      return false;      }

     String path="/sdcard/media/audio/ringtones/";
     String filename="sound1"+".ogg";

     boolean exists = (new File(path)).exists();
     if (!exists){new File(path).mkdirs();}

     FileOutputStream save;
     try {
      save = new FileOutputStream(path+filename);
      save.write(buffer);
      save.flush();
      save.close();
     } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      return false;
     } catch (IOException e) {
      // TODO Auto-generated catch block
      return false;
     }
     sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename)));

     File k = new File(path, filename);
     ContentValues values = new ContentValues();
     values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
     values.put(MediaStore.MediaColumns.TITLE, "sound1 Ringtone");
     values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
     values.put(MediaStore.Audio.Media.ARTIST, "cssounds ");
     values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
     values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
     values.put(MediaStore.Audio.Media.IS_ALARM, true);
     values.put(MediaStore.Audio.Media.IS_MUSIC, false);

     //Insert it into the database
     this.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values);

     return true;
    }

//Save in Notification Folder

    public boolean savenot(int ressound){
     byte[] buffer=null;
     InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
     int size=0;

     try {
       size = fIn.available();
       buffer = new byte[size];
       fIn.read(buffer);
       fIn.close();
     } catch (IOException e) {
      // TODO Auto-generated catch block
      return false;      }

     String path="/sdcard/media/audio/notifications/";
     String filename="sound1"+".ogg";

     boolean exists = (new File(path)).exists();
     if (!exists){new File(path).mkdirs();}

     FileOutputStream save;
     try {
      save = new FileOutputStream(path+filename);
      save.write(buffer);
      save.flush();
      save.close();
     } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      return false;
     } catch (IOException e) {
      // TODO Auto-generated catch block
      return false;
     }
     sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename)));

     File k = new File(path, filename);
     ContentValues values = new ContentValues();
     values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
     values.put(MediaStore.MediaColumns.TITLE, "sound1 Notification");
     values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
     values.put(MediaStore.Audio.Media.ARTIST, "cssounds ");
     values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
     values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
     values.put(MediaStore.Audio.Media.IS_ALARM, true);
     values.put(MediaStore.Audio.Media.IS_MUSIC, false);

     //Insert it into the database
     this.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values);

     return true;
    }

Body:
I think you can got solution by using following changes:

1: take two arrays. one for storing your ringbuttons ids which you are adding to menu to play and another array respectively with corresponding sound array id for that button's sound;

For example,

int btnid=new int[count];//count is no of buttons for playing ring
int rawid=ne int[count];

Then you can catch the id of button of clicked menuitem and from that you have to compare in function1 with your btnid array and get the index of array of btnid matched.

2: than after with same index you can find rawsource in rawid array.

Your first problem is solved, now for that second prob of filename you just try this:

String filename="sound"+id+".ogg";//id is index of array


问:
Select Values from one Table and adding it to another table while having Same PK
I have two tables
Table 1 Schema:

```<code>Table1:: Product_Report Column:: PId, PReportName, PReportSize
</code>```

And Second Table Schema:

```<code>Table2:: Product Column:: PId, PName, PSize, PCategory
</code>```

In both table PId is PrimaryKey. I want to add PReportCategory as new column in Product_Report (Table1) in that value of PReportCategory is selected from PCategory of Product (Table2)

Something like:

```<code> INSERT into Product_Report (PReportCategory) VALUES Select PCategory from Product where (I guess here need help)
</code>```

If I am right to path I am following then I guess in where condition I need help if not then please help me to construct query

Thank You

答:
Q: "I want to add PReportCategory as new column in Product_Report"

```<code>ALTER TABLE Product_Report
  ADD PReportCategory BIGINT DEFAULT NULL COMMENT 'ref Product.PCategory'
</code>```

(Use an appropriate datataype in place of BIGINT, I added that as a placeholder datatype for the column.)

Q: "... value of PReportCategory is selected from PCategory of Product"

```<code>UPDATE Product_Report t
  JOIN Product s
    ON s.PId = t.PId
   SET t.PReportCategory = s.PCategory
</code>```

This would leave NULL values for PReportCategory in rows in Product_Report that don't have a matching row found in Product.

It's not at all clear what problem this is attempting to solve, i.e. why it's necessary to add this column and populate it. But this example of MySQL syntax demonstrates how we would 1) add a column to a table and 2) populate that column from values in rows in another table, matched based on the values of PId

Body:
I have two tables
Table 1 Schema:

Table1:: Product_Report Column:: PId, PReportName, PReportSize

And Second Table Schema:

Table2:: Product Column:: PId, PName, PSize, PCategory

In both table PId is PrimaryKey. I want to add PReportCategory as new column in Product_Report (Table1) in that value of PReportCategory is selected from PCategory of Product (Table2)

Something like:

 INSERT into Product_Report (PReportCategory) VALUES Select PCategory from Product where (I guess here need help)

If I am right to path I am following then I guess in where condition I need help if not then please help me to construct query

Thank You

Body:
Q: "I want to add PReportCategory as new column in Product_Report"

ALTER TABLE Product_Report
  ADD PReportCategory BIGINT DEFAULT NULL COMMENT 'ref Product.PCategory'

(Use an appropriate datataype in place of BIGINT, I added that as a placeholder datatype for the column.)

Q: "... value of PReportCategory is selected from PCategory of Product"

UPDATE Product_Report t
  JOIN Product s
    ON s.PId = t.PId
   SET t.PReportCategory = s.PCategory

This would leave NULL values for PReportCategory in rows in Product_Report that don't have a matching row found in Product.

It's not at all clear what problem this is attempting to solve, i.e. why it's necessary to add this column and populate it. But this example of MySQL syntax demonstrates how we would 1) add a column to a table and 2) populate that column from values in rows in another table, matched based on the values of PId


问:
MySql: Inser Into ... Select ... Where return #1054 error
I have two tables with a column both containing the same data.

The first table is called "countries" and has the following structure:

```<code>ID -> primary key;
name_countries;
code_countries;
code_city;
name_city;
longitude_city;
latitude_city.
</code>```

The second table is called "ar_geozone" and has the following structure:

```<code>country;
code_city;
name_city;
longitude;
latitude.
</code>```

I would like to copy all data from "ar_geozone" to "countries", for those rows where there is a match between "ar_geozone.country" and "countries.code_countries".

But when I use this SQL string,

```<code>INSERT INTO countries (code_city, name_city, longitude_city, latitude_city)
SELECT code_city, name_city, longitude, latitude FROM ar_geozone
WHERE ar_geozone.country LIKE countries.code_countries
</code>```

the system returns the error: # 1054 - Unknown column 'countries.code_countries' in 'where clause'.

答:
Use an Update instead of Insert

From what I have understood, you already have code_countries populated in the table and you have to fill code_city, name_city, longitude_city, latitude_city columns.
Instead of insert try to use an update

"UPDATE countries ct SET code_city = (SELECT code_city FROM ar_geozone ag WHERE ag.country LIKE ct.code_countries)"

Similarily you can write for other columns.

=======

Body:
I have two tables with a column both containing the same data.

The first table is called "countries" and has the following structure:

ID -> primary key;
name_countries;
code_countries;
code_city;
name_city;
longitude_city;
latitude_city.

The second table is called "ar_geozone" and has the following structure:

country;
code_city;
name_city;
longitude;
latitude.

I would like to copy all data from "ar_geozone" to "countries", for those rows where there is a match between "ar_geozone.country" and "countries.code_countries".

But when I use this SQL string,

INSERT INTO countries (code_city, name_city, longitude_city, latitude_city)
SELECT code_city, name_city, longitude, latitude FROM ar_geozone
WHERE ar_geozone.country LIKE countries.code_countries

the system returns the error: # 1054 - Unknown column 'countries.code_countries' in 'where clause'.


问:
phantomjs cookie "expires" vs "expiry"
In phantom JS cookies have two properties.

http://phantomjs.org/api/webpage/property/cookies.html

"expires" and "expiry"

I don't understand why it has two properties instead of one.

Can I just use the "expiry" timestamp and ignore the "expires"?

答:
According to the 'add-cookie' documentation it's only documented to add expires as a numeric.

```<code>phantom.addCookie({
  'name'     : 'Valid-Cookie-Name',   /* required property */
  'value'    : 'Valid-Cookie-Value',  /* required property */
  'domain'   : 'localhost',
  'path'     : '/foo',                /* required property */
  'httponly' : true,
  'secure'   : false,
  'expires'  : (new Date()).getTime() + (1000 * 60 * 60)   /* <-- expires in 1 hour */
});
</code>```

It's not clear what is intended in the example in the cookies documentation however, as there are approximately two years between expires: 'Sat Oct 11 2014 21:44:33 GMT+0200 (CEST)' and expiry: 1476128618 which is Monday 10th October 2016 07:43:38 PM.

Title: phantomjs cookie "expires" vs "expiry"

Body:
According to the 'add-cookie' documentation it's only documented to add expires as a numeric.

phantom.addCookie({
  'name'     : 'Valid-Cookie-Name',   /* required property */
  'value'    : 'Valid-Cookie-Value',  /* required property */
  'domain'   : 'localhost',
  'path'     : '/foo',                /* required property */
  'httponly' : true,
  'secure'   : false,
  'expires'  : (new Date()).getTime() + (1000 * 60 * 60)   /* <-- expires in 1 hour */
});

It's not clear what is intended in the example in the cookies documentation however, as there are approximately two years between expires: 'Sat Oct 11 2014 21:44:33 GMT+0200 (CEST)' and expiry: 1476128618 which is Monday 10th October 2016 07:43:38 PM.


问:
Where can I download the latest version of VSLangProj150
I'm looking for the current version of VSLangProj150.dll but I can't seem to find it anywhere.

I have this version, VSLangProj150.15.0.26228 retrieved from nuget but I believe this is an old version because: 1) it was published on 4/13/2017 and 2) it only contains a single interface called PackageReferences which is empty and a VsProjReferencesPropId150 enum with only two values.

Today, I've installed VS 2017 v15.5 and included the Visual Studio SDK component, but I can't seem to find the dll anywhere on my system.

It appears that there is a new version because I've seen references on the web that refers to VSProject4 and Reference6 which are defined in VSLangProj150. And I've found this reference in NuGet.Clients that reads:
AsVsProject4.PackageRefereences?.InstalledPackages

Or am I missing something?

答:
Found it! Must manually get it from nuget.org using VSLangProj150 Version 1.0.0 or as I did, I just added the following:

<package id="VSLangProj150" version="1.0.0" targetFramework="net46" />

to my packages.config file and then let VS 2017 automatically restore any of my missing packages!


问:
Exporting results from powershell into a CSV document not working
I wrote a script in Powershell that will pull all files in a directory from the past seven years (this is my first time using Powershell).

I am trying to Export my results from the script below into a TXT or CSV document.

```<code>get-childitem -Path P:\ -recurse | where-object {$_.LastWriteTime -lt (getdate).Addyears(-7)}
</code>```

What should I add to the end of this script to get this data written to a file?

答:
First things first, your script is finding files older than 7 years not files from the last 7 years. You need to change your -lt to a -gt.

```<code>get-childitem -Path P:\ -recurse| where-object {$_.LastWriteTime -gt (get-date).Addyears(-7)}
</code>```

As you have written your script it finds the date/time that the file was last written to, for example 3/24/2015 2:45PM. Then it checks if that is less than right now minus 7 years (at the time of writing that is 12/5/2010 3:22PM). Looking at the years alone we can see that 2015 is not less than 2010, so that file would be excluded.

You can output to a text file using the Out-File or (my preference) Set-Content cmdlets.

```<code>get-childitem -Path P:\ -recurse| where-object {$_.LastWriteTime -gt (get-date).Addyears(-7)} | Set-Content C:\Path\To\File.txt
</code>```

Alternatively if you want to capture the data as well, or display it on screen, you can use the Tee-Object cmdlet.

```<code>get-childitem -Path P:\ -recurse| where-object {$_.LastWriteTime -gt (get-date).Addyears(-7)} | Tee-Object -FilePath C:\Path\To\File.txt
</code>```

If you would like a CSV file you use the Export-Csv cmdlet. When using this cmdlet it is very common to use the -NoTypeInformation parameter (shortened to -NoType in my example) to avoid getting a first line that specifies the object types that it output.

```<code>get-childitem -Path P:\ -recurse| where-object {$_.LastWriteTime -gt (get-date).Addyears(-7)} | Export-Csv C:\Path\To\File.csv -NoType
</code>```

Body:
I wrote a script in Powershell that will pull all files in a directory from the past seven years (this is my first time using Powershell).

I am trying to Export my results from the script below into a TXT or CSV document.

get-childitem -Path P:\ -recurse | where-object {$_.LastWriteTime -lt (getdate).Addyears(-7)}

What should I add to the end of this script to get this data written to a file?

Body:
First things first, your script is finding files older than 7 years not files from the last 7 years. You need to change your -lt to a -gt.

get-childitem -Path P:\ -recurse| where-object {$_.LastWriteTime -gt (get-date).Addyears(-7)}

As you have written your script it finds the date/time that the file was last written to, for example 3/24/2015 2:45PM. Then it checks if that is less than right now minus 7 years (at the time of writing that is 12/5/2010 3:22PM). Looking at the years alone we can see that 2015 is not less than 2010, so that file would be excluded.

You can output to a text file using the Out-File or (my preference) Set-Content cmdlets.

get-childitem -Path P:\ -recurse| where-object {$_.LastWriteTime -gt (get-date).Addyears(-7)} | Set-Content C:\Path\To\File.txt

Alternatively if you want to capture the data as well, or display it on screen, you can use the Tee-Object cmdlet.

get-childitem -Path P:\ -recurse| where-object {$_.LastWriteTime -gt (get-date).Addyears(-7)} | Tee-Object -FilePath C:\Path\To\File.txt

If you would like a CSV file you use the Export-Csv cmdlet. When using this cmdlet it is very common to use the -NoTypeInformation parameter (shortened to -NoType in my example) to avoid getting a first line that specifies the object types that it output.

get-childitem -Path P:\ -recurse| where-object {$_.LastWriteTime -gt (get-date).Addyears(-7)} | Export-Csv C:\Path\To\File.csv -NoType


问:
How to set text to value of listview items after time intervals
I am developing an android app where a user will input text to an EditText, then it will be added to a ListView.

But once a button with onClick value "start" is clicked, it will display each item of the ListView in a TextView with id displayText, in the order of each item and it will loop(Repeat) once it is exhausted.

Here is my Code

Math.java

```<code>public class Math extends AppCompatActivity {

private ArrayList<String> items;
private ArrayAdapter<String> itemsAdapter;
private ListView lvItems;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_math);

    lvItems = (ListView) findViewById(R.id.lvItems);
    items = new ArrayList<String>();
    itemsAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, items);
    lvItems.setAdapter(itemsAdapter);
}

public void AddItem(View v) {
    EditText etNewItem = (EditText) findViewById(R.id.etNewItem);
    String itemText = etNewItem.getText().toString();
    itemsAdapter.add(itemText);
    etNewItem.setText("");
}
public void start(View v){
    RelativeLayout lc = (RelativeLayout)findViewById(R.id.contentContainer);
    lc.setVisibility(View.GONE);
    RelativeLayout tc = (RelativeLayout)findViewById(R.id.tvContainer);
    tc.setVisibility(View.VISIBLE);
}
}
</code>```

activity_math.xml

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Math">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/tvContainer"
    android:visibility="gone">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textSize="30sp"
        android:id="@+id/displayText"/>

</RelativeLayout>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/contentContainer">

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/lvItems"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_above="@+id/btnAddItem" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/etNewItem"
        android:layout_alignTop="@+id/btnAddItem"
        android:hint="Enter a new item"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_toLeftOf="@+id/btnAddItem"
        android:layout_toStartOf="@+id/btnAddItem"
        android:layout_alignParentBottom="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add Item"
        android:id="@+id/btnAddItem"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:onClick="AddItem"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start"
        android:layout_alignParentBottom="true"
        android:layout_toLeftOf="@id/btnAddItem"
        android:onClick="start"/>

</RelativeLayout>
</code>```

答:
Okay, i think the issue is that you haven't given the TextView any thing to display. you have to convert the arrayList to a String array and use setText to display the Value.
add this part to the "start" method

```<code>String ls =System.getProperty("line.separator");// i used this to seperate the array items
           String joint = TextUtils.join(ls, lvitems);
            result.setText(joint);
</code>```

That should work

Body:
I am developing an android app where a user will input text to an EditText, then it will be added to a ListView.

But once a button with onClick value "start" is clicked, it will display each item of the ListView in a TextView with id displayText, in the order of each item and it will loop(Repeat) once it is exhausted.

Here is my Code

Math.java

public class Math extends AppCompatActivity {

private ArrayList<String> items;
private ArrayAdapter<String> itemsAdapter;
private ListView lvItems;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_math);

    lvItems = (ListView) findViewById(R.id.lvItems);
    items = new ArrayList<String>();
    itemsAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, items);
    lvItems.setAdapter(itemsAdapter);
}

public void AddItem(View v) {
    EditText etNewItem = (EditText) findViewById(R.id.etNewItem);
    String itemText = etNewItem.getText().toString();
    itemsAdapter.add(itemText);
    etNewItem.setText("");
}
public void start(View v){
    RelativeLayout lc = (RelativeLayout)findViewById(R.id.contentContainer);
    lc.setVisibility(View.GONE);
    RelativeLayout tc = (RelativeLayout)findViewById(R.id.tvContainer);
    tc.setVisibility(View.VISIBLE);
}
}

activity_math.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Math">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/tvContainer"
    android:visibility="gone">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textSize="30sp"
        android:id="@+id/displayText"/>

</RelativeLayout>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/contentContainer">

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/lvItems"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_above="@+id/btnAddItem" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/etNewItem"
        android:layout_alignTop="@+id/btnAddItem"
        android:hint="Enter a new item"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_toLeftOf="@+id/btnAddItem"
        android:layout_toStartOf="@+id/btnAddItem"
        android:layout_alignParentBottom="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add Item"
        android:id="@+id/btnAddItem"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:onClick="AddItem"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start"
        android:layout_alignParentBottom="true"
        android:layout_toLeftOf="@id/btnAddItem"
        android:onClick="start"/>

</RelativeLayout>

Body:
Okay, i think the issue is that you haven't given the TextView any thing to display. you have to convert the arrayList to a String array and use setText to display the Value.
add this part to the "start" method

String ls =System.getProperty("line.separator");// i used this to seperate the array items
           String joint = TextUtils.join(ls, lvitems);
            result.setText(joint);

That should work


问:
Undefined behaviour in RE2 which stated to be well defined
Recently I've found that the RE2 library uses this technique for fast set lookups. During the lookup it uses values from uninitialized array, which, as far as I know, is undefined behaviour.

I've even found this issue with valgrind warnings about use of uninitialized memory. But the issue was closed with a comment that this behaviour is indended.

I suppose that in reality an uninitialized array will just contain some random data on all modern compilers and architectures. But on the other hand I treat the 'undefined behaviour' statement as 'literally anything can happen' (including your program formats your hard drive or Godzilla comes and destroys your city).

The question is: is it legal to use uninitialized data in C++?

答:
When C was originally designed, if arr was an array of some type T occupying N bytes, an expression like arr[i] meant "take the base address of arr, add i*N to it, fetch N bytes at the resulting address, and interpret them as a T".  If every possible combination of N bytes would have a meaning when interpreted as a type T, fetching an uninitialized array element may yield an arbitrary value, but the behavior would otherwise be predictable.  If T is a 32-bit type, an attempt to read an uninitialized array element of type T would yield one of at most 4294967296 possible behaviors; such action would be safe if and only if every one of those 4294967296 behaviors would meet a program's requirements.  As you note, there are situations where such a guarantee is useful.

The C Standard, however, describes a semantically-weaker language which does not guarantee that an attempt to read an uninitialized array element will behave in a fashion consistent with any bit pattern the storage might have contain.  Compiler writers want to process this weaker language, rather than the one Dennis Ritchie invented, because it allows them to apply a number of optimizations without regard for how they interact.  For example, if code performs a=x; and later performs b=a; and c=a;, and if a compiler can't "see" anything between the original assignment and the later ones that could change a or x, it could omit the first assignment and change the latter two assignments to b=x; and c=x;.  If, however, something happens between the latter two assignments that would change x, that could result in b and c getting different values--something that should be impossible if nothing changes a.

Applying that optimization by itself wouldn't be a problem if nothing changed x that shouldn't.  On the other hand, consider code which uses some allocated storage as type float, frees it, re-allocates it, and uses it as type int.  If the compiler knows that the original and replacement request are of the same size, it could recycle the storage without freeing and reallocating it.  That could, however, cause the code sequence:

```<code>float *fp = malloc(4);
...
*fp = slowCalculation();
somethingElse = *fp;
free(fp);
int *ip = malloc(4);
...
a=*ip;
b=a;
...
c=a;
</code>```

to get rewritten as:

```<code>float *fp = malloc(4);
...
startSlowCalculation(); // Use some pipelined computation unit
int *ip = (int*)fp;
...
b=*ip;

*fp = resultOfSlowCalculation();  // ** Moved from up above
somethingElse = *fp;

...
c=*ip;
</code>```

It would be rare for performance to benefit particularly from processing the result of the slow calculation between the writes to b and c.  Unfortunately, compilers aren't designed in a way that would make it convenient to guarantee that a deferred calculation wouldn't by chance land in exactly the spot where it would cause trouble.

Personally, I regard compiler writers' philosophy as severely misguided: if a programmer in a certain situation knows that a guarantee would be useful, requiring the programmer to work around the lack of it will impose significant cost with 100% certainty.  By contrast, a requirement that compiler refrain from optimizations that are predicated on the lack of that guarantee would rarely cost anything (since code to work around its absence would almost certainly block the "optimization" anyway).  Unfortunately, some people seem more interested in optimizing the performance of those source texts which don't need guarantees beyond what the Standard mandates, than in optimizing the efficiency with which a compiler can generate code to accomplish useful tasks.

Body:
When C was originally designed, if arr was an array of some type T occupying N bytes, an expression like arr[i] meant "take the base address of arr, add i*N to it, fetch N bytes at the resulting address, and interpret them as a T".  If every possible combination of N bytes would have a meaning when interpreted as a type T, fetching an uninitialized array element may yield an arbitrary value, but the behavior would otherwise be predictable.  If T is a 32-bit type, an attempt to read an uninitialized array element of type T would yield one of at most 4294967296 possible behaviors; such action would be safe if and only if every one of those 4294967296 behaviors would meet a program's requirements.  As you note, there are situations where such a guarantee is useful.

The C Standard, however, describes a semantically-weaker language which does not guarantee that an attempt to read an uninitialized array element will behave in a fashion consistent with any bit pattern the storage might have contain.  Compiler writers want to process this weaker language, rather than the one Dennis Ritchie invented, because it allows them to apply a number of optimizations without regard for how they interact.  For example, if code performs a=x; and later performs b=a; and c=a;, and if a compiler can't "see" anything between the original assignment and the later ones that could change a or x, it could omit the first assignment and change the latter two assignments to b=x; and c=x;.  If, however, something happens between the latter two assignments that would change x, that could result in b and c getting different values--something that should be impossible if nothing changes a.

Applying that optimization by itself wouldn't be a problem if nothing changed x that shouldn't.  On the other hand, consider code which uses some allocated storage as type float, frees it, re-allocates it, and uses it as type int.  If the compiler knows that the original and replacement request are of the same size, it could recycle the storage without freeing and reallocating it.  That could, however, cause the code sequence:

float *fp = malloc(4);
...
*fp = slowCalculation();
somethingElse = *fp;
free(fp);
int *ip = malloc(4);
...
a=*ip;
b=a;
...
c=a;

to get rewritten as:

float *fp = malloc(4);
...
startSlowCalculation(); // Use some pipelined computation unit
int *ip = (int*)fp;
...
b=*ip;

*fp = resultOfSlowCalculation();  // ** Moved from up above
somethingElse = *fp;

...
c=*ip;

It would be rare for performance to benefit particularly from processing the result of the slow calculation between the writes to b and c.  Unfortunately, compilers aren't designed in a way that would make it convenient to guarantee that a deferred calculation wouldn't by chance land in exactly the spot where it would cause trouble.

Personally, I regard compiler writers' philosophy as severely misguided: if a programmer in a certain situation knows that a guarantee would be useful, requiring the programmer to work around the lack of it will impose significant cost with 100% certainty.  By contrast, a requirement that compiler refrain from optimizations that are predicated on the lack of that guarantee would rarely cost anything (since code to work around its absence would almost certainly block the "optimization" anyway).  Unfortunately, some people seem more interested in optimizing the performance of those source texts which don't need guarantees beyond what the Standard mandates, than in optimizing the efficiency with which a compiler can generate code to accomplish useful tasks.


问:
How to resolve Duplicate Symbol Error?
I'm compiling 2 C++ files together. 4 if you include the header files. The problem is, I keep getting "Duplicate Symbol" errors when the linker tries to link the files together.

Here are my files.

main.h

```<code>int test2();
</code>```

main.cc

```<code>#include "main.h"
#include "test.h"

int test2(int test) {
    return 0;
}

int main() {

    test2(test());
    return 0;
}
</code>```

test.h

```<code>int hello = 10;
int test();
</code>```

test.cc

```<code>#include <iostream>
#include "test.h"
using namespace std;

int test() {
  cout << hello << endl;
  return 0;
}
</code>```

I think I'm doing something simple wrong. Can someone please point out what I'm doing wrong.
Here's how I'm compiling the files.

```<code>c++ main.cc test.cc -o main
</code>```

Here's the error I get:

duplicate symbol _hello in:
/var/folders/nj/568_95bj4dg9v11l_mksv_2m0000gn/T/main-3becdd.o
/var/folders/nj/568_95bj4dg9v11l_mksv_2m0000gn/T/test-e84473.o
ld: 1 duplicate symbol for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
```

答:
You can simply define hello as a "static" (global) variable

```<code>static int hello = 10;
</code>```

More information is mentioned in a similar question:

Duplicate symbols while linking

Title: How to resolve Duplicate Symbol Error?

Body:
I'm compiling 2 C++ files together. 4 if you include the header files. The problem is, I keep getting "Duplicate Symbol" errors when the linker tries to link the files together.

Here are my files.

main.h

int test2();

main.cc

#include "main.h"
#include "test.h"

int test2(int test) {
    return 0;
}

int main() {

    test2(test());
    return 0;
}

test.h

int hello = 10;
int test();

test.cc

#include <iostream>
#include "test.h"
using namespace std;

int test() {
  cout << hello << endl;
  return 0;
}

I think I'm doing something simple wrong. Can someone please point out what I'm doing wrong.
Here's how I'm compiling the files.

c++ main.cc test.cc -o main

Here's the error I get:

duplicate symbol _hello in:
/var/folders/nj/568_95bj4dg9v11l_mksv_2m0000gn/T/main-3becdd.o
/var/folders/nj/568_95bj4dg9v11l_mksv_2m0000gn/T/test-e84473.o
ld: 1 duplicate symbol for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Body:
You can simply define hello as a "static" (global) variable

static int hello = 10;

More information is mentioned in a similar question:

Duplicate symbols while linking


问:
Win32, C++: Sending email in Windows 10 by invoking default mail client
There are number of posts in Stackoverflow as well as many other websites which show how to send an email with an attachment by invoking the default mail client. Pretty much the same when you right click on any file in Windows Explorer and from the context menu choosing Send to->Mail recipient.

Lot of these samples I found online use MAPI, but none of them work. There are also examples that use ShellExecute and use the mailto: protocol. The latter works for me but not when I try to send an attachment. The attachment simply does not show up in Outlook's New Mail window. The MAPI examples once again don't work with attachments. I get weird errors like whether I would like to allow or deny.

If Windows is able to do it, that means other apps should be able to do it too. Does anyone know which API to use that works for Windows 10?

答:
Here's the code that works. It's mixed with Qt stuff, but Qt classes are later converted to STL in the code. The reason that my code was not working previously was because I was setting lpszPathName to the path of the attachment and lpszFileName to the filename of the attachment. Path has to be set to the full path including the filename, and filename should be set to whatever we want to be displayed as the name of the attachment in the email client. It may be just the filename, it may be something else.</p>

```<code>bool InvokeDefaultEmailClient(HWND hwndParent, const QStringList
                             &attachmentFilenames, const QString &subject)
{
    HINSTANCE hInst = LoadLibraryW(L"mapi32.dll");
    if (!hInst) {
        return false;
    }

    ULONG(PASCAL *SendMail)(ULONG, ULONG_PTR, MapiMessageW*, FLAGS, ULONG);
    (FARPROC&)SendMail = GetProcAddress(hInst, "MAPISendMailW");

    if (!SendMail) {
        return false;
    }

    std::vector<std::wstring> attachmentFilenamesVector;
    for(int i=0; i<attachmentFilenames.size(); ++i) {
        QString filename = attachmentFilenames[i];
        attachmentFilenamesVector.push_back(filename.toStdWString());
    }

    QVector<MapiFileDescW> fileDescs;
    for (int i = 0; i < attachmentFilenamesVector.size(); ++i) {
        MapiFileDescW fileDesc;
        ZeroMemory(&fileDesc, sizeof(fileDesc));
        fileDesc.nPosition = (ULONG)-1;
        fileDesc.lpszPathName = (TCHAR*)attachmentFilenamesVector[i].c_str();
        fileDesc.lpszFileName = (TCHAR*)attachmentFilenamesVector[i].c_str();
        fileDescs.push_back(fileDesc);
    }

    MapiMessageW message;
    ZeroMemory(&message, sizeof(message));
    message.lpszSubject = (TCHAR*)subject.toStdString().c_str();
    message.nFileCount = fileDescs.size();
    message.lpFiles = fileDescs.data();

    int error = SendMail(0, (ULONG_PTR)hwndParent, &message, MAPI_LOGON_UI | MAPI_DIALOG, 0);

    if (error != SUCCESS_SUCCESS && error != MAPI_USER_ABORT && error != MAPI_E_LOGIN_FAILURE) {
        return false;
    }

    return true;
}
</code>```

Body:
Here's the code that works. It's mixed with Qt stuff, but Qt classes are later converted to STL in the code. The reason that my code was not working previously was because I was setting lpszPathName to the path of the attachment and lpszFileName to the filename of the attachment. Path has to be set to the full path including the filename, and filename should be set to whatever we want to be displayed as the name of the attachment in the email client. It may be just the filename, it may be something else.

bool InvokeDefaultEmailClient(HWND hwndParent, const QStringList
                             &attachmentFilenames, const QString &subject)
{
    HINSTANCE hInst = LoadLibraryW(L"mapi32.dll");
    if (!hInst) {
        return false;
    }

    ULONG(PASCAL *SendMail)(ULONG, ULONG_PTR, MapiMessageW*, FLAGS, ULONG);
    (FARPROC&)SendMail = GetProcAddress(hInst, "MAPISendMailW");

    if (!SendMail) {
        return false;
    }

    std::vector<std::wstring> attachmentFilenamesVector;
    for(int i=0; i<attachmentFilenames.size(); ++i) {
        QString filename = attachmentFilenames[i];
        attachmentFilenamesVector.push_back(filename.toStdWString());
    }

    QVector<MapiFileDescW> fileDescs;
    for (int i = 0; i < attachmentFilenamesVector.size(); ++i) {
        MapiFileDescW fileDesc;
        ZeroMemory(&fileDesc, sizeof(fileDesc));
        fileDesc.nPosition = (ULONG)-1;
        fileDesc.lpszPathName = (TCHAR*)attachmentFilenamesVector[i].c_str();
        fileDesc.lpszFileName = (TCHAR*)attachmentFilenamesVector[i].c_str();
        fileDescs.push_back(fileDesc);
    }

    MapiMessageW message;
    ZeroMemory(&message, sizeof(message));
    message.lpszSubject = (TCHAR*)subject.toStdString().c_str();
    message.nFileCount = fileDescs.size();
    message.lpFiles = fileDescs.data();

    int error = SendMail(0, (ULONG_PTR)hwndParent, &message, MAPI_LOGON_UI | MAPI_DIALOG, 0);

    if (error != SUCCESS_SUCCESS && error != MAPI_USER_ABORT && error != MAPI_E_LOGIN_FAILURE) {
        return false;
    }

    return true;
}


问:
flexible css button no images
need your brains!!

i am hoping to make a button with no images, as with CSS3, that will scale based on the verbiage in the button. I have tried a few things but I am unable to get anything to work.

For Example:
the button has a minimum width of say 95px

and that's great for HOME or ABOUT US
but if i have copy that is like
Dallas City Council Team

It would be great if the button would get wider.

Can anyone help me with this? pretty please? I've driven myself insane!!!

Thank you so much in advance!!!

答: I don't completely understand your question, but if you want to make a button class scale depending on the text in the button, you shouldn't give it any width and just style it with padding</p>

Title: flexible css button no images


问:
Save data and close Tkinter window at the same time
So I am trying to get data from the user and then I want the gui window to close, and save the data into variables for my code right after they click "Enter". But the window just stays there. How do I get it to save the data, and the gui window to close at the same time?</p>

```<code>#pop up window
def show_entry_fields():
   global ModelNumber,PowerOutput,SerialNumber

   ModelNumber=e1.get()
   PowerOutput=e2.get()
   SerialNumber=e3.get()

master = Tk()
master.title("Model Information")

master.geometry("500x300")

master.iconbitmap("square.ico")

Label(master, text="Model Information").grid(row=0,column=1)
Label(master, text="Model Number ").grid(row=2)
Label(master, text="Power Output (w)").grid(row=3)
Label(master,text="Serial Number").grid(row=4)

e1 = Entry(master)
e2 = Entry(master)
e3 = Entry(master)

e1.grid(row=2, column=1)
e2.grid(row=3, column=1)
e3.grid(row=4, column=1)

Button(master, text='Enter', command=show_entry_fields).grid(row=6,
column=1, sticky=W, pady=4)

mainloop()
master.withdraw()
</code>```

答:
This is what I ended up doing.
It does what the show_entry_fields function has inside (which is saving the data as global variables), and it gets ride of the GUI window right after I press "enter"</p>

```<code>   Button(master, text='Enter',  command=lambda: [f() for f in [show_entry_fields, master.quit]]).grid(row=6, column=1, sticky=W, pady=4)
</code>```

Body:
So I am trying to get data from the user and then I want the gui window to close, and save the data into variables for my code right after they click "Enter". But the window just stays there. How do I get it to save the data, and the gui window to close at the same time?

#pop up window
def show_entry_fields():
   global ModelNumber,PowerOutput,SerialNumber

   ModelNumber=e1.get()
   PowerOutput=e2.get()
   SerialNumber=e3.get()

master = Tk()
master.title("Model Information")

master.geometry("500x300")

master.iconbitmap("square.ico")

Label(master, text="Model Information").grid(row=0,column=1)
Label(master, text="Model Number ").grid(row=2)
Label(master, text="Power Output (w)").grid(row=3)
Label(master,text="Serial Number").grid(row=4)

e1 = Entry(master)
e2 = Entry(master)
e3 = Entry(master)

e1.grid(row=2, column=1)
e2.grid(row=3, column=1)
e3.grid(row=4, column=1)

Button(master, text='Enter', command=show_entry_fields).grid(row=6,
column=1, sticky=W, pady=4)

mainloop()
master.withdraw()

Body:
This is what I ended up doing.
It does what the show_entry_fields function has inside (which is saving the data as global variables), and it gets ride of the GUI window right after I press "enter"

   Button(master, text='Enter',  command=lambda: [f() for f in [show_entry_fields, master.quit]]).grid(row=6, column=1, sticky=W, pady=4)


问:
Convert Long And Lat to X Y coordinate using ArcGis Api For Javascript
Hello i'm trying to convert long,lat values to X,Y using ArcGis Api For Javascript

```<code> var i = esri.geometry.lngLatToXY(3.13, 36.742)
 console.log(i); //returns Array [ 348541.32567373366, 4403205.668961807 ]
</code>```

in what system does this conversion take place?
is there a method to specify the projection system?

note: the conversion is done from decimal degree to meters

i followed this :
https://developers.arcgis.com/javascript/3/jsapi/esri.geometry.webmercatorutils-amd.html

答:
This method is used to convert geographic coordinate system longitude/latitude (wkid 4326) to projected coordinate system Web Mercator (wkid 102100).

Default esri map use Web Mercator as projection system. If you need to convert your coordinates to an other coordinate system you need to use the project method of GeometryService :
https://developers.arcgis.com/javascript/3/jsapi/geometryservice-amd.html

Example:

```<code>require(["esri/geometry/Point", "esri/tasks/GeometryService", "esri/tasks/ProjectParameters", "esri/SpatialReference", "dojo/domReady!"],
  function(Point, GeometryService, ProjectParameters, SpatialReference) {

    var outSR = "YOUR_OUTPUT_COORDINATE_SYSTEM"; // `wkid {number}`
    var geometryService = new GeometryService("https://utility.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer");
    var inputpoint = new Point({
      longitude: "YOUR_LONGITUDE_INPUT",
      latitude: "YOUR_LATITUDE_INPUT"
    });

    var projectParams = new ProjectParameters();
    projectParams.geometries = [inputpoint];
    projectParams.outSR = new SpatialReference({ wkid: outSR });

    geometryService.project(projectParams, (result) => {
      let outputpoint = result[0]; // outputpoint first element of result array
      console.log("Result x:", outputpoint.x, "y :", outputpoint.y);
    });
  });
</code>```

Wkid numbers can be found here:

projected coordinate system: http://resources.arcgis.com/en/help/arcgis-rest-api/index.html#/Projected_coordinate_systems/02r3000000vt000000/

Geographic coordinate system: http://resources.arcgis.com/en/help/arcgis-rest-api/index.html#/Geographic_coordinate_systems/02r300000105000000/

EDIT

Here is a working example: Plunker

Body:
Hello i'm trying to convert long,lat values to X,Y using ArcGis Api For Javascript

 var i = esri.geometry.lngLatToXY(3.13, 36.742)
 console.log(i); //returns Array [ 348541.32567373366, 4403205.668961807 ]

in what system does this conversion take place?
is there a method to specify the projection system?

note: the conversion is done from decimal degree to meters

i followed this :
https://developers.arcgis.com/javascript/3/jsapi/esri.geometry.webmercatorutils-amd.html

Body:
This method is used to convert geographic coordinate system longitude/latitude (wkid 4326) to projected coordinate system Web Mercator (wkid 102100).

Default esri map use Web Mercator as projection system. If you need to convert your coordinates to an other coordinate system you need to use the project method of GeometryService :
https://developers.arcgis.com/javascript/3/jsapi/geometryservice-amd.html

Example:

require(["esri/geometry/Point", "esri/tasks/GeometryService", "esri/tasks/ProjectParameters", "esri/SpatialReference", "dojo/domReady!"],
  function(Point, GeometryService, ProjectParameters, SpatialReference) {

    var outSR = "YOUR_OUTPUT_COORDINATE_SYSTEM"; // `wkid {number}`
    var geometryService = new GeometryService("https://utility.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer");
    var inputpoint = new Point({
      longitude: "YOUR_LONGITUDE_INPUT",
      latitude: "YOUR_LATITUDE_INPUT"
    });

    var projectParams = new ProjectParameters();
    projectParams.geometries = [inputpoint];
    projectParams.outSR = new SpatialReference({ wkid: outSR });

    geometryService.project(projectParams, (result) => {
      let outputpoint = result[0]; // outputpoint first element of result array
      console.log("Result x:", outputpoint.x, "y :", outputpoint.y);
    });
  });

Wkid numbers can be found here:

projected coordinate system: http://resources.arcgis.com/en/help/arcgis-rest-api/index.html#/Projected_coordinate_systems/02r3000000vt000000/

Geographic coordinate system: http://resources.arcgis.com/en/help/arcgis-rest-api/index.html#/Geographic_coordinate_systems/02r300000105000000/

EDIT

Here is a working example: Plunker


问:
Pygame ship movement only Up & Down (left right is working)

This part is gamefunction.py file

```<code>import sys

import pygame

def check_keydown_events(event,ship):
    """Respond to the keypressess."""
    if event.key == pygame.K_RIGHT:
        ship.moving_right = True
    elif event.key == pygame.K_LEFT:
        ship.moving_left = True
    elif event.key == pygame.K_UP:
        ship.moving_up = True
    elif event.key == pygame.K_DOWN:
        ship.moving_down = True

def check_keyup_events(event, ship):
    """Respond to the keyreleases."""
    if event.key == pygame.K_RIGHT:
        ship.moving_right = False
    elif event.key == pygame.K_LEFT:
        ship.moving_left = False
    elif event.key == pygame.K_UP:
        ship.moving_up = False
    elif event.key == pygame.K_DOWN:
        ship.moving_down = False

def check_events(ship):
    """Respond to keypresses and mouse events."""
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

        elif event.type == pygame.KEYDOWN:
            check_keydown_events(event,ship)
        elif event.type == pygame.KEYUP:
            check_keyup_events(event, ship)
</code>```

this is named ship.py

```<code>import pygame

class Ship():

    def __init__(self,ai_settings,screen):
        """Initialize the ship and set its starting position."""
        self.screen = screen
        self.ai_settings = ai_settings
        #Load the ship image and get its rect.
        self.image = pygame.image.load('images/ship.png')
        self.rect = self.image.get_rect()
        self.screen_rect = screen.get_rect()

        #Start each new ship at the bottom center of the screen.
        self.rect.centerx = self.screen_rect.centerx
        self.rect.bottom = self.screen_rect.bottom

        #Store a decimal value for the ship's center.
        self.center = float(self.rect.centerx)
        #Movement Flags
        self.moving_right = False
        self.moving_left = False
        self.moving_up = False
        self.moving_down = False

    def update(self):
        """Update the ship's position based on the movement flag."""
        #Update the ship's center value, not the rect
        if self.moving_right and self.rect.right<self.screen_rect.right:
            self.center += self.ai_settings.ship_speed_factor
        if self.moving_left and self.rect.left>0:
            self.center -= self.ai_settings.ship_speed_factor
        #Up-dwon motion added ***Please check the logic for 1200x800 screen***
        if self.moving_up and self.rect.top<self.screen_rect.top:
            self.center += self.ai_settings.ship_speed_factor
        if self.moving_down and self.rect.bottom>800:
            self.center -= self.ai_settings.ship_speed_factor

        #Update rect object from self.center.
        self.rect.centerx = self.center
</code>```

答:
Source: Python Crash Course

Just a few tweeks in ship.py:

Under self.center = float(self.rect.centerx), add self.bottom = float(self.rect.bottom) and change:

```<code>if self.moving_up and self.rect.top<self.screen_rect.top:
    self.center += self.ai_settings.ship_speed_factor
if self.moving_down and self.rect.bottom>800:
    self.center -= self.ai_settings.ship_speed_factor
</code>```

to:

```<code>if self.moving_up and self.rect.top<self.screen_rect.top:
    self.bottom -= self.ai_settings.ship_speed_factor
if self.moving_down and self.rect.bottom<800:
    self.bottom += self.ai_settings.ship_speed_factor
</code>```

and finally under self.rect.centerx = self.center, add self.rect.bottom = self.bottom.

This should make you be able to go up and down in your game!

Body:
This part is gamefunction.py file

import sys

import pygame

def check_keydown_events(event,ship):
    """Respond to the keypressess."""
    if event.key == pygame.K_RIGHT:
        ship.moving_right = True
    elif event.key == pygame.K_LEFT:
        ship.moving_left = True
    elif event.key == pygame.K_UP:
        ship.moving_up = True
    elif event.key == pygame.K_DOWN:
        ship.moving_down = True

def check_keyup_events(event, ship):
    """Respond to the keyreleases."""
    if event.key == pygame.K_RIGHT:
        ship.moving_right = False
    elif event.key == pygame.K_LEFT:
        ship.moving_left = False
    elif event.key == pygame.K_UP:
        ship.moving_up = False
    elif event.key == pygame.K_DOWN:
        ship.moving_down = False

def check_events(ship):
    """Respond to keypresses and mouse events."""
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

        elif event.type == pygame.KEYDOWN:
            check_keydown_events(event,ship)
        elif event.type == pygame.KEYUP:
            check_keyup_events(event, ship)

this is named ship.py

import pygame

class Ship():

    def __init__(self,ai_settings,screen):
        """Initialize the ship and set its starting position."""
        self.screen = screen
        self.ai_settings = ai_settings
        #Load the ship image and get its rect.
        self.image = pygame.image.load('images/ship.png')
        self.rect = self.image.get_rect()
        self.screen_rect = screen.get_rect()

        #Start each new ship at the bottom center of the screen.
        self.rect.centerx = self.screen_rect.centerx
        self.rect.bottom = self.screen_rect.bottom

        #Store a decimal value for the ship's center.
        self.center = float(self.rect.centerx)
        #Movement Flags
        self.moving_right = False
        self.moving_left = False
        self.moving_up = False
        self.moving_down = False

    def update(self):
        """Update the ship's position based on the movement flag."""
        #Update the ship's center value, not the rect
        if self.moving_right and self.rect.right<self.screen_rect.right:
            self.center += self.ai_settings.ship_speed_factor
        if self.moving_left and self.rect.left>0:
            self.center -= self.ai_settings.ship_speed_factor
        #Up-dwon motion added ***Please check the logic for 1200x800 screen***
        if self.moving_up and self.rect.top<self.screen_rect.top:
            self.center += self.ai_settings.ship_speed_factor
        if self.moving_down and self.rect.bottom>800:
            self.center -= self.ai_settings.ship_speed_factor

        #Update rect object from self.center.
        self.rect.centerx = self.center

Body:
Source: Python Crash Course

Just a few tweeks in ship.py:

Under self.center = float(self.rect.centerx), add self.bottom = float(self.rect.bottom) and change:

if self.moving_up and self.rect.top<self.screen_rect.top:
    self.center += self.ai_settings.ship_speed_factor
if self.moving_down and self.rect.bottom>800:
    self.center -= self.ai_settings.ship_speed_factor

to:

if self.moving_up and self.rect.top<self.screen_rect.top:
    self.bottom -= self.ai_settings.ship_speed_factor
if self.moving_down and self.rect.bottom<800:
    self.bottom += self.ai_settings.ship_speed_factor

and finally under self.rect.centerx = self.center, add self.rect.bottom = self.bottom.

This should make you be able to go up and down in your game!


问:
How to split a file by a multi-character delimiter?
On Unix, without adding anything to the OS (i.e. only using grep, awk, sed, cut, etc.), how can I extract the "text" line in only the "codeView" section (and ignore that in the "probableStartLocationView" section)?

```<code>. . .
      "events" : [ {
"id" : "12345",
"important" : true,
"type" : "Creation",
"description" : "Something happened here",
"extraDetails" : null,
"codeView" : {
  "lines" : [ {
    "fragments" : [ {
      "type" : "NORMAL_CODE",
      "value" : "str = wrapper.getParameter("
    }, {
      "type" : "CODE_STRING",
      "value" : ""abcd""
    }, {
      "type" : "NORMAL_CODE",
      "value" : ")"
    } ],
    "text" : "str = wrapper.getParameter("abcd")"
  } ],
  "nested" : false
},
"probableStartLocationView" : {
  "lines" : [ {
    "fragments" : [ {
      "type" : "STACKTRACE_LINE",
      "value" : "<init>() @ JSONInputData.java:72"
    } ],
    "text" : "<init>() @ JSONInputData.java:72"
  } ],
  "nested" : false
},
. . .
</code>```

答:
If you really need to use OS included tools only, you can try something like that:

```<code>JSONString='"codeView" : { "lines" : [ { "fragments" : [ { "type" : "NORMAL_CODE", "value" : "str = wrapper.getParameter(" }, { "type" : "CODE_STRING", "value" : ""abcd"" }, { "type" : "NORMAL_CODE", "value" : ")" } ], "text" : "str = wrapper.getParameter("abcd")" } ], "nested" : false },'

function jsonParse() {
    awk -F"[,:}]" '{for(i=1;i<=NF;i++){if($i~/'$1'\042/){print $(i+1)}}}' | tr -d '"' | sed -n 1p
}

printf "$(echo $JSONString | jsonParse text)"
</code>```

Please note: This is not at all a safe way to do it, as it doesn't parse the JSON. It just extracts the text key.

Demo available here.

However since in your example there are two text keys, this code will only get the first one. If you need any text key after the first one, you have to alter the code above a bit. You need to make sed target the exact line you need. Say you need the second text in the "codeView" block, you would write

```<code>sed -n 2p
</code>```

instead of sed -n 1p.

Demo for the second text key is here.

Body:
On Unix, without adding anything to the OS (i.e. only using grep, awk, sed, cut, etc.), how can I extract the "text" line in only the "codeView" section (and ignore that in the "probableStartLocationView" section)?

. . .
      "events" : [ {
"id" : "12345",
"important" : true,
"type" : "Creation",
"description" : "Something happened here",
"extraDetails" : null,
"codeView" : {
  "lines" : [ {
    "fragments" : [ {
      "type" : "NORMAL_CODE",
      "value" : "str = wrapper.getParameter("
    }, {
      "type" : "CODE_STRING",
      "value" : ""abcd""
    }, {
      "type" : "NORMAL_CODE",
      "value" : ")"
    } ],
    "text" : "str = wrapper.getParameter("abcd")"
  } ],
  "nested" : false
},
"probableStartLocationView" : {
  "lines" : [ {
    "fragments" : [ {
      "type" : "STACKTRACE_LINE",
      "value" : "<init>() @ JSONInputData.java:72"
    } ],
    "text" : "<init>() @ JSONInputData.java:72"
  } ],
  "nested" : false
},
. . .

Body:
If you really need to use OS included tools only, you can try something like that:

JSONString='"codeView" : { "lines" : [ { "fragments" : [ { "type" : "NORMAL_CODE", "value" : "str = wrapper.getParameter(" }, { "type" : "CODE_STRING", "value" : "&quot;abcd&quot;" }, { "type" : "NORMAL_CODE", "value" : ")" } ], "text" : "str = wrapper.getParameter(&quot;abcd&quot;)" } ], "nested" : false },'

function jsonParse() {
    awk -F"[,:}]" '{for(i=1;i<=NF;i++){if($i~/'$1'\042/){print $(i+1)}}}' | tr -d '"' | sed -n 1p
}

printf "$(echo $JSONString | jsonParse text)"

Please note: This is not at all a safe way to do it, as it doesn't parse the JSON. It just extracts the text key.

Demo available here.

However since in your example there are two text keys, this code will only get the first one. If you need any text key after the first one, you have to alter the code above a bit. You need to make sed target the exact line you need. Say you need the second text in the "codeView" block, you would write

sed -n 2p

instead of sed -n 1p.

Demo for the second text key is here.


问:
Attempt by security transparent method to access security critical type failed
I am getting below error in MVC4 application

```<code> Attempt by security transparent method  'Autofac.Integration.Mvc.RegistrationExtensions.RegisterControllers(Autofac.Cont    ainerBuilder, System.Reflection.Assembly[])' to access security critical type 'Autofac.Builder.IRegistrationBuilder`3<System.Object,Autofac.Features.Scanning.ScanningActivatorData,Autofac.Builder.DynamicRegistrationStyle>' failed.

 Assembly 'Autofac.Integration.Mvc, Version=3.0.0.0, Culture=neutral,
 PublicKeyToken=17863af14b0044da' is marked with the
 AllowPartiallyTrustedCallersAttribute, and uses the level 2 security
 transparency model.  Level 2 transparency causes all methods in
 AllowPartiallyTrustedCallers assemblies to become security transparent by
 default, which may be the cause of this exception.
</code>```

I tried different solutions given in below links but none of them work for me
Attempt by security transparent method to access security critical method failed

Attempt by security transparent method xxx to access security critical yy and
https://forums.asp.net/t/1939805.aspx

Please help

答:
I am pretty sure this is the version issue. I installed Autofac.WebApi by mistake, the version of Autofac was automatically 3.x.x. Then the issue came. After that I realized I had to use Autofac.WebApi2 instead of Autofac.WebApi. I installed, Autofac version went up to 4.6.2, then booom the issue was solved.

Hope it helps

Body:
I am getting below error in MVC4 application

 Attempt by security transparent method  'Autofac.Integration.Mvc.RegistrationExtensions.RegisterControllers(Autofac.Cont    ainerBuilder, System.Reflection.Assembly[])' to access security critical type 'Autofac.Builder.IRegistrationBuilder`3<System.Object,Autofac.Features.Scanning.ScanningActivatorData,Autofac.Builder.DynamicRegistrationStyle>' failed.

 Assembly 'Autofac.Integration.Mvc, Version=3.0.0.0, Culture=neutral,
 PublicKeyToken=17863af14b0044da' is marked with the
 AllowPartiallyTrustedCallersAttribute, and uses the level 2 security
 transparency model.  Level 2 transparency causes all methods in
 AllowPartiallyTrustedCallers assemblies to become security transparent by
 default, which may be the cause of this exception.

I tried different solutions given in below links but none of them work for me
Attempt by security transparent method to access security critical method failed

Attempt by security transparent method xxx to access security critical yy and
https://forums.asp.net/t/1939805.aspx

Please help


问:
Create an Interval class with desired format
Im trying to create a class called Interval that if given 1 parameter a, it creates it in the format [a,a], and if given 2 parameters a and b, it creates it in the format [a,b]. See the following code

```<code>class Interval():

   def __init__(self,left,*args):

       if args:
           self.left=left
           self.right=args
       else:
           self.left=left
           self.right=left

   def __repr__(self):
       return("[{},{}]".format(self.left,self.right))
</code>```

Now when i have only one parameter it prints it out in the desired format, but with 2 parameters i get a paranthesis inside the brackets, see below:

```<code>    a = Interval(1)
    b = Interval(2,4)
    print (a)
    print (b)
</code>```

Prints out:

```<code>    [1,1]
    [2,(4,)]
</code>```

Why does this happen? Any help appreciated,  thanks.

答:
'args' is a tuple, that's why you get the paranthesis.</p>

```<code>class Interval():

   def __init__(self,left,*args):

       if args:
           self.left=left
           self.right=args[0]
       else:
           self.left=left
           self.right=left

   def __repr__(self):
       return("[{},{}]".format(self.left,self.right))
</code>```

Body:
Im trying to create a class called Interval that if given 1 parameter a, it creates it in the format [a,a], and if given 2 parameters a and b, it creates it in the format [a,b]. See the following code

class Interval():

   def __init__(self,left,*args):

       if args:
           self.left=left
           self.right=args
       else:
           self.left=left
           self.right=left

   def __repr__(self):
       return("[{},{}]".format(self.left,self.right))

Now when i have only one parameter it prints it out in the desired format, but with 2 parameters i get a paranthesis inside the brackets, see below:

    a = Interval(1)
    b = Interval(2,4)
    print (a)
    print (b)

Prints out:

    [1,1]
    [2,(4,)]

Why does this happen? Any help appreciated,  thanks.

Body:
'args' is a tuple, that's why you get the paranthesis.

class Interval():

   def __init__(self,left,*args):

       if args:
           self.left=left
           self.right=args[0]
       else:
           self.left=left
           self.right=left

   def __repr__(self):
       return("[{},{}]".format(self.left,self.right))