问:
Default Option not selected dropdown in angularjs
I am struggling with dropdown list, Please refer bellow code

My Controller

```<code>(function(angular) {
  'use strict';
angular.module('ngrepeatSelect', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.data = {
     model: null,
     availableOptions: [
       {id: '1', name: 'Option A'},
       {id: '2', name: 'Option B'},
       {id: '3', name: 'Option C'}
     ]
    };

    $scope.data.model=1;

 }]);
})(window.angular);
</code>```

My UI

```<code><body ng-app="ngrepeatSelect">
  <div ng-controller="ExampleController">
  <form name="myForm">
    <label for="repeatSelect"> Repeat select: </label>
    <select name="repeatSelect" id="repeatSelect" ng-model="data.model">
      <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
    </select>
  </form>
  <hr>
  <tt>model = {{data.model}}</tt><br/>
</div>
</body>
</code>```

Here is an demo, In this demo i am setting $scope.data.model as 1 , then why my Dropdown list showing blank ..

I had searched and tried lot, but no luck, Please help.
Thanks in advance, and sorry for my bad English.

Edit Note : I had tried this before, But still facing this issue.

答:
The best practice in angular ng-repeat is using ng-options for select.
In order to make default selection, we need to assign ng-model value in the controller as the option object itself. i.e, the data type of the ng-model and the repeating option must be the same as exact.

Let us assign it as

```<code>$scope.data.model = $scope.data.availableOptions[0];
</code>```

Here is an working example of your question.

(function (angular) {
    'use strict';
    angular.module('ngrepeatSelect', [])
        .controller('ExampleController', ['$scope', function ($scope) {
            $scope.data = {
                model: null,
                availableOptions: [{id: '1', name: 'Option A'},
                    {id: '2',name: 'Option B'},
                    {id: '3',name: 'Option C'}]
            };

            $scope.data.model = $scope.data.availableOptions[0];

    }]);
})(window.angular);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body ng-app="ngrepeatSelect">
    <div ng-controller="ExampleController">
        <form name="myForm">
            <label for="repeatSelect"> Repeat select: </label>
            <select name="repeatSelect" id="repeatSelect" ng-model="data.model" ng-options="option.name for option in data.availableOptions track by option.id">
            </select>
        </form>
        <hr>
        <tt>model = {{data.model}}</tt>
        <br/>
    </div>
</body></code>```

Body:
I am struggling with dropdown list, Please refer bellow code

My Controller

(function(angular) {
  'use strict';
angular.module('ngrepeatSelect', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.data = {
     model: null,
     availableOptions: [
       {id: '1', name: 'Option A'},
       {id: '2', name: 'Option B'},
       {id: '3', name: 'Option C'}
     ]
    };

    $scope.data.model=1;

 }]);
})(window.angular);

My UI

  <form name="myForm">
     Repeat select:
    <select name="repeatSelect" id="repeatSelect" ng-model="data.model">
      <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
    </select>
  </form>

  <tt>model = {{data.model}}</tt>

Here is an demo, In this demo i am setting $scope.data.model as 1 , then why my Dropdown list showing blank ..

I had searched and tried lot, but no luck, Please help.
Thanks in advance, and sorry for my bad English.

Edit Note : I had tried this before, But still facing this issue.

Body:
The best practice in angular ng-repeat is using ng-options for select.
In order to make default selection, we need to assign ng-model value in the controller as the option object itself. i.e, the data type of the ng-model and the repeating option must be the same as exact.

Let us assign it as

$scope.data.model = $scope.data.availableOptions[0];

Here is an working example of your question.

(function (angular) {
    'use strict';
    angular.module('ngrepeatSelect', [])
        .controller('ExampleController', ['$scope', function ($scope) {
            $scope.data = {
                model: null,
                availableOptions: [{id: '1', name: 'Option A'},
                    {id: '2',name: 'Option B'},
                    {id: '3',name: 'Option C'}]
            };

            $scope.data.model = $scope.data.availableOptions[0];

    }]);
})(window.angular);

<body ng-app="ngrepeatSelect">
    <div ng-controller="ExampleController">
        <form name="myForm">
            <label for="repeatSelect"> Repeat select: </label>
            <select name="repeatSelect" id="repeatSelect" ng-model="data.model" ng-options="option.name for option in data.availableOptions track by option.id">
            </select>
        </form>
        <hr>
        <tt>model = {{data.model}}</tt>
        <br/>
    </div>
</body>


来源: stackexchange

问:
can't get value from html tag
I'm trying to retrieve the value inside an html tag. I can retrieve the whole tag but not the value inside.

in app.component.html:

```<code><p #docTitle>the thing I want to extract</p>
</code>```

in app.component.ts

```<code>docTitle;

@ViewChild('docTitle') docTitle;

ngAfterViewInit(){
    console.log(this.docTitle.nativeElement.value); //this gives me the whole tag
}
</code>```

i've tried

```<code><p id="docTitle">what I want to retrieve</p>
</code>```

with

```<code>document.getElementById('docTitle').value //same as above, gives whole tag
</code>```

The point of this whole thing is to retrieve the value (which is translated in different languages with i18n) in order to use it to settle the html page's title.

Thanks for the help.

答:
You could do:</p>

```<code>ngAfterViewInit(){
    console.log(this.docTitle.nativeElement.innerHTML);
    // OR
    console.log(this.docTitle.nativeElement.textContent);
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: can't get value from html tag

Body:
I'm trying to retrieve the value inside an html tag. I can retrieve the whole tag but not the value inside.

in app.component.html:

the thing I want to extract

in app.component.ts

docTitle;

@ViewChild('docTitle') docTitle;

ngAfterViewInit(){
    console.log(this.docTitle.nativeElement.value); //this gives me the whole tag
}

i've tried

what I want to retrieve

with

document.getElementById('docTitle').value //same as above, gives whole tag

The point of this whole thing is to retrieve the value (which is translated in different languages with i18n) in order to use it to settle the html page's title.

Thanks for the help.

Body:
You could do:

ngAfterViewInit(){
    console.log(this.docTitle.nativeElement.innerHTML);
    // OR
    console.log(this.docTitle.nativeElement.textContent);
}


问:
In PHP, why are my session variables persisted as references?
Here's the code. It's a simple operation to check that a session ID isn't being spoofed by verifying the IP address:

```<code>session_start();
$session_ip_address = $_SERVER['REMOTE_ADDR'];
if((!isset($_SESSION['SESSION_IP_ADDRESS'])) || !$_SESSION['SESSION_IP_ADDRESS']) {
    $_SESSION['SESSION_IP_ADDRESS'] = $session_ip_address;
}

if($_SESSION['SESSION_IP_ADDRESS'] != $_SERVER['REMOTE_ADDR']) {
    session_destroy();
    $_SESSION['security_error'] = true;
}
</code>```

If I insert var_dump($_SESSION) right after session_start() and again at the end of the script, then the very first time I run the code (without a session cookie set) I see that at first the array is empty, then it has my IP address assigned to the key 'SESSION_IP_ADDRESS'. So far, so good. But when I run the code again, now it shows that 'SESSION_IP_ADDRESS' is stored as a reference immediately after the session starts (I can tell by the ampersand prepended to the string). When I run it a third time, I see that 'SESSION_IP_ADDRESS' is now a null reference ('SESSION_IP_ADDRESS' => &null) immediately after the session starts. What is going on?!

To reiterate, this is the output the first time:

```<code>array(0) {
}
array(1) {
  ["SESSION_IP_ADDRESS"]=>
  string(11) "xx.xx.xxx.x"
}
</code>```

This is the output the second time:

```<code>array(1) {
  ["SESSION_IP_ADDRESS"]=>
  &string(11) "xx.xx.xxx.x"
}
array(1) {
  ["SESSION_IP_ADDRESS"]=>
  &string(11) "xx.xx.xxx.x"
}
</code>```

And the third time and every time from then on:

```<code>array(1) {
  ["SESSION_IP_ADDRESS"]=>
  &NULL
}
array(1) {
  ["SESSION_IP_ADDRESS"]=>
  &string(11) "xx.xx.xxx.x"
}
</code>```

答:
If I have:

```<code><?php

$x = 'blah';
$_SESSION['blah'] = $x;

var_dump($_SESSION);
</code>```

I get:

```<code>array(1) {
  ["blah"]=>
  string(4) "blah"
}
</code>```

No references in sight. PHP 5.3.2 on Ubuntu 10.04.1

ContentLicense: CC BY-SA 2.5

Body:
Here's the code. It's a simple operation to check that a session ID isn't being spoofed by verifying the IP address:

session_start();
$session_ip_address = $_SERVER['REMOTE_ADDR'];
if((!isset($_SESSION['SESSION_IP_ADDRESS'])) || !$_SESSION['SESSION_IP_ADDRESS']) {
    $_SESSION['SESSION_IP_ADDRESS'] = $session_ip_address;
}

if($_SESSION['SESSION_IP_ADDRESS'] != $_SERVER['REMOTE_ADDR']) {
    session_destroy();
    $_SESSION['security_error'] = true;
}

If I insert var_dump($_SESSION) right after session_start() and again at the end of the script, then the very first time I run the code (without a session cookie set) I see that at first the array is empty, then it has my IP address assigned to the key 'SESSION_IP_ADDRESS'. So far, so good. But when I run the code again, now it shows that 'SESSION_IP_ADDRESS' is stored as a reference immediately after the session starts (I can tell by the ampersand prepended to the string). When I run it a third time, I see that 'SESSION_IP_ADDRESS' is now a null reference ('SESSION_IP_ADDRESS' => &null) immediately after the session starts. What is going on?!

To reiterate, this is the output the first time:

array(0) {
}
array(1) {
  ["SESSION_IP_ADDRESS"]=>
  string(11) "xx.xx.xxx.x"
}

This is the output the second time:

array(1) {
  ["SESSION_IP_ADDRESS"]=>
  &string(11) "xx.xx.xxx.x"
}
array(1) {
  ["SESSION_IP_ADDRESS"]=>
  &string(11) "xx.xx.xxx.x"
}

And the third time and every time from then on:

array(1) {
  ["SESSION_IP_ADDRESS"]=>
  &NULL
}
array(1) {
  ["SESSION_IP_ADDRESS"]=>
  &string(11) "xx.xx.xxx.x"
}

Body:
If I have:

<?php

$x = 'blah';
$_SESSION['blah'] = $x;

var_dump($_SESSION);

I get:

array(1) {
  ["blah"]=>
  string(4) "blah"
}

No references in sight. PHP 5.3.2 on Ubuntu 10.04.1


问:
Array method versus hashes
I have an object (returned from and API) that is either a hash or an array of hashes. I want to enclose it in an array if it is not already an array.

I tried to apply Array on it, which functions in an expected way with numbers or arrays:

```<code>Array(1) # => [1]
Array([1, 2]) # => [1, 2]
Array([{a: 1}, {b: 2}]) # => [{:a=>1}, {:b=>2}]
</code>```

but it fails with hashes:

```<code>Array({a: 1}) # => [[:a, 1]]
</code>```

which should be [{:a=>1}].

Alternatively, I could add a type check:

```<code>responses = [responses] if responses.is_a?(Hash)
</code>```

Is there a better solution?

答:
I want to enclose it in an array if it is not already an array.

What about:

```<code>result = [result] unless result.is_a? Array
</code>```

Alternatively, using try_convert:

```<code>result = Array.try_convert(result) || [result]
</code>```

Title: Array method versus hashes

Body:
I have an object (returned from and API) that is either a hash or an array of hashes. I want to enclose it in an array if it is not already an array.

I tried to apply Array on it, which functions in an expected way with numbers or arrays:

Array(1) # => [1]
Array([1, 2]) # => [1, 2]
Array([{a: 1}, {b: 2}]) # => [{:a=>1}, {:b=>2}]

but it fails with hashes:

Array({a: 1}) # => [[:a, 1]]

which should be [{:a=>1}].

Alternatively, I could add a type check:

responses = [responses] if responses.is_a?(Hash)

Is there a better solution?

Body:
I want to enclose it in an array if it is not already an array.

What about:

result = [result] unless result.is_a? Array

Alternatively, using try_convert:

result = Array.try_convert(result) || [result]


问:
Change just Font of AttributedText in Swift
I have a number of UILabels created in IB which all have attributed text. Each label's text contains multiple lines of different font sizes and colors.

At run-time, I want to be able to change just the font name of these labels without changing the existing font sizes or colors.

I have researched and could not find a straight forward method to achieve this. Any ideas?

答:
The above works great but with Swift4 and Xcode 9.1 I got number of warnings that method names had changed. Below is the result of applying all those warnings. Otherwise I did not change anything.</p>

```<code>let newAttributedString = NSMutableAttributedString(attributedString: label.attributedText!)

// Enumerate through all the font ranges
newAttributedString.enumerateAttribute(NSAttributedStringKey.font, in: NSMakeRange(0, newAttributedString.length), options: [])
{
    value, range, stop in
    guard let currentFont = value as? UIFont else {
        return
    }

    // An NSFontDescriptor describes the attributes of a font: family name, face name, point size, etc.
    // Here we describe the replacement font as coming from the "Hoefler Text" family
    let fontDescriptor = currentFont.fontDescriptor.addingAttributes([UIFontDescriptor.AttributeName.family: "Hoefler Text"])

    // Ask the OS for an actual font that most closely matches the description above
    if let newFontDescriptor = fontDescriptor.matchingFontDescriptors(withMandatoryKeys: [UIFontDescriptor.AttributeName.family]).first {
        let newFont = UIFont(descriptor: newFontDescriptor, size: currentFont.pointSize)
        newAttributedString.addAttributes([NSAttributedStringKey.font: newFont], range: range)
    }
}

label.attributedText = newAttributedString
</code>```

Body:
The above works great but with Swift4 and Xcode 9.1 I got number of warnings that method names had changed. Below is the result of applying all those warnings. Otherwise I did not change anything.

let newAttributedString = NSMutableAttributedString(attributedString: label.attributedText!)

// Enumerate through all the font ranges
newAttributedString.enumerateAttribute(NSAttributedStringKey.font, in: NSMakeRange(0, newAttributedString.length), options: [])
{
    value, range, stop in
    guard let currentFont = value as? UIFont else {
        return
    }

    // An NSFontDescriptor describes the attributes of a font: family name, face name, point size, etc.
    // Here we describe the replacement font as coming from the "Hoefler Text" family
    let fontDescriptor = currentFont.fontDescriptor.addingAttributes([UIFontDescriptor.AttributeName.family: "Hoefler Text"])

    // Ask the OS for an actual font that most closely matches the description above
    if let newFontDescriptor = fontDescriptor.matchingFontDescriptors(withMandatoryKeys: [UIFontDescriptor.AttributeName.family]).first {
        let newFont = UIFont(descriptor: newFontDescriptor, size: currentFont.pointSize)
        newAttributedString.addAttributes([NSAttributedStringKey.font: newFont], range: range)
    }
}

label.attributedText = newAttributedString


问:
What do these 2 code fragments do
These 2 code fragments from the book Algorithms seem to be doing something mathematical. The code I have no trouble understanding, but I want to know what mathematical computation is being done.

1.

```<code>double t=c;
while(Math.abs(t-c/t) > 1e-15*t)
    t=(c/t+t)/2.0;
</code>```

2.

```<code>for(int i=0;i<=N;i++)
    StdOut.println(2*Math.Pi*i/N);
    // prints the value of circumference of a circle of radius 0, 1/N,2/N .. 1 ?
</code>```

答: The first is a standard algorithm for approximating square roots. It can be viewed as a special case of Newton's method but was known thousands of years before Newton and is sometimes called the Babylonian algorithm. The second really should be self-explanatory as it is commented and is just an immediate application of the definition of pi as the ration of circumference to diameter, which is twice the radius.

Title: What do these 2 code fragments do

Body:
These 2 code fragments from the book Algorithms seem to be doing something mathematical. The code I have no trouble understanding, but I want to know what mathematical computation is being done.

1.

double t=c;
while(Math.abs(t-c/t) > 1e-15*t)
    t=(c/t+t)/2.0;

2.

for(int i=0;i<=N;i++)
    StdOut.println(2*Math.Pi*i/N);
    // prints the value of circumference of a circle of radius 0, 1/N,2/N .. 1 ?


问:
Matplotlib maskoceans results using lists
I have 3 lists x,y,z containing long,lat,value. I am trying to construct a plot using contourf and maskoceans. The result i am getting isn't very good near the coastline. Trying to increase arguments of linspace leads to memory error. Is there a way to achieve better result close to the coastline?
My code is as follows:</p>

```<code>import numpy as np
import scipy.interpolate
from mpl_toolkits.basemap import Basemap,maskoceans
import matplotlib.pyplot as plt

x=[23.027008, 22.774524, 23.010211, 22.346053, 21.264416, 21.261967, 21.31769, 21.478437, 21.406678, 21.453064]
y=[36.547227, 36.824754, 37.482874, 37.61182, 37.873769, 37.935473, 37.978032, 38.139038, 38.162707, 38.168772]
z=[155.15, 354.86, 400.2, 47.16, 188.44, 277.01, 375.12, 87.71, 133.85, 123.56]

map =Basemap(projection='mill',
             llcrnrlat=36.928942,llcrnrlon=21.696255,
             urcrnrlat=38.03002,urcrnrlon=23.497298,
             resolution='i')
map.drawcoastlines()

xi, yi = np.linspace(21,24, 100), np.linspace(36, 39, 100)
xi, yi = np.meshgrid(xi, yi)

xm,ym=map(xi,yi)

rbf = scipy.interpolate.Rbf(x, y, z, function='linear')
zi = rbf(xi, yi)

zm=maskoceans(xi,yi,zi,resolution='h',grid=1.25)
map.contourf(xm, ym, zm,cmap='jet')
map.colorbar()

plt.show()
</code>```

答:
The problem you are having is your interpolated grid is not fine enough for the intricacies of the coastline, since you are quite zoomed in. Plus you are using a different resolution for your oceans as for your basemap which causes some strange artifacts. So I made 3 changes to your code:

Don't use map as a variable name - it is a built-in Python function and shouldn't be overridden.

m = Basemap(...

Increase the resolution of your interpolated grid

xi, yi = np.linspace(21,24, 1000), np.linspace(36, 39, 1000)

Match resolution of the maskoceans with the Basemap

zm=maskoceans(xi,yi,zi,resolution='i',grid=1.25)

Body:
I have 3 lists x,y,z containing long,lat,value. I am trying to construct a plot using contourf and maskoceans. The result i am getting isn't very good near the coastline. Trying to increase arguments of linspace leads to memory error. Is there a way to achieve better result close to the coastline?
My code is as follows:

import numpy as np
import scipy.interpolate
from mpl_toolkits.basemap import Basemap,maskoceans
import matplotlib.pyplot as plt

x=[23.027008, 22.774524, 23.010211, 22.346053, 21.264416, 21.261967, 21.31769, 21.478437, 21.406678, 21.453064]
y=[36.547227, 36.824754, 37.482874, 37.61182, 37.873769, 37.935473, 37.978032, 38.139038, 38.162707, 38.168772]
z=[155.15, 354.86, 400.2, 47.16, 188.44, 277.01, 375.12, 87.71, 133.85, 123.56]

map =Basemap(projection='mill',
             llcrnrlat=36.928942,llcrnrlon=21.696255,
             urcrnrlat=38.03002,urcrnrlon=23.497298,
             resolution='i')
map.drawcoastlines()

xi, yi = np.linspace(21,24, 100), np.linspace(36, 39, 100)
xi, yi = np.meshgrid(xi, yi)

xm,ym=map(xi,yi)

rbf = scipy.interpolate.Rbf(x, y, z, function='linear')
zi = rbf(xi, yi)

zm=maskoceans(xi,yi,zi,resolution='h',grid=1.25)
map.contourf(xm, ym, zm,cmap='jet')
map.colorbar()

plt.show()


问:
Java8: Implement multiple conditional statements with stream API
I have a code block that redirects a Cassandra query to different Cassandra tables based on the available parameters such that I check multiple logical conditions inside multiple if conditions. I'm trying my hand at java 8 and looking to reduce these conditions to lambda expressions. Here's how the code currently looks,

```<code>String processTable(String cid, String postcode, String[] ratingvalue, String ratingType) {

    String table = "";
    if (postcode != null && ratingvalue == null) {
        table = cassconf.getTable1();
    }
    if (postcode != null && ratingvalue != null) {
        table = cassconf.getTable2();
    }
    if (cid != null && ratingvalue == null) {
        table = cassconf.getTable3();
    }
    if (cid != null && ratingvalue != null) {
        table = cassconf.getTable4();
    }
    if (cid != null && postcode != null && ratingvalue == null) {
        table = cassconf.getTable5();
    }
    if (cid != null && postcode != null & ratingvalue != null) {
        table = cassconf.getTable6();
    }
    return table;

}
</code>```

My problem is even if I store the arguments in a map and filter the unavailable values from the stream, I don't know how to return the final value of the table based on these 6 different conditions.

答:
Java 8 is not a magic wand you can simply wave at a piece of code to instantly improve it's readability.

Using null as a sentinel is bad practice and that's fundamentally why your code is hard to read. I suggest you rethink having nullable parameters.

Without fixing that, this is probably the best you can do:

```<code>if (ratingvalue == null)
{
    if (cid != null && postcode != null) {
        table = cassconf.getTable5();
    }
    else if (postcode != null) {
        table = cassconf.getTable1();
    }
    else if (cid != null) {
        table = cassconf.getTable3();
    }
}
else
{
    if (cid != null && postcode != null) {
        table = cassconf.getTable6();
    }
    else if (postcode != null) {
        table = cassconf.getTable2();
    }
    else if (cid != null) {
        table = cassconf.getTable4();
    }
}
</code>```

Body:
I have a code block that redirects a Cassandra query to different Cassandra tables based on the available parameters such that I check multiple logical conditions inside multiple if conditions. I'm trying my hand at java 8 and looking to reduce these conditions to lambda expressions. Here's how the code currently looks,

String processTable(String cid, String postcode, String[] ratingvalue, String ratingType) {

    String table = "";
    if (postcode != null && ratingvalue == null) {
        table = cassconf.getTable1();
    }
    if (postcode != null && ratingvalue != null) {
        table = cassconf.getTable2();
    }
    if (cid != null && ratingvalue == null) {
        table = cassconf.getTable3();
    }
    if (cid != null && ratingvalue != null) {
        table = cassconf.getTable4();
    }
    if (cid != null && postcode != null && ratingvalue == null) {
        table = cassconf.getTable5();
    }
    if (cid != null && postcode != null & ratingvalue != null) {
        table = cassconf.getTable6();
    }
    return table;

}

My problem is even if I store the arguments in a map and filter the unavailable values from the stream, I don't know how to return the final value of the table based on these 6 different conditions.

Body:
Java 8 is not a magic wand you can simply wave at a piece of code to instantly improve it's readability.

Using null as a sentinel is bad practice and that's fundamentally why your code is hard to read. I suggest you rethink having nullable parameters.

Without fixing that, this is probably the best you can do:

if (ratingvalue == null)
{
    if (cid != null && postcode != null) {
        table = cassconf.getTable5();
    }
    else if (postcode != null) {
        table = cassconf.getTable1();
    }
    else if (cid != null) {
        table = cassconf.getTable3();
    }
}
else
{
    if (cid != null && postcode != null) {
        table = cassconf.getTable6();
    }
    else if (postcode != null) {
        table = cassconf.getTable2();
    }
    else if (cid != null) {
        table = cassconf.getTable4();
    }
}


问:
Pipeline : Folder has an appended @number after checkout from SVN
I am checking out a folder from one SVN location onto 3 different VMs. The folder "MakeBelieve" has to be checked out. So I use the Groovy syntax:

```<code>checkout([
$class: 'SubversionSCM',
additionalCredentials: [],
excludedCommitMessages: '',
excludedRegions: '',
excludedRevprop: '',
excludedUsers: '',
filterChangelog: false,
ignoreDirPropChanges: false,
includedRegions: '',
locations: [[credentialsId: 'xxxxxxxxxxxxxxxxxxxxxxxxxxx',
depthOption: 'infinity',
ignoreExternalsOption: true,
local: 'MakeBelieve',
remote: 'svn_url_to_be_removed']],
workspaceUpdater: [$class: 'CheckoutUpdater']])
</code>```

Out of the 3 Virtual Machines, on 2 machines it is being checked out as MakeBelieve. But on one of the machines it is being checked as MakeBelieve@2. Don't know why this is happening. The parallel stage is stated as:

```<code>stage('Check Out Code') {
        parallel {
            stage('Checkout in Machine1') {
                agent {
                    label "Machine1"
                }
                steps {
                    echo 'Check out code '
                    checkout([$class: 'SubversionSCM',
                    additionalCredentials: [],
                     excludedCommitMessages: '',
                     excludedRegions: '',
                     excludedRevprop: '',
                     excludedUsers: '',
                     filterChangelog: false,
                     ignoreDirPropChanges: false,
                     includedRegions: '',
                     locations: [[credentialsId: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
                     depthOption: 'infinity',
                     ignoreExternalsOption: true,
                     local: 'MakeBelieve',
                     remote: 'svn_url']],
                     workspaceUpdater: [$class: 'CheckoutUpdater']])
                }
            }
            stage('Checkout in Machine2') {
                agent {
                    label "Machine2"
                }
                steps {
                    echo 'Check out code in'
                    checkout([$class: 'SubversionSCM',
                        additionalCredentials: [],
                        excludedCommitMessages: '',
                        excludedRegions: '',
                        excludedRevprop: '',
                        excludedUsers: '',
                        filterChangelog: false,
                        ignoreDirPropChanges: false,
                        includedRegions: '',
                        locations: [[credentialsId: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
                        depthOption: 'infinity',
                        ignoreExternalsOption: true,
                        local: 'MakeBelieve',
                        remote: 'svn_url']],
                        workspaceUpdater: [$class: 'CheckoutUpdater']])
                }
            }
            stage('Checkout in Machine3') {
                agent {
                    label "Machine3"
                }
                steps {
                    echo 'Check out code in'
                    checkout([$class: 'SubversionSCM',
                        additionalCredentials: [],
                        excludedCommitMessages: '',
                        excludedRegions: '',
                        excludedRevprop: '',
                        excludedUsers: '',
                        filterChangelog: false,
                        ignoreDirPropChanges: false,
                        includedRegions: '',
                        locations: [[credentialsId: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
                        depthOption: 'infinity',
                        ignoreExternalsOption: true,
                        local: 'MakeBelieve',
                        remote: 'svn_url']],
                        workspaceUpdater: [$class: 'CheckoutUpdater']])
                }
            }
        }
    }
</code>```

The folders should have the same name instead 2 machines have the correct folder and the last machine gets checked out as MakeBelieve@2. I need it to be MakeBelieve.

答:
I think this is due to concurrent builds. For every build that is started while one already is in progress, Jenkins appends an "@#concurrent build" to the workspace folder (I do not have a reference for this, just observation of my own setup). Maybe this SO question will solve your problem:

How do I prevent two pipeline jenkins jobs of the same type to run in parallel on the same node?

Body:
I am checking out a folder from one SVN location onto 3 different VMs. The folder "MakeBelieve" has to be checked out. So I use the Groovy syntax:

checkout([
$class: 'SubversionSCM',
additionalCredentials: [],
excludedCommitMessages: '',
excludedRegions: '',
excludedRevprop: '',
excludedUsers: '',
filterChangelog: false,
ignoreDirPropChanges: false,
includedRegions: '',
locations: [[credentialsId: 'xxxxxxxxxxxxxxxxxxxxxxxxxxx',
depthOption: 'infinity',
ignoreExternalsOption: true,
local: 'MakeBelieve',
remote: 'svn_url_to_be_removed']],
workspaceUpdater: [$class: 'CheckoutUpdater']])

Out of the 3 Virtual Machines, on 2 machines it is being checked out as MakeBelieve. But on one of the machines it is being checked as MakeBelieve@2. Don't know why this is happening. The parallel stage is stated as:

stage('Check Out Code') {
        parallel {
            stage('Checkout in Machine1') {
                agent {
                    label "Machine1"
                }
                steps {
                    echo 'Check out code '
                    checkout([$class: 'SubversionSCM',
                    additionalCredentials: [],
                     excludedCommitMessages: '',
                     excludedRegions: '',
                     excludedRevprop: '',
                     excludedUsers: '',
                     filterChangelog: false,
                     ignoreDirPropChanges: false,
                     includedRegions: '',
                     locations: [[credentialsId: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
                     depthOption: 'infinity',
                     ignoreExternalsOption: true,
                     local: 'MakeBelieve',
                     remote: 'svn_url']],
                     workspaceUpdater: [$class: 'CheckoutUpdater']])
                }
            }
            stage('Checkout in Machine2') {
                agent {
                    label "Machine2"
                }
                steps {
                    echo 'Check out code in'
                    checkout([$class: 'SubversionSCM',
                        additionalCredentials: [],
                        excludedCommitMessages: '',
                        excludedRegions: '',
                        excludedRevprop: '',
                        excludedUsers: '',
                        filterChangelog: false,
                        ignoreDirPropChanges: false,
                        includedRegions: '',
                        locations: [[credentialsId: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
                        depthOption: 'infinity',
                        ignoreExternalsOption: true,
                        local: 'MakeBelieve',
                        remote: 'svn_url']],
                        workspaceUpdater: [$class: 'CheckoutUpdater']])
                }
            }
            stage('Checkout in Machine3') {
                agent {
                    label "Machine3"
                }
                steps {
                    echo 'Check out code in'
                    checkout([$class: 'SubversionSCM',
                        additionalCredentials: [],
                        excludedCommitMessages: '',
                        excludedRegions: '',
                        excludedRevprop: '',
                        excludedUsers: '',
                        filterChangelog: false,
                        ignoreDirPropChanges: false,
                        includedRegions: '',
                        locations: [[credentialsId: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
                        depthOption: 'infinity',
                        ignoreExternalsOption: true,
                        local: 'MakeBelieve',
                        remote: 'svn_url']],
                        workspaceUpdater: [$class: 'CheckoutUpdater']])
                }
            }
        }
    }

The folders should have the same name instead 2 machines have the correct folder and the last machine gets checked out as MakeBelieve@2. I need it to be MakeBelieve.


问:
How to add a Send feedback option on an app crashing?
How can I add a Send feedback option on an Android app crashing? This option is seen in Google's own apps and here is an example from Starbucks.

There are a number of very old answers to this question that involve programmatically creating something like this. They seem overly involved to make this show.

I'm surprised there isn't a simple way to implement this without putting a try catch around the entire app. Can this be enabled simply e.g. by enabling an option on the Google Play store console or by by adding something to the manifest?

I have not been able to find data on how to do this in the Android or Play Store documentation.

Update: We are using Crashlytics/Fabric as our crash reporting library

This image shows the default behaviour on Android 6.0.

And 8.0:

答:
The Android platform will just do this for you. You don't need to add any additional code. Try throwing an exception from your app. You should see this.

See https://android-developers.googleblog.com/2010/05/google-feedback-for-android.html

Once you publish the app to playstore, the option to "Send feedback" will be visible. I think you are not able to see it because the app which you are testing is a version of the app not directly downloaded from playstore, e.g: one signed with debug keystore.


问:
Rails + Authlogic @current_user problem - "Show" method no longer works
I implemented Authlogic in my rails app which works and tests great. Users can login, logout, etc.

However, since I changed my methods in the users_controller to use the @current_user variable, none of my user methods or forms (other than "index" strangely...) work!

For example, this "Show" methods works and shows the user profile for any user (Note: I want to eventually restrict this to the currently logged in user somehow):

```<code>def show
    @user = User.find(params[:id])
end
</code>```

If I follow the show method as shown in the Authlogic rails cast and the official example to:

```<code>def show
    @user = @current_user
end
</code>```

I get all kinds of undefined method METHOD for nil:NilClass errors. It seems as the though the @current_user variable doesn't contain any of the user's information.

I assume the @current_user is pulling info from the current_user method as defined in the application controller below:

```<code>def current_user
  return @current_user if defined?(@current_user)
  @current_user = current_user_session && current_user_session.record
end
</code>```

What am I missing? My hunch is that there is no mapping between the User object from the user model and the current_user method. Any help would be greatly appreciated!

Thanks in advance!

~Dan

答:
current_user is a helper that comes with authlogic, so you have to use it without '@'.
Usually you create @sothing to pass it from controller to view, so you will access something you prepared in the action method.</p>

Body:
I implemented Authlogic in my rails app which works and tests great. Users can login, logout, etc.

However, since I changed my methods in the users_controller to use the @current_user variable, none of my user methods or forms (other than "index" strangely...) work!

For example, this "Show" methods works and shows the user profile for any user (Note: I want to eventually restrict this to the currently logged in user somehow):

def show
    @user = User.find(params[:id])
end

If I follow the show method as shown in the Authlogic rails cast and the official example to:

def show
    @user = @current_user
end

I get all kinds of undefined method METHOD for nil:NilClass errors. It seems as the though the @current_user variable doesn't contain any of the user's information.

I assume the @current_user is pulling info from the current_user method as defined in the application controller below:

def current_user
  return @current_user if defined?(@current_user)
  @current_user = current_user_session && current_user_session.record
end

What am I missing? My hunch is that there is no mapping between the User object from the user model and the current_user method. Any help would be greatly appreciated!

Thanks in advance!

~Dan


问:
Ajax image NOT changing on dropdown selection
HTML

```<code>    <div class="new-product">
        <div class="col-md-5 zoom-grid">
            <div class="flexslider">
                <ul class="slides">
                     <li data-thumb="images/<?php echo $productimg1?>">
                        <div id="style_image" class="thumb-image" ><img  src="images/<?php echo $productimg1?>" data-imagezoom="true" class="img-responsive" alt="" /> </div>
                    </li>
                    <li data-thumb="images/<?php echo $productimg2?>">

                </ul>
            </div>
        </div>
</code>```

I have this html where image comes from database using php
 now I need to change that image with ajax

```<code>    <script>

function getState(val) {

    $.ajax({
    type: "POST",
    url: "check.php",
    data: {id: val},
    dataType:'json',
    success: function(data){
        $("#style_code").children().remove();
        $("#style_image").children().remove();
         data.option.forEach(function (item) {
                $("#style_code").append('<option value="' + item.color_name + '">' + item.size + '</option>');

                $('#style_image').append('<img  src="images/'+item.image_name+'" data-imagezoom="true" class="img-responsive" alt="" />')
            //$("#style_image").html(data);

            });

    }
    });
    }
</script>
</code>```

check.php

```<code>        <?php

$con=mysqli_connect("localhost","root","","ecommercedb") or die(mysql_error());

if(!empty($_POST["id"])) {
    $query ="SELECT * FROM stylecolor WHERE color_code = '" . $_POST["id"] . "'";       $results = mysqli_query($con,$query);
     while (($row = mysqli_fetch_object($results))) {
        $data->option[] = $row;

    }

}
      echo json_encode($data);
  ?>
</code>```

It's not changing  the image on slider but when I call it somewhere else it is working fine.
I am using 2 functions on 1 dropdown item ,i.e. it changes the other dropdown options and an image .

答:
You should use style_image as id. Like:

```<code><div  id="style_image" class="thumb-image" >
</code>```

NOT:

```<code><div  #style_image class="thumb-image" >
</code>```

ContentLicense: CC BY-SA 4.0

Body:
HTML

                     <li data-thumb="images/<?php echo $productimg1?>">

<img  src="images/<?php echo $productimg1?>" data-imagezoom="true" class="img-responsive" alt="" />

                    <li data-thumb="images/<?php echo $productimg2?>">

I have this html where image comes from database using php
 now I need to change that image with ajax

check.php

        <?php

$con=mysqli_connect("localhost","root","","ecommercedb") or die(mysql_error());

if(!empty($_POST["id"])) {
    $query ="SELECT * FROM stylecolor WHERE color_code = '" . $_POST["id"] . "'";       $results = mysqli_query($con,$query);
     while (($row = mysqli_fetch_object($results))) {
        $data->option[] = $row;

    }

}
      echo json_encode($data);
  ?>

It's not changing  the image on slider but when I call it somewhere else it is working fine.
I am using 2 functions on 1 dropdown item ,i.e. it changes the other dropdown options and an image .

Body:
You should use style_image as id. Like:

<div  id="style_image" class="thumb-image" >

NOT:

<div  #style_image class="thumb-image" >


问:
Apache nifi: Timed out while waiting for OnScheduled of 'QueryDatabaseTable' processor to finish
I'm trying to create my first flow using the QueryDatabaseTable to incrementally extract rows from an Oracle database table.

I'm getting the errors below.  I enabled full debug but nothing else useful is logged.

Thoughts on what to try next?

2017-07-10 14:43:52,280 WARN [StandardProcessScheduler Thread-4] o.a.n.controller.StandardProcessorNode Timed out while waiting for OnScheduled of 'QueryDatabaseTable' processor to finish. An attempt is made to cancel the task via Thread.interrupt(). However it does not guarantee that the task will be canceled since the code inside current OnScheduled operation may have been written to ignore interrupts which may result in a runaway thread. This could lead to more issues, eventually requiring NiFi to be restarted. This is usually a bug in the target Processor 'QueryDatabaseTable[id=1e535f00-015d-1000-236d-7adebe14958a]' that needs to be documented, reported and eventually fixed.

2017-07-10 14:43:52,280 ERROR [StandardProcessScheduler Thread-4] o.a.n.p.standard.QueryDatabaseTable QueryDatabaseTable[id=1e535f00-015d-1000-236d-7adebe14958a] QueryDatabaseTable[id=1e535f00-015d-1000-236d-7adebe14958a] failed to invoke @OnScheduled method due to java.lang.RuntimeException: Timed out while executing one of processor's OnScheduled task.; processor will not be scheduled to run for 30 seconds: java.lang.RuntimeException: Timed out while executing one of processor's OnScheduled task.
java.lang.RuntimeException: Timed out while executing one of processor's OnScheduled task.
        at org.apache.nifi.controller.StandardProcessorNode.invokeTaskAsCancelableFuture(StandardProcessorNode.java:1480)
        at org.apache.nifi.controller.StandardProcessorNode.access$000(StandardProcessorNode.java:102)
        at org.apache.nifi.controller.StandardProcessorNode$1.run(StandardProcessorNode.java:1303)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)
Caused by: java.util.concurrent.TimeoutException: null
        at java.util.concurrent.FutureTask.get(FutureTask.java:205)
        at org.apache.nifi.controller.StandardProcessorNode.invokeTaskAsCancelableFuture(StandardProcessorNode.java:1465)
        ... 9 common frames omitted

2017-07-10 14:43:52,280 ERROR [StandardProcessScheduler Thread-4] o.a.n.controller.StandardProcessorNode Failed to invoke @OnScheduled method due to java.lang.RuntimeException: Timed out while executing one of processor's OnScheduled task.
java.lang.RuntimeException: Timed out while executing one of processor's OnScheduled task.
        at org.apache.nifi.controller.StandardProcessorNode.invokeTaskAsCancelableFuture(StandardProcessorNode.java:1480)
        at org.apache.nifi.controller.StandardProcessorNode.access$000(StandardProcessorNode.java:102)
        at org.apache.nifi.controller.StandardProcessorNode$1.run(StandardProcessorNode.java:1303)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)
Caused by: java.util.concurrent.TimeoutException: null
        at java.util.concurrent.FutureTask.get(FutureTask.java:205)
        at org.apache.nifi.controller.StandardProcessorNode.invokeTaskAsCancelableFuture(StandardProcessorNode.java:1465)
        ... 9 common frames omitted

答:
On my case, it was a firewall issue. I asked to permission from security manager. The connection also can be checked via telnet.

```<code>telnet databaseserver port_number
</code>```

Expected output:

```<code>Trying database_server...
Connected to 1database_server.
Escape character is '^]'.
</code>```

Body:
On my case, it was a firewall issue. I asked to permission from security manager. The connection also can be checked via telnet.

telnet databaseserver port_number

Expected output:

Trying database_server...
Connected to 1database_server.
Escape character is '^]'.


问:
get response or signal when all threads are complete
Using GUI i am copying multiple files. for each file i am starting a thread. Is there is a way with which I can get a signal or response which tells that all the threads are done with their work. I need the response because depending on the response when all threads are done, I want to enable/disable few buttons and check boxes on the GUI. </p>

```<code>for file_name in _src_files:
    if (os.path.exists(_full_file_name)):
        t = Thread(target=file_util.copy_file, args=[_full_file_name, _str_destination_dir, 'update=1'])
        t.start()
</code>```

答:
You must create a class that inherits from QObject and have custom signals, for example:

```<code>def copy_file(source, destination, message, log):
    [...]
    log.finished.emit()
</code>```

```<code>class Logger(QObject):
    finished = pyqtSignal()
</code>```

```<code>self.l = Logger()
for file_name in _src_files:
    if (os.path.exists(_full_file_name)):
        t = Thread(target=file_util.copy_file, args=[_full_file_name, _str_destination_dir, 'update=1'], self.l)
        t.start()
self.l.finished.connect(some_slot)
</code>```

Example:

```<code>import time
from threading import Thread
import sys

from PyQt4.QtGui import *
from PyQt4.QtCore import *

class Logger(QObject):
    finished = pyqtSignal(str)

def myfunc(i, log):
    print("sleeping 5 sec from thread %d" % i)
    time.sleep(5)
    print("finished sleeping from thread %d" % i)
    log.finished.emit("message %d" % i)

class Widget(QWidget):
    def __init__(self, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)
        self.l = Logger()
        self.counter_threads = 0
        for i in range(10):
            t = Thread(target=myfunc, args=(i, self.l))
            t.start()
            self.counter_threads += 1
        self.l.finished.connect(self.some_slot)

    def some_slot(self, message):
        print("some_slot: "+ message)
        self.counter_threads -= 1
        if self.counter_threads == 0:
            print("finished all threads")

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())
</code>```

Body:
Using GUI i am copying multiple files. for each file i am starting a thread. Is there is a way with which I can get a signal or response which tells that all the threads are done with their work. I need the response because depending on the response when all threads are done, I want to enable/disable few buttons and check boxes on the GUI.

for file_name in _src_files:
    if (os.path.exists(_full_file_name)):
        t = Thread(target=file_util.copy_file, args=[_full_file_name, _str_destination_dir, 'update=1'])
        t.start()

Body:
You must create a class that inherits from QObject and have custom signals, for example:

def copy_file(source, destination, message, log):
    [...]
    log.finished.emit()

class Logger(QObject):
    finished = pyqtSignal()

self.l = Logger()
for file_name in _src_files:
    if (os.path.exists(_full_file_name)):
        t = Thread(target=file_util.copy_file, args=[_full_file_name, _str_destination_dir, 'update=1'], self.l)
        t.start()
self.l.finished.connect(some_slot)

Example:

import time
from threading import Thread
import sys

from PyQt4.QtGui import *
from PyQt4.QtCore import *

class Logger(QObject):
    finished = pyqtSignal(str)

def myfunc(i, log):
    print("sleeping 5 sec from thread %d" % i)
    time.sleep(5)
    print("finished sleeping from thread %d" % i)
    log.finished.emit("message %d" % i)

class Widget(QWidget):
    def __init__(self, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)
        self.l = Logger()
        self.counter_threads = 0
        for i in range(10):
            t = Thread(target=myfunc, args=(i, self.l))
            t.start()
            self.counter_threads += 1
        self.l.finished.connect(self.some_slot)

    def some_slot(self, message):
        print("some_slot: "+ message)
        self.counter_threads -= 1
        if self.counter_threads == 0:
            print("finished all threads")

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())


问:
How do I avoid a media player crash when the back button is clicked on the device?
I have a media player in an Android Studio project. It crashes when the back button is clicked on the connected phone. This is what I gathered from the Logcat as the fault: "Unable to destroy activity {com.example.proj/com.example.proj.RadioActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.stop()' on a null object reference"

Here's the relevant snippet:

```<code>@Override
public void onDestroy() {
    super.onDestroy();
    stop();
}

public void onCompletion(MediaPlayer mp) {
    stop();
}
</code>```

I've found that if I click "Play" and then the back button, the app does not crash, suggesting that play is not a null object reference even if no media is playing).

How do I write a condition that if the back button is clicked and the MediaPlayer is not playing, do not destroy the player/app? I have no reference to the button in the code.

答:
```<code>@Override
protected void onDestroy() {
    super.onDestroy();
    if (mediaPlayer != null) {
        mediaPlayer.stop();
    }
}
</code>```

Body:
I have a media player in an Android Studio project. It crashes when the back button is clicked on the connected phone. This is what I gathered from the Logcat as the fault: "Unable to destroy activity {com.example.proj/com.example.proj.RadioActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.stop()' on a null object reference"

Here's the relevant snippet:

@Override
public void onDestroy() {
    super.onDestroy();
    stop();
}

public void onCompletion(MediaPlayer mp) {
    stop();
}

I've found that if I click "Play" and then the back button, the app does not crash, suggesting that play is not a null object reference even if no media is playing).

How do I write a condition that if the back button is clicked and the MediaPlayer is not playing, do not destroy the player/app? I have no reference to the button in the code.


问:
How to copy a python object/ How to get element of a python object

Question 1:

I need to make a copy of one circle I create

```<code>import matplotlib.pyplot as plt
from matplotlib.patches import Circle
C1=Circle(xy=(3, 4), radius=2, fill=False, color='g')
</code>```

I want to do something like:

```<code>C2 = C1.copy()
</code>```

To be able to modify C2 without modifying C1 but I get the error:

```<code>'AttributeError: 'Circle' object has no attribute 'copy''
</code>```

Does anyone know how to do it?

Question 2:

I try to get the element of C1

```<code>xy = C1.xy
</code>```

AttributeError: 'Circle' object has no attribute 'xy'

```<code>color = C1.color
</code>```

AttributeError: 'Circle' object has no attribute 'color'

For xy, I manage to get it by doing

```<code>xy = C1.center
</code>```

But I do not understand why I have to use center even if I declare it as 'xy'. For color I still don't know how to get it... I thin it is probably a characteristic of a parent object (not specific to the circle object) but how to get it????

答:
```<code>import matplotlib.pyplot as plt
from matplotlib.patches import Circle

C1=Circle(xy=(3, 4), radius=2, fill=False, color='g')
</code>```

To get the color 'b' of the circle:

```<code>C1.get_edgecolor()
</code>```

Body:
Question 1:

I need to make a copy of one circle I create

import matplotlib.pyplot as plt
from matplotlib.patches import Circle
C1=Circle(xy=(3, 4), radius=2, fill=False, color='g')

I want to do something like:

C2 = C1.copy()

To be able to modify C2 without modifying C1 but I get the error:

'AttributeError: 'Circle' object has no attribute 'copy''

Does anyone know how to do it?

Question 2:

I try to get the element of C1

xy = C1.xy

AttributeError: 'Circle' object has no attribute 'xy'

color = C1.color

AttributeError: 'Circle' object has no attribute 'color'

For xy, I manage to get it by doing

xy = C1.center

But I do not understand why I have to use center even if I declare it as 'xy'. For color I still don't know how to get it... I thin it is probably a characteristic of a parent object (not specific to the circle object) but how to get it????

Body:
import matplotlib.pyplot as plt
from matplotlib.patches import Circle

C1=Circle(xy=(3, 4), radius=2, fill=False, color='g')

To get the color 'b' of the circle:

C1.get_edgecolor()


问:
Docker "Get Started(Python)" not working
Python developer: See last part "For Python developer"!

MacOs: 10.13.1 (17B1003)

Docker version:

```<code>Client:
 Version:      17.09.0-ce
 API version:  1.32
 Go version:   go1.8.3
 Git commit:   afdb6d4
 Built:        Tue Sep 26 22:40:09 2017
 OS/Arch:      darwin/amd64

Server:
 Version:      17.09.0-ce
 API version:  1.32 (minimum version 1.12)
 Go version:   go1.8.3
 Git commit:   afdb6d4
 Built:        Tue Sep 26 22:45:38 2017
 OS/Arch:      linux/amd64
 Experimental: true
</code>```

The following "Get stated" is not working:
https://docs.docker.com/get-started/part2/#run-the-app

Running: docker run -p 4000:80 friendlyhello

Just produces the following:

```<code>5e4d9c813323        friendlyhello       "python app.py"     6 seconds ago       Exited (0) 4 seconds ago                       focused_payne
</code>```

And docker logs js empty.

Also if:

```<code>docker run -it -p 4000:80 friendlyhello /bin/bash
</code>```

and run: python app.py

Nothing. So it might have to do with python app.py.

Note: I am not a Python dev.

For Python developer:

app.py:

```<code>from flask import Flask
from redis import Redis, RedisError
import os
import socket

# Connect to Redis
redis = Redis(host="redis", db=0, socket_connect_timeout=2, socket_timeout=2)

app = Flask(__name__)

@app.route("/")
def hello():
    try:
        visits = redis.incr("counter")
    except RedisError:
        visits = "<i>cannot connect to Redis, counter disabled</i>"

    html = "<h3>Hello {name}!</h3>" \
           "<b>Hostname:</b> {hostname}<br/>" \
           "<b>Visits:</b> {visits}"
    return html.format(name=os.getenv("NAME", "world"), hostname=socket.gethostname(), visits=visits)

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=80)
</code>```

答:
I think you're doing something else wrong, i copied all three files and ran it just fine.

https://gist.github.com/kingbuzzman/b48be91757fc60e97f6a9a189d006bd8

here are the full steps: (i really suggest you are in /tmp when you run this)

```<code># 1. Create a temp folder
# 2. Download all the files into the temp folder
# 3. Build the docker image
# 4. Run the image in a detached mode -- so we can curl the url
# 5. Sleep a little and wait until the app is fully up
# 6. Test that it all works
# 7. Stop the container (and we don't care about its stdout)
mkdir -p dockerapp && \
curl -sL https://gist.github.com/kingbuzzman/b48be91757fc60e97f6a9a189d006bd8/download | tar -xvz -C dockerapp --strip-components=1 && \
docker build -t friendlyhello dockerapp && \
docker run --rm -p 4000:80 --name friendlyhello -d friendlyhello && \
sleep 2 && \
curl -s http://localhost:4000/ -w "\n" && \
docker kill friendlyhello >/dev/null
</code>```

(you can highlight and copy all this straight into your terminal and see this)

What we're looking for here is the last line
Hello World!
Hostname: 979c5e755f64
Visits: cannot connect to Redis, counter disabled which is how we know its running.

Body:
Python developer: See last part "For Python developer"!

MacOs: 10.13.1 (17B1003)

Docker version:

Client:
 Version:      17.09.0-ce
 API version:  1.32
 Go version:   go1.8.3
 Git commit:   afdb6d4
 Built:        Tue Sep 26 22:40:09 2017
 OS/Arch:      darwin/amd64

Server:
 Version:      17.09.0-ce
 API version:  1.32 (minimum version 1.12)
 Go version:   go1.8.3
 Git commit:   afdb6d4
 Built:        Tue Sep 26 22:45:38 2017
 OS/Arch:      linux/amd64
 Experimental: true

The following "Get stated" is not working:
https://docs.docker.com/get-started/part2/#run-the-app

Running: docker run -p 4000:80 friendlyhello

Just produces the following:

5e4d9c813323        friendlyhello       "python app.py"     6 seconds ago       Exited (0) 4 seconds ago                       focused_payne

And docker logs js empty.

Also if:

docker run -it -p 4000:80 friendlyhello /bin/bash

and run: python app.py

Nothing. So it might have to do with python app.py.

Note: I am not a Python dev.

For Python developer:

app.py:

from flask import Flask
from redis import Redis, RedisError
import os
import socket

# Connect to Redis
redis = Redis(host="redis", db=0, socket_connect_timeout=2, socket_timeout=2)

app = Flask(__name__)

@app.route("/")
def hello():
    try:
        visits = redis.incr("counter")
    except RedisError:
        visits = "cannot connect to Redis, counter disabled"

    html = "
Hello {name}!
" \
           "Hostname: {hostname}
" \
           "Visits: {visits}"
    return html.format(name=os.getenv("NAME", "world"), hostname=socket.gethostname(), visits=visits)

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=80)

Body:
I think you're doing something else wrong, i copied all three files and ran it just fine.

https://gist.github.com/kingbuzzman/b48be91757fc60e97f6a9a189d006bd8

here are the full steps: (i really suggest you are in /tmp when you run this)

# 1. Create a temp folder
# 2. Download all the files into the temp folder
# 3. Build the docker image
# 4. Run the image in a detached mode -- so we can curl the url
# 5. Sleep a little and wait until the app is fully up
# 6. Test that it all works
# 7. Stop the container (and we don't care about its stdout)
mkdir -p dockerapp && \
curl -sL https://gist.github.com/kingbuzzman/b48be91757fc60e97f6a9a189d006bd8/download | tar -xvz -C dockerapp --strip-components=1 && \
docker build -t friendlyhello dockerapp && \
docker run --rm -p 4000:80 --name friendlyhello -d friendlyhello && \
sleep 2 && \
curl -s http://localhost:4000/ -w "\n" && \
docker kill friendlyhello >/dev/null

(you can highlight and copy all this straight into your terminal and see this)

What we're looking for here is the last line <h3>Hello World!</h3><b>Hostname:</b> 979c5e755f64<br/><b>Visits:</b> <i>cannot connect to Redis, counter disabled</i> which is how we know its running.


问:
DB or XML Question
XML seems to be another way to store information in a much smaller scale? While DB can handle all sorts. I'm interested in knowing what are the pro's and con's to the each. Is one of them better in a scenario? I'm sure each has there best case scenario.

Thank you in advance.

答:
XML is great for storing static data, like configuration files.  It can be read from very easily and quickly with existing APIs and/or XPath.  However, since it is simply a file it should be used only for storing data that will be read and not require updates from the application your users will use.  Depending on your OS, file locking and privileges may be an issue for updates and concurrency could be a logistical nightmare to maintain.

Databases are collections of records that can be read, updated, or deleted with ease.  For large datasets, databases also provide the ability to index fields to improve performance and to setup different schema or views to control the visibility of records for different types of users.  Data integrity can more easily be maintained with a database as well.

In summary, XML is better suited for small to medium datasets that will not need to change often and are read-only from the application.  Databases are better suited for dynamic or large datasets or where security of the data may be a concern.

Title: DB or XML Question


问:
Scala : append Array to List
I'm trying to append Array to List When writing data into a csv file as follows.

But, each Array was not appended to the List.
How can I append each Array to a List.

Please help me with this.

```<code>import java.io.StringWriter
import au.com.bytecode.opencsv.CSVWriter
import scala.collection.JavaConversions._
import java.io.FileWriter
import java.io.BufferedWriter

var out = new BufferedWriter(new FileWriter("/Users/TestCom/Desktop/test_4.csv"));
var writer = new CSVWriter(out);
var outputSchema = Array("name","0h","20h")
var listOfRecords = List(outputSchema)

var numIters = 0
for(numIters <- 0 to 1){

    var testVal1 = numIters + 1
    var testVal2 = numIters + 2

    var eachArr = Array(testVal1, testVal2)
    listOfRecords ++ eachArr
}

writer.writeAll(listOfRecords)
out.close()
</code>```

答:
Change your line that does listOfRecords ++ eachArr to be listOfRecords = listOfRecords ++ eachArr.

The list is immutable so you must reassign after appending.

Title: Scala : append Array to List

Body:
I'm trying to append Array to List When writing data into a csv file as follows.

But, each Array was not appended to the List.
How can I append each Array to a List.

Please help me with this.

import java.io.StringWriter
import au.com.bytecode.opencsv.CSVWriter
import scala.collection.JavaConversions._
import java.io.FileWriter
import java.io.BufferedWriter

var out = new BufferedWriter(new FileWriter("/Users/TestCom/Desktop/test_4.csv"));
var writer = new CSVWriter(out);
var outputSchema = Array("name","0h","20h")
var listOfRecords = List(outputSchema)

var numIters = 0
for(numIters <- 0 to 1){

    var testVal1 = numIters + 1
    var testVal2 = numIters + 2

    var eachArr = Array(testVal1, testVal2)
    listOfRecords ++ eachArr
}

writer.writeAll(listOfRecords)
out.close()


问:
Building a constexpr template struct (C++11)
I have this code, which works... so far so good :

```<code>struct _TYPEIDSTR {};
typedef _TYPEIDSTR *TYPE_ID;
template<class T> _TYPEIDSTR _TYPE_ID;

template<class T> constexpr TYPE_ID getTypeID() { return &_TYPE_ID<T>; }
</code>```

calling in main like this :

```<code>constexpr TYPE_ID id1 = getTypeID<int>();
constexpr TYPE_ID id2 = getTypeID<int>();
RLOG("ID1 : " << id1);
RLOG("ID2 : " << id2);
</code>```

works perfectly, and I've an unique identifier for each type used in getTypeID() call.
Now I want to build a struct that brings some info about a function :

```<code>template<typename RES, typename... ARGS> struct _GlobalOverlayInfo {
    bool _member;
    RES(*_fn)(ARGS...);
    size_t _nargs;
    TYPE_ID _argIDs;
    constexpr _GlobalOverlayInfo(RES(*fn)(ARGS...)) :
    _member(false),
    _fn(fn),
    _nargs(sizeof...(ARGS)),
    _argIDs {getTypeID<ARGS>()...}
    {}
};

template<typename RES, typename... ARGS>
constexpr auto getOverlayInfo(RES(*fn)(ARGS...)) {
    return & _GlobalOverlayInfo<RES, ARGS...>(fn); <<---ERROR1
}
</code>```

using this function :

```<code>int pippo(int x) {
    return 0;
}
</code>```

and calling like this :

```<code>constexpr auto x = getOverlayInfo(pippo); <<--- ERROR2
</code>```

I get the 2 marked errors; ERROR1 is "taking address of a temporary" (but shouldn't it a compile time evaluation ?) and ERROR2 is "error: ‘&’ is not a constant expression".
I tried in many ways, but I couldn't success. Where I am wrong ?
Is there a way (in C++11) to achieve this result ?
All I need is a pointer to an unique structure generated for each RES and ARGS... parameters.

答:
Not sure to understand what you want to do.

Anyway, if you want to works with C++11 (and avoid C++14 or newer) you can't use a template variable like

```<code>template<class T> _TYPEIDSTR _TYPE_ID;
</code>```

that is a C++14 feature.

If you want a constexpr template identifier, you could use std::type_index, that is available starting from C++11.

If you can't use std::type_index... well, the best I can imagine is a template class with a static variable and a static method that return the pointer to it.

Something like

```<code>template <typename>
struct typeId
 {
   static constexpr int const val {};

   static constexpr int const * getId ()
    { return &val; }
 };

template <typename T>
constexpr int const typeId<T>::val;
</code>```

You can get constexpr values and you can check that are differents

```<code>constexpr auto const idInt = typeId<int>::getId();
constexpr auto const idLong = typeId<long>::getId();

std::cout << (idInt != idLong) << std::endl; // print 1
</code>```

For the function case...

Functions has types and single functions can be template parameters.

So if you want a constexpr identifier for a function, you can create a wrapper as follows

```<code>template <typename Ft, Ft f>
struct funcT
 { };
</code>```

and, using the preceding typeId, get different constexpr values from different functions as follows

```<code>int  foo (int) { return 0; }
int  bar (int) { return 0; }
long baz (int, long, long long) { return 0L; }

// ...

constexpr auto idFoo = typeId<funcT<decltype(&foo), &foo>>::getId();
constexpr auto idBar = typeId<funcT<decltype(&bar), &bar>>::getId();
constexpr auto idBaz = typeId<funcT<decltype(&baz), &baz>>::getId();

std::cout << (idFoo != idBar) << std::endl; // print 1
std::cout << (idFoo != idBaz) << std::endl; // print 1
</code>```

Body:
I have this code, which works... so far so good :

struct _TYPEIDSTR {};
typedef _TYPEIDSTR *TYPE_ID;
template<class T> _TYPEIDSTR _TYPE_ID;

template<class T> constexpr TYPE_ID getTypeID() { return &_TYPE_ID<T>; }

calling in main like this :

constexpr TYPE_ID id1 = getTypeID<int>();
constexpr TYPE_ID id2 = getTypeID<int>();
RLOG("ID1 : " << id1);
RLOG("ID2 : " << id2);

works perfectly, and I've an unique identifier for each type used in getTypeID() call.
Now I want to build a struct that brings some info about a function :

template<typename RES, typename... ARGS> struct _GlobalOverlayInfo {
    bool _member;
    RES(*_fn)(ARGS...);
    size_t _nargs;
    TYPE_ID _argIDs;
    constexpr _GlobalOverlayInfo(RES(*fn)(ARGS...)) :
    _member(false),
    _fn(fn),
    _nargs(sizeof...(ARGS)),
    _argIDs {getTypeID<ARGS>()...}
    {}
};

template<typename RES, typename... ARGS>
constexpr auto getOverlayInfo(RES(*fn)(ARGS...)) {
    return & _GlobalOverlayInfo<RES, ARGS...>(fn); <<---ERROR1
}

using this function :

int pippo(int x) {
    return 0;
}

and calling like this :

constexpr auto x = getOverlayInfo(pippo); <<--- ERROR2

I get the 2 marked errors; ERROR1 is "taking address of a temporary" (but shouldn't it a compile time evaluation ?) and ERROR2 is "error: ‘&’ is not a constant expression".
I tried in many ways, but I couldn't success. Where I am wrong ?
Is there a way (in C++11) to achieve this result ?
All I need is a pointer to an unique structure generated for each RES and ARGS... parameters.

Body:
Not sure to understand what you want to do.

Anyway, if you want to works with C++11 (and avoid C++14 or newer) you can't use a template variable like

template<class T> _TYPEIDSTR _TYPE_ID;

that is a C++14 feature.

If you want a constexpr template identifier, you could use std::type_index, that is available starting from C++11.

If you can't use std::type_index... well, the best I can imagine is a template class with a static variable and a static method that return the pointer to it.

Something like

template <typename>
struct typeId
 {
   static constexpr int const val {};

   static constexpr int const * getId ()
    { return &val; }
 };

template <typename T>
constexpr int const typeId<T>::val;

You can get constexpr values and you can check that are differents

constexpr auto const idInt = typeId<int>::getId();
constexpr auto const idLong = typeId<long>::getId();

std::cout << (idInt != idLong) << std::endl; // print 1

For the function case...

Functions has types and single functions can be template parameters.

So if you want a constexpr identifier for a function, you can create a wrapper as follows

template <typename Ft, Ft f>
struct funcT
 { };

and, using the preceding typeId, get different constexpr values from different functions as follows

int  foo (int) { return 0; }
int  bar (int) { return 0; }
long baz (int, long, long long) { return 0L; }

// ...

constexpr auto idFoo = typeId<funcT<decltype(&foo), &foo>>::getId();
constexpr auto idBar = typeId<funcT<decltype(&bar), &bar>>::getId();
constexpr auto idBaz = typeId<funcT<decltype(&baz), &baz>>::getId();

std::cout << (idFoo != idBar) << std::endl; // print 1
std::cout << (idFoo != idBaz) << std::endl; // print 1


问:
Exiting from a Batch Script
I have a batch script which I am using to run a C# application with command line arguments
like :  application.exe arg1 arg2 arg3.

How can I exit from the batch script on some condition occured due to execution of application.exe arg1 arg2 arg3.

```<code>example my batch script looks like this
:start
echo cycle %count%
application.exe arg1 arg2
application.exe arg3 arg4
..
..
..
..
some 10 commands
count = count+1
if %count% < 10 goto start
:endloop
</code>```

depending on some condition I want to exit from the batch script (say application.exe arg6 arg7 which calls some functionXX() on the return value of functionXX()?

How can I accomplish this?

答:
You should most likely use exit /b (More info here) or goto :eof where :eof means end of file, both work here, it's just a matter of personal preference

EDIT: For the record, exit /b and goto :eof, if in a subroutine, will only exit the subroutine

EDIT #2: exit /b can cause problems, so do use goto :eof IF it is a subroutine, if not, you should be fine

Title: Exiting from a Batch Script

Body:
I have a batch script which I am using to run a C# application with command line arguments
like :  application.exe arg1 arg2 arg3.

How can I exit from the batch script on some condition occured due to execution of application.exe arg1 arg2 arg3.

example my batch script looks like this
:start
echo cycle %count%
application.exe arg1 arg2
application.exe arg3 arg4
..
..
..
..
some 10 commands
count = count+1
if %count% < 10 goto start
:endloop

depending on some condition I want to exit from the batch script (say application.exe arg6 arg7 which calls some functionXX() on the return value of functionXX()?

How can I accomplish this?


问:
Set a number of spinners to default
I have 18 spinners in a GridLayout with values assigned to each one manually(no adapters) in the activity layout. Now I want a "clear button" to call a method:"onClickClear" that sets each spinner to the default value.

Is there a way to do that without writing a reference to 18 spinners and using setSelection(0). I'm pretty new to Android and this is a proof of concept project I'm doing :)

答:
Just add all of them to a Spinner array, something like Spinner[] spinners = new Spinner[18]; then spinners[0] = findViewById...
That way you can set them all to the default value easily with a for loop.
for (Spinner spinner : spinners)
spinner.setSelection(0)</p>

Title: Set a number of spinners to default


问:
Duplicate results on JOIN
Here is my question : I am trying to get all the games of a class. the class can host a game, or have a game in another class.

games table have : guest_class (ID of class) and host_class(ID of class)

classes table have : id_class (ID of class)

An example I am trying to get the games of the class 1.
There are only 2 games with class 1.

```<code>id_game: 1, id_class: 1, host_class: 3, guest_class: 1,
id_game: 2, id_class: 1, host_class: 1, guest_class: 6,
</code>```

Why am I getting duplicated results ?

QUERY

```<code>var classID = Number(req.query.searchValue);
var query = `SELECT * FROM games g
LEFT JOIN classes c ON c.id_class = g.host_class OR c.id_class = g.guest_class
WHERE ( g.host_class = ? OR g.guest_class = ? )`;
con2.query(query, [classID,classID] , function (err, result) {
</code>```

RESULT

```<code>[ RowDataPacket {
    id_game: 1,
    date: 2017-12-04T23:00:00.000Z,
    host_class: 3,
    guest_class: 1,
    host_score: 34,
    guest_score: 74,
    tournament_id: 0,
    group_id: 1,
    statistics: '',
    incidents: '',
    id_class: 1},
  RowDataPacket {
    id_game: 1,
    date: 2017-12-04T23:00:00.000Z,
    host_class: 3,
    guest_class: 1,
    host_score: 34,
    guest_score: 74,
    tournament_id: 0,
    group_id: 1,
    statistics: '',
    incidents: '',
    id_class: 3},
  RowDataPacket {
    id_game: 2,
    date: 2017-11-30T23:00:00.000Z,
    host_class: 1,
    guest_class: 6,
    host_score: 84,
    guest_score: 57,
    tournament_id: 0,
    group_id: 1,
    statistics: '',
    incidents: '',
    id_class: 1},
  RowDataPacket {
    id_game: 2,
    date: 2017-11-30T23:00:00.000Z,
    host_class: 1,
    guest_class: 6,
    host_score: 84,
    guest_score: 57,
    tournament_id: 0,
    group_id: 1,
    statistics: '',
    incidents: '',
    id_class: 6} ]
</code>```

答:
I am trying to get the games of the class 1. There are only 2 games with class 1.

You dont need a join for that:

```<code>SELECT *
FROM games g
WHERE g.host_class = ? OR g.guest_class = ?
</code>```

Title: Duplicate results on JOIN

Body:
Here is my question : I am trying to get all the games of a class. the class can host a game, or have a game in another class.

games table have : guest_class (ID of class) and host_class(ID of class)

classes table have : id_class (ID of class)

An example I am trying to get the games of the class 1.
There are only 2 games with class 1.

id_game: 1, id_class: 1, host_class: 3, guest_class: 1,
id_game: 2, id_class: 1, host_class: 1, guest_class: 6,

Why am I getting duplicated results ?

QUERY

var classID = Number(req.query.searchValue);
var query = `SELECT * FROM games g
LEFT JOIN classes c ON c.id_class = g.host_class OR c.id_class = g.guest_class
WHERE ( g.host_class = ? OR g.guest_class = ? )`;
con2.query(query, [classID,classID] , function (err, result) {

RESULT

[ RowDataPacket {
    id_game: 1,
    date: 2017-12-04T23:00:00.000Z,
    host_class: 3,
    guest_class: 1,
    host_score: 34,
    guest_score: 74,
    tournament_id: 0,
    group_id: 1,
    statistics: '',
    incidents: '',
    id_class: 1},
  RowDataPacket {
    id_game: 1,
    date: 2017-12-04T23:00:00.000Z,
    host_class: 3,
    guest_class: 1,
    host_score: 34,
    guest_score: 74,
    tournament_id: 0,
    group_id: 1,
    statistics: '',
    incidents: '',
    id_class: 3},
  RowDataPacket {
    id_game: 2,
    date: 2017-11-30T23:00:00.000Z,
    host_class: 1,
    guest_class: 6,
    host_score: 84,
    guest_score: 57,
    tournament_id: 0,
    group_id: 1,
    statistics: '',
    incidents: '',
    id_class: 1},
  RowDataPacket {
    id_game: 2,
    date: 2017-11-30T23:00:00.000Z,
    host_class: 1,
    guest_class: 6,
    host_score: 84,
    guest_score: 57,
    tournament_id: 0,
    group_id: 1,
    statistics: '',
    incidents: '',
    id_class: 6} ]

Body:
I am trying to get the games of the class 1. There are only 2 games with class 1.

You dont need a join for that:

SELECT *
FROM games g
WHERE g.host_class = ? OR g.guest_class = ?


问:
In Chrome DevTools, can I turn off stacking of console.log messages?
I have Javascript code that loops through an array, and I have some quick console.log() calls that either prints "Not found" or "Found!" as the loop examines each element in the array for something.

I noticed that in the Chrome DevTools console tab, it stacks thee same console.log message together.  For example, if the first 4 iterations of the loop result in "Not found" the console tab shows:

```<code>(4) Not found
</code>```

Is there any way to see the console.log message as separate lines?

答:
This was asked ages ago, but to anyone who finds this, the quickest and easiest way to do this is to add a TimeStamp to the log: </p>

```<code>console.log("Found:" + new Date());
</code>```

Body:
I have Javascript code that loops through an array, and I have some quick console.log() calls that either prints "Not found" or "Found!" as the loop examines each element in the array for something.

I noticed that in the Chrome DevTools console tab, it stacks thee same console.log message together.  For example, if the first 4 iterations of the loop result in "Not found" the console tab shows:

(4) Not found

Is there any way to see the console.log message as separate lines?

Body:
This was asked ages ago, but to anyone who finds this, the quickest and easiest way to do this is to add a TimeStamp to the log:

console.log("Found:" + new Date());


问:
Custom MaxmindDB (geoip2) with Private IPs
How to create a custom Maxmind database with PRIVATE IPs address.

I need something like this Customizing Maxmind DB.

I tried to following this Building Your Own MMDB Database for Fun and Profit . So I changed the PERL script to the following:

```<code>#!/usr/bin/env perl

use strict;
use warnings;
use feature qw( say );

use MaxMind::DB::Writer::Tree;
use Net::Works::Network;

my $filename = 'users.mmdb';

# Your top level data structure will always be a map (hash).  The MMDB format
# is strongly typed.  Describe your data types here.
# See https://metacpan.org/pod/MaxMind::DB::Writer::Tree#DATA-TYPES

my %types = (
    latitude => 'uint32',
    longitude     => 'uint32',
    city         => 'utf8_string',
    country     => 'utf_string',
);

my $tree = MaxMind::DB::Writer::Tree->new(

    # "database_type" is some arbitrary string describing the database.  At
    # MaxMind we use strings like 'GeoIP2-City', 'GeoIP2-Country', etc.
    database_type => 'My-IP-Data',

    # "description" is a hashref where the keys are language names and the
    # values are descriptions of the database in that language.
    description =>
        { en => 'My database of IP data', fr => q{Mon Data d'IP}, },

    # "ip_version" can be either 4 or 6
    ip_version => 4,

    # add a callback to validate data going in to the database
    map_key_type_callback => sub { $types{ $_[0] } },

    # "record_size" is the record size in bits.  Either 24, 28 or 32.
    record_size => 24,
);

my %address_for_employee = (
    '10.1.0.0/16' => {
          latitude => -12.9608,
        longitude      => 40.5078,
        city         => 'Maputo',
    country         => 'Mozambique',
    },
    '10.2.0.0/16' => {
        latitude => -25.0519,
        longitude      => 33.6442,
        city         => 'Gaza',
    country         => 'Mozambique',
    },
);

for my $address ( keys %address_for_employee ) {

    # Create one network and insert it into our database
    my $network = Net::Works::Network->new_from_string( string => $address );

    $tree->insert_network( $network, $address_for_employee{$address} );
}

# Write the database to disk.
open my $fh, '>:raw', $filename;
$tree->write_tree( $fh );
close $fh;

say "$filename has now been created";
</code>```

But no luck.
Now Im getting the following error :
Iteration is not currently allowed in trees with no nodes. Record type: empty at /usr/local/lib/perl/5.14.2/MaxMind/DB/Writer/Tree.pm line 292.

Can anybody help me creating a GEOIP2 DB with private ip address?

答:
I used the remove_reserved_networks parameter in the constructor.

```<code>my $tree = MaxMind::DB::Writer::Tree->new(

# "database_type" is some arbitrary string describing the database.  At
# MaxMind we use strings like 'GeoIP2-City', 'GeoIP2-Country', etc.
database_type => 'GeoIP2-City',

# "description" is a hashref where the keys are language names and the
# values are descriptions of the database in that language.
description =>
    { en => 'IP-Ranges', de => q{IP-Bereiche}, },

# "ip_version" can be either 4 or 6
ip_version => 4,

# add a callback to validate data going in to the database
map_key_type_callback => sub { $types{ $_[0] } },

# "record_size" is the record size in bits.  Either 24, 28 or 32.
record_size => 24,

remove_reserved_networks => 0,
);
</code>```

Body:
How to create a custom Maxmind database with PRIVATE IPs address.

I need something like this Customizing Maxmind DB.

I tried to following this Building Your Own MMDB Database for Fun and Profit . So I changed the PERL script to the following:

#!/usr/bin/env perl

use strict;
use warnings;
use feature qw( say );

use MaxMind::DB::Writer::Tree;
use Net::Works::Network;

my $filename = 'users.mmdb';

# Your top level data structure will always be a map (hash).  The MMDB format
# is strongly typed.  Describe your data types here.
# See https://metacpan.org/pod/MaxMind::DB::Writer::Tree#DATA-TYPES

my %types = (
    latitude => 'uint32',
    longitude     => 'uint32',
    city         => 'utf8_string',
    country     => 'utf_string',
);

my $tree = MaxMind::DB::Writer::Tree->new(

    # "database_type" is some arbitrary string describing the database.  At
    # MaxMind we use strings like 'GeoIP2-City', 'GeoIP2-Country', etc.
    database_type => 'My-IP-Data',

    # "description" is a hashref where the keys are language names and the
    # values are descriptions of the database in that language.
    description =>
        { en => 'My database of IP data', fr => q{Mon Data d'IP}, },

    # "ip_version" can be either 4 or 6
    ip_version => 4,

    # add a callback to validate data going in to the database
    map_key_type_callback => sub { $types{ $_[0] } },

    # "record_size" is the record size in bits.  Either 24, 28 or 32.
    record_size => 24,
);

my %address_for_employee = (
    '10.1.0.0/16' => {
          latitude => -12.9608,
        longitude      => 40.5078,
        city         => 'Maputo',
    country         => 'Mozambique',
    },
    '10.2.0.0/16' => {
        latitude => -25.0519,
        longitude      => 33.6442,
        city         => 'Gaza',
    country         => 'Mozambique',
    },
);

for my $address ( keys %address_for_employee ) {

    # Create one network and insert it into our database
    my $network = Net::Works::Network->new_from_string( string => $address );

    $tree->insert_network( $network, $address_for_employee{$address} );
}

# Write the database to disk.
open my $fh, '>:raw', $filename;
$tree->write_tree( $fh );
close $fh;

say "$filename has now been created";

But no luck.
Now Im getting the following error :
Iteration is not currently allowed in trees with no nodes. Record type: empty at /usr/local/lib/perl/5.14.2/MaxMind/DB/Writer/Tree.pm line 292.

Can anybody help me creating a GEOIP2 DB with private ip address?

Body:
I used the remove_reserved_networks parameter in the constructor.

my $tree = MaxMind::DB::Writer::Tree->new(

# "database_type" is some arbitrary string describing the database.  At
# MaxMind we use strings like 'GeoIP2-City', 'GeoIP2-Country', etc.
database_type => 'GeoIP2-City',

# "description" is a hashref where the keys are language names and the
# values are descriptions of the database in that language.
description =>
    { en => 'IP-Ranges', de => q{IP-Bereiche}, },

# "ip_version" can be either 4 or 6
ip_version => 4,

# add a callback to validate data going in to the database
map_key_type_callback => sub { $types{ $_[0] } },

# "record_size" is the record size in bits.  Either 24, 28 or 32.
record_size => 24,

remove_reserved_networks => 0,
);


问:
C# VS 2013 Error 02019: Invalid target type for /target: must specify 'exe', 'winexe', 'library', 'module', 'appcontainerexe' or 'winmdobj' CSC
I work on a website that uses various class libraries that are occasionally updated. One of the libraries is a sqlproj file and I believe it was made with VS2010. It is a dependency for other libraries and I'm not able to build/rebuild my solution because I keep getting this error, thus the DLLs will not generate. When I first open the project in VS2013, I get a migration report that opens in my browser. But the migration states that it's successful. When I try building the project, I get the error:

Error 1   02019: Invalid target type for /target: must specify 'exe', 'winexe', 'library', 'module', 'appcontainerexe' or 'winmdobj'  CSC

I've tried to follow some of the recommendations on this question with essentially the same issue, but have been unsuccessful. Project fails to load due to missing SqlServer.targets file after upgrading to Visual Studio 2013 It seems like there are some unresolved streams in that question as well.

Any help would be great. Happy to provide more details and/or edit the question to make it more generalized. Thanks in advance.

答:
I had the same error message but on VS2017 in .sqlproj.
It helped to add DefaultTargets argument in .targets file.</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="SetDacVersionToAssemblyVersion" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <Import Project="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\SSDT\Microsoft.Data.Tools.Schema.SqlTasks.targets" />

  <Target Name="SetDacVersionToAssemblyVersion" AfterTargets="CoreCompile" Condition=" '$(EnableDacVersionFromAssembly)' == 'True' ">
    <GetAssemblyIdentity AssemblyFiles="$(IntermediateTargetFullFileName)">
      <Output TaskParameter="Assemblies" PropertyName="IntermediateTargetAssembly" />
    </GetAssemblyIdentity>
    <PropertyGroup>
      <DacVersion>$(IntermediateTargetAssembly.Split(',')[1].Split('=')[1])</DacVersion>
    </PropertyGroup>
  </Target>

</Project>
</code>```

Body:
I had the same error message but on VS2017 in .sqlproj.
It helped to add DefaultTargets argument in .targets file.

<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="SetDacVersionToAssemblyVersion" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <Import Project="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\SSDT\Microsoft.Data.Tools.Schema.SqlTasks.targets" />

  <Target Name="SetDacVersionToAssemblyVersion" AfterTargets="CoreCompile" Condition=" '$(EnableDacVersionFromAssembly)' == 'True' ">
    <GetAssemblyIdentity AssemblyFiles="$(IntermediateTargetFullFileName)">
      <Output TaskParameter="Assemblies" PropertyName="IntermediateTargetAssembly" />
    </GetAssemblyIdentity>
    <PropertyGroup>
      <DacVersion>$(IntermediateTargetAssembly.Split(',')[1].Split('=')[1])</DacVersion>
    </PropertyGroup>
  </Target>

</Project>


问:
How to create folder/file that name ended with a dot in Windows?
I wanna create a file that file name end with a dot in Windows.

use "mkdir a.", but i only create a folder named with "a"

And I just wonder how to write a function to create such directory, thanks

答:
```<code>mkdir \\?\c:\test2.
</code>```

this creates a folder ending with (.)
provide drive letter

Body:
mkdir \\?\c:\test2.

this creates a folder ending with (.)
provide drive letter


问:
UpdatePanel does not fire on first click of link button
I have an update panel on an .aspx page. Within this aspx page I have a few ascx controls. One of the controls has my link button. When that button is pressed I'd expect to get the results I intend to get, but I expect to not see a page flicker or see the page postback. It does both. After I change some search information and click the link button again the page does an async postback (which is what I expected on the first click). After running this sequence through fiddler I see that the first time I click the button I am missing some information that is included in all subsequent requests.

ctl00$ScriptManager1=ctl00$cplContents$updatePanelOrderSearch|ctl00$cplContents$ucOrderSearchControl$btnRange&EVENTTARGET=ctl00%24cplContents%24ucOrderSearchControl%24btnRange&.....

Above is what I get on clicks 2, 3, etc.. This is not in the request when I click on the link button the very first time. Im wondering if this is why I am get a full, non async postback the first time.

Any help would be appreciated. My update panel code is below.

```<code><asp:UpdatePanel ID="updatePanelOrderSearch" runat="server" UpdateMode="Always" ChildrenAsTriggers="true">
    <ContentTemplate>
        <uc:control1 "this control has the link button" />
        <hr />
        <div id="SearchResults">
            <div id="SearchResultsMessage">
                <asp:Literal ID="lblMessage" Text="No orders found" Visible="false" runat="server" />
            </div>
            <uc:contorl 2 />
        </div>
        <uc: control3 />
    </ContentTemplate>
</asp:UpdatePanel>
</code>```

Thanks

答: this was an issue from months ago and we wound up not using this solution</p>

Body:
I have an update panel on an .aspx page. Within this aspx page I have a few ascx controls. One of the controls has my link button. When that button is pressed I'd expect to get the results I intend to get, but I expect to not see a page flicker or see the page postback. It does both. After I change some search information and click the link button again the page does an async postback (which is what I expected on the first click). After running this sequence through fiddler I see that the first time I click the button I am missing some information that is included in all subsequent requests.

ctl00$ScriptManager1=ctl00$cplContents$updatePanelOrderSearch|ctl00$cplContents$ucOrderSearchControl$btnRange&EVENTTARGET=ctl00%24cplContents%24ucOrderSearchControl%24btnRange&.....

Above is what I get on clicks 2, 3, etc.. This is not in the request when I click on the link button the very first time. Im wondering if this is why I am get a full, non async postback the first time.

Any help would be appreciated. My update panel code is below.

<asp:UpdatePanel ID="updatePanelOrderSearch" runat="server" UpdateMode="Always" ChildrenAsTriggers="true">
    <ContentTemplate>
        <uc:control1 "this control has the link button" />

                <asp:Literal ID="lblMessage" Text="No orders found" Visible="false" runat="server" />

            <uc:contorl 2 />

        <uc: control3 />
    </ContentTemplate>
</asp:UpdatePanel>

Thanks


问:
Error: No value for "ColumnName". Get JSON value in Android
I want to get f_index value from JSON into my Android App. I am getting an error "No value for f_index.

```<code>W/System.err: org.json.JSONException: No value for f_index
</code>```

If I remove the below line then I am able to get the lat, long and is_local values properly and further use them.

```<code>ill_id_data.add(ill_jo.getInt("f_index"));
</code>```

I am not able to understand what is going wrong here?

JSON received in the app which I pass to parse method.

```<code>{
"server_response": [{
    "f_index": "3",
    "lat": "21.9159",
    "long": "78.1021",
    "is_local": "0"
}, {
    "f_index": "6",
    "lat": "25.0751",
    "long": "54.9476",
    "is_local": "0"
}, {
    "f_index": "7",
    "lat": "14.6773",
    "long": "75.542",
    "is_local": "1"
}, {
    "f_index": "8",
    "lat": "21.9159",
    "long": "78.1021",
    "is_local": "0"
}, {
    "f_index": "9",
    "lat": "25.8079",
    "long": "86.0449",
    "is_local": "1"
}]
}
</code>```

Code for parsing the JSON in my App.

```<code>ArrayList<Double> ill_lat_data = new ArrayList<Double>(3);
ArrayList<Double> ill_long_data = new ArrayList<Double>(3);
ArrayList<Interger> ill_id_data = new ArrayList<Integer>(3);
ArrayList<Integer> ill_is_local_data = new ArrayList<Integer>(3);

public void parseIndexLatLngJSON() {

    int count_ill = 0;

    try {
        ill_json_object = new JSONObject(json_index_latlng);
        ill_json_array = gm_json_object.getJSONArray("server_response");

        while (count_ill < ill_json_array.length()) {
            JSONObject ill_jo = ill_json_array.getJSONObject(count_ill);

            ill_id_data.add(ill_jo.getInt("f_index"));
            Log.d("tag_last_check", String.valueOf(ill_jo.getInt("f_index")));
            ill_lat_data.add(ill_jo.getDouble("lat"));
            ill_is_local_data.add(ill_jo.getInt("is_local"));
            ill_long_data.add(ill_jo.getDouble("long"));

            count_ill++;
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
</code>```

This is my php file.

```<code>$sql="SELECT id,lat,`long` FROM newsphere_one WHERE lat != 0 OR `long` != 0;";

$con=mysqli_connect($host,$hostname,$password,$db);

$result = mysqli_query($con,$sql);

$response = array();

while($row=mysqli_fetch_array($result)){
array_push($response, array("f_index" => $row[0],"lat" => $row[1],"long" => $row[2],"is_local" => $row[3]));
}

echo json_encode(array("server_response"=>$response));
</code>```

答:
First of all,  </p>

```<code>ill_id_data.add(ill_jo.getInt("f_index"));
</code>```

<p>tries to get a integer, while in your json it's defined as a string.
Try and get the string then cast it to int. Try to use: </p>

```<code>Integer.parseInt()
</code>```

Body:
I want to get f_index value from JSON into my Android App. I am getting an error "No value for f_index.

W/System.err: org.json.JSONException: No value for f_index

If I remove the below line then I am able to get the lat, long and is_local values properly and further use them.

ill_id_data.add(ill_jo.getInt("f_index"));

I am not able to understand what is going wrong here?

JSON received in the app which I pass to parse method.

{
"server_response": [{
    "f_index": "3",
    "lat": "21.9159",
    "long": "78.1021",
    "is_local": "0"
}, {
    "f_index": "6",
    "lat": "25.0751",
    "long": "54.9476",
    "is_local": "0"
}, {
    "f_index": "7",
    "lat": "14.6773",
    "long": "75.542",
    "is_local": "1"
}, {
    "f_index": "8",
    "lat": "21.9159",
    "long": "78.1021",
    "is_local": "0"
}, {
    "f_index": "9",
    "lat": "25.8079",
    "long": "86.0449",
    "is_local": "1"
}]
}

Code for parsing the JSON in my App.

ArrayList<Double> ill_lat_data = new ArrayList<Double>(3);
ArrayList<Double> ill_long_data = new ArrayList<Double>(3);
ArrayList<Interger> ill_id_data = new ArrayList<Integer>(3);
ArrayList<Integer> ill_is_local_data = new ArrayList<Integer>(3);

public void parseIndexLatLngJSON() {

    int count_ill = 0;

    try {
        ill_json_object = new JSONObject(json_index_latlng);
        ill_json_array = gm_json_object.getJSONArray("server_response");

        while (count_ill < ill_json_array.length()) {
            JSONObject ill_jo = ill_json_array.getJSONObject(count_ill);

            ill_id_data.add(ill_jo.getInt("f_index"));
            Log.d("tag_last_check", String.valueOf(ill_jo.getInt("f_index")));
            ill_lat_data.add(ill_jo.getDouble("lat"));
            ill_is_local_data.add(ill_jo.getInt("is_local"));
            ill_long_data.add(ill_jo.getDouble("long"));

            count_ill++;
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

This is my php file.

$sql="SELECT id,lat,`long` FROM newsphere_one WHERE lat != 0 OR `long` != 0;";

$con=mysqli_connect($host,$hostname,$password,$db);

$result = mysqli_query($con,$sql);

$response = array();

while($row=mysqli_fetch_array($result)){
array_push($response, array("f_index" => $row[0],"lat" => $row[1],"long" => $row[2],"is_local" => $row[3]));
}

echo json_encode(array("server_response"=>$response));

Body:
First of all,

ill_id_data.add(ill_jo.getInt("f_index"));

tries to get a integer, while in your json it's defined as a string.
Try and get the string then cast it to int. Try to use:

Integer.parseInt()


问:
C++ using derived class variable in base class
```<code>The below is my code design
class D;
class A {
   D *d;
   class B:public C {
   somefunctions();
   }
}

class C {
    //I need to use class D variables inside Class C
}
</code>```

Whatever I do inside the Class C for bringing Class D variables,
it is throwing Invalid use of Incomplete 'Class D' and Forward declaration of 'class D'. The thing is we can't move the class positions.
Need your help, Please give suggestions with examples.
Thanks in advance for your help

答:
A class definition depends on the types of its sub objects. If C has a member of type D, then D has to be defined before C. If D is defined after C, then C must not depend on D.

Types typically don't depend on functions, so if a member function of C depends on D, the solution is simple:

Define C

Define D

Define the member function of C that depends on D

Body:
The below is my code design
class D;
class A {
   D *d;
   class B:public C {
   somefunctions();
   }
}

class C {
    //I need to use class D variables inside Class C
}

Whatever I do inside the Class C for bringing Class D variables,
it is throwing Invalid use of Incomplete 'Class D' and Forward declaration of 'class D'. The thing is we can't move the class positions.
Need your help, Please give suggestions with examples.
Thanks in advance for your help