问:
Why does `is` return False even though id's are identical?
I already looked at this question, but I don't really get why the two id() calls return an identical value, while the is comparison returns False.

>>> [2,2,2] + [1] == [2,2,2,1]
True
>>> [2,2,2] + [1] is [2,2,2,1]
False
>>> id([2,2,2] + [1])
4396847688
>>> id([2,2,2,1])
4396847688
```

To be sure, I did expect the two comparisons to return True and False as they did, I just don't get why the ids are not different.

答:
Just re-entering my comment as "an answer":

Simply because the same memory is reused for the objects: in the last two statements, the lifetimes of the objects whose id's you're obtaining do not overlap, so Python is free to (re)use the same memory for them.

Body:
I already looked at this question, but I don't really get why the two id() calls return an identical value, while the is comparison returns False.

>>> [2,2,2] + [1] == [2,2,2,1]
True
>>> [2,2,2] + [1] is [2,2,2,1]
False
>>> id([2,2,2] + [1])
4396847688
>>> id([2,2,2,1])
4396847688

To be sure, I did expect the two comparisons to return True and False as they did, I just don't get why the ids are not different.


来源: stackexchange

问:
requestLocationisn't calling didUpdateLocations
First of all: I know there are similar threads here on So, but nothing thats suggested works for me.

Here is what i am trying to do:
I want to have a PositionController(Class) that controls the users current position and gives interfaces for other classes,ViewControllers etc to use the information.

Currently i have this code implemented:

```<code>import Foundation
import CoreLocation

class PositionController: CLLocationManager, CLLocationManagerDelegate{

    let locationManager: CLLocationManager

    override init() {
        self.locationManager = CLLocationManager()
        print("---------------Init---------------------------")
    }

    func getPosition(){

        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        locationManager.desiredAccuracy = kCLLocationAccuracyKilometer
        locationManager.requestLocation()
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error)
     }

    func locationManager(_ mnager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        print(locations)
    }
}
</code>```

Note that the print statements in the delegate functions are only placeholders at the moment.
Also note that i want the getPosition-Method to be called from outside ViewControllers. But when i call the function it just goes through the codeblock without calling neither of the two delegate functions at the end.

Further i have "Privacy - Location When In Use Description" and
"Location Usage Description" added to my plist.
I really dont know what i am missing or doing wrong, so all help is appreciated

EDIT:

```<code>import UIKit
import GoogleMaps
import GoogleMaps

class MapViewController: UIViewController, CLLocationManagerDelegate {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    // For use in foreground

    print("-----------------------In------------------------")
    let positionController = PositionController()
    positionController.getPosition()
    print("-----------------------Out------------------------")

    let camera = GMSCameraPosition.camera(withLatitude: 48.137154
                                          longitude: 11.576124, zoom:12)
    let mapView = GMSMapView.map(withFrame: CGRect.zero, camera:camera)
    let marker = GMSMarker()

    marker.position = camera.target
    marker.snippet = "Munich"
    marker.appearAnimation = GMSMarkerAnimation.pop
    marker.map = mapView

    self.view = mapView

}
</code>```

答:
Your problem is that you are creating an instance of PositionController as a local variable in viewDidLoad.  viewDidLoad will exit, deallocating the PositionController instance before the location callback gets a chance to execute (Determine location can take quite a few seconds or even longer).

If you use a property to hold your PositionController reference then it will have the same lifetime as your view controller object:

```<code>class MapViewController: UIViewController, CLLocationManagerDelegate {

    let positionController = PositionController()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        // For use in foreground

        print("-----------------------In------------------------")
        self.positionController.getPosition()
        print("-----------------------Out------------------------")

        let camera = GMSCameraPosition.camera(withLatitude: 48.137154
                                              longitude: 11.576124, zoom:12)
        let mapView = GMSMapView.map(withFrame: CGRect.zero, camera:camera)
        let marker = GMSMarker()

        marker.position = camera.target
        marker.snippet = "Munich"
        marker.appearAnimation = GMSMarkerAnimation.pop
        marker.map = mapView

        self.view = mapView

    }
</code>```

You probably want to have a single instance of PositionController in your app.  You could make it a property of your AppDelegate or make it a singleton in its own right (Singletons can create issues with mockability and testing, so I will leave it up to you to decide how you want to do it).

ContentLicense: CC BY-SA 3.0

Body:
First of all: I know there are similar threads here on So, but nothing thats suggested works for me.

Here is what i am trying to do:
I want to have a PositionController(Class) that controls the users current position and gives interfaces for other classes,ViewControllers etc to use the information.

Currently i have this code implemented:

import Foundation
import CoreLocation

class PositionController: CLLocationManager, CLLocationManagerDelegate{

    let locationManager: CLLocationManager

    override init() {
        self.locationManager = CLLocationManager()
        print("---------------Init---------------------------")
    }

    func getPosition(){

        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        locationManager.desiredAccuracy = kCLLocationAccuracyKilometer
        locationManager.requestLocation()
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error)
     }

    func locationManager(_ mnager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        print(locations)
    }
}

Note that the print statements in the delegate functions are only placeholders at the moment.
Also note that i want the getPosition-Method to be called from outside ViewControllers. But when i call the function it just goes through the codeblock without calling neither of the two delegate functions at the end.

Further i have "Privacy - Location When In Use Description" and
"Location Usage Description" added to my plist.
I really dont know what i am missing or doing wrong, so all help is appreciated

EDIT:

import UIKit
import GoogleMaps
import GoogleMaps

class MapViewController: UIViewController, CLLocationManagerDelegate {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    // For use in foreground

    print("-----------------------In------------------------")
    let positionController = PositionController()
    positionController.getPosition()
    print("-----------------------Out------------------------")

    let camera = GMSCameraPosition.camera(withLatitude: 48.137154
                                          longitude: 11.576124, zoom:12)
    let mapView = GMSMapView.map(withFrame: CGRect.zero, camera:camera)
    let marker = GMSMarker()

    marker.position = camera.target
    marker.snippet = "Munich"
    marker.appearAnimation = GMSMarkerAnimation.pop
    marker.map = mapView

    self.view = mapView

}

Body:
Your problem is that you are creating an instance of PositionController as a local variable in viewDidLoad.  viewDidLoad will exit, deallocating the PositionController instance before the location callback gets a chance to execute (Determine location can take quite a few seconds or even longer).

If you use a property to hold your PositionController reference then it will have the same lifetime as your view controller object:

class MapViewController: UIViewController, CLLocationManagerDelegate {

    let positionController = PositionController()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        // For use in foreground

        print("-----------------------In------------------------")
        self.positionController.getPosition()
        print("-----------------------Out------------------------")

        let camera = GMSCameraPosition.camera(withLatitude: 48.137154
                                              longitude: 11.576124, zoom:12)
        let mapView = GMSMapView.map(withFrame: CGRect.zero, camera:camera)
        let marker = GMSMarker()

        marker.position = camera.target
        marker.snippet = "Munich"
        marker.appearAnimation = GMSMarkerAnimation.pop
        marker.map = mapView

        self.view = mapView

    }

You probably want to have a single instance of PositionController in your app.  You could make it a property of your AppDelegate or make it a singleton in its own right (Singletons can create issues with mockability and testing, so I will leave it up to you to decide how you want to do it).


问:
Why does the object created without using "new" operator gets the same address
Going through this question, one answer said the object created are destroyed outside their scope, To get this concept clearly I wrote the following code:

```<code>#include <iostream>

using namespace std;

struct Node{
    int val;
    Node *next;
    Node(int x) : val(x) , next(NULL){}
};

int main(){
    for(int i=0;i<10;i++){
        int someval = rand()%100;
        Node somenode = Node(someval);
        printf("Address for object %d is %p \n",i+1, &somenode);
    }
}
</code>```

I got the following output:

```<code>Address for object 1 is 0x7ffc32ff26b0
Address for object 2 is 0x7ffc32ff26b0
Address for object 3 is 0x7ffc32ff26b0
Address for object 4 is 0x7ffc32ff26b0
Address for object 5 is 0x7ffc32ff26b0
Address for object 6 is 0x7ffc32ff26b0
Address for object 7 is 0x7ffc32ff26b0
Address for object 8 is 0x7ffc32ff26b0
Address for object 9 is 0x7ffc32ff26b0
Address for object 10 is 0x7ffc32ff26b0
</code>```

I understand that each object is destroyed every time the loop iterates and a new object is created; but why do all of them have the same address. This problem occurred to me when I was creating a linked list and I did not use the new operator to create the object instead just used the same code, and the list always pointed to the same node and I ran into an infinite loop. Why is the same address allocated to each object?

答:
This has to do with local variables and scope. Since the variable somenode is declared inside of the {} brackets of the for loop, it's scope is local to that for loop. That is to say, it exists during a single iteration of the for loop and then it goes out of scope before the beginning of the next iteration.

Compilers as a general try to be efficient. After the first iteration of the for loop the address 0x7ffc32ff26b0 points to a location in memory that is big enough to store a Node structure. The compiler also knows that this memory is unused (it went out of scope) so it figures it can just re-use the same memory location. In other words, although the structures occupy the same RAM memory, they are all independent and unrelated to each other.

This behaviour is not guaranteed and you should not rely on it, it's simply an attempt from the compiler to keep the final assembled code as simple and efficient as possible.

Body:
Going through this question, one answer said the object created are destroyed outside their scope, To get this concept clearly I wrote the following code:

#include <iostream>

using namespace std;

struct Node{
    int val;
    Node *next;
    Node(int x) : val(x) , next(NULL){}
};

int main(){
    for(int i=0;i<10;i++){
        int someval = rand()%100;
        Node somenode = Node(someval);
        printf("Address for object %d is %p \n",i+1, &somenode);
    }
}

I got the following output:

Address for object 1 is 0x7ffc32ff26b0
Address for object 2 is 0x7ffc32ff26b0
Address for object 3 is 0x7ffc32ff26b0
Address for object 4 is 0x7ffc32ff26b0
Address for object 5 is 0x7ffc32ff26b0
Address for object 6 is 0x7ffc32ff26b0
Address for object 7 is 0x7ffc32ff26b0
Address for object 8 is 0x7ffc32ff26b0
Address for object 9 is 0x7ffc32ff26b0
Address for object 10 is 0x7ffc32ff26b0

I understand that each object is destroyed every time the loop iterates and a new object is created; but why do all of them have the same address. This problem occurred to me when I was creating a linked list and I did not use the new operator to create the object instead just used the same code, and the list always pointed to the same node and I ran into an infinite loop. Why is the same address allocated to each object?


问:
Best way to define error code and error message mapping in .NET
I want to create custom error code and message mapping file. Currently I use Dictionary<int, string> to store them but I think they may have better way to achieve this.

If there is common practice to do this please let me know.

答:
Maybe rather have a look at using a resource in the project

Adding and Editing Resources (Visual C#)

ContentLicense: CC BY-SA 2.5


问:
Test Coverage .NetCore
I was looking for a TestCoverage for .netCore Xunit.

I found OpenCover, but i have no sucess to execute the command to run it:

```<code>C:\Users\andre.silva\AppData\Local\Apps\OpenCover\OpenCover.Console.exe -target:"C:\Users\andre.silva\.dnx\runtimes\dnx-clr-win-x86.1.0.0-rc1-update1\bin\dnx.exe" -targetargs:"--lib dotnet test" -output:coverage.xml -register:user -filter:"+[*]* -[xunit*]*"
</code>```

Error: Unable to resolve project

Does Anybody know if OpenCover can runwith .NETCore projects?

Tks guys

答:
I solved the problem.

I was running a command with a simple 'dotnet test' but i should use 'dotnet xunit'

Just goes to your root folder in test project and run:

C:\Users\andre.silva\.nuget\packages\OpenCover\4.6.519\tools\OpenCover.Console.exe -target:"C:\Program Files\dotnet\dotnet.exe" -targetargs:"xunit" -register:user -filter:"+[*]* -[xunit*]*" -oldStyle

Tks Guys

Title: Test Coverage .NetCore

Body:
I was looking for a TestCoverage for .netCore Xunit.

I found OpenCover, but i have no sucess to execute the command to run it:

C:\Users\andre.silva\AppData\Local\Apps\OpenCover\OpenCover.Console.exe -target:"C:\Users\andre.silva\.dnx\runtimes\dnx-clr-win-x86.1.0.0-rc1-update1\bin\dnx.exe" -targetargs:"--lib dotnet test" -output:coverage.xml -register:user -filter:"+[*]* -[xunit*]*"

Error: Unable to resolve project

Does Anybody know if OpenCover can runwith .NETCore projects?

Tks guys

ContentLicense: CC BY-SA 4.0


问:
 not consistently monospace with braille characters
I am attempting to draw a cube using the Braille Patterns Unicode Block, via the node-drawille library.

However, it appears that the width of the braille characters is not consistent(?), even though the text is in a ```</code> element.</p>

<p>I have included the demo, which prints the length of each line (80 characters). I have also included a picture of what I see when I highlight the entire <code>``` element. (OSX 10.12)

I have tested both with the default monospace and the font I use in my terminal (Menlo Regular). The results are similar, the width is inconsistent even though the character count is the same.

Desired result (pasted exactly into terminal):

(For best results w/ demo, run in a full page, and highlight the entire pre element to see the variable widths).

var data = document.getElementById('cube').innerHTML;
data.split('\n').forEach(x => console.log(x.length))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><pre id="cube">

                                        ⢀⡀
                                    ⢀⡠⠔⠊⠁⡏⠑⠤⡀
                                ⢀⡠⠔⠊⠁    ⡇  ⠈⠑⠤⡀
                            ⢀⡠⠔⠊⠁        ⡇     ⠈⠑⠤⡀
                           ⢸⠑⠒⠤⠤⣀⡀       ⡇    ⢀⣀⡠⠤⠜⢳
                           ⢸     ⠈⠉⠒⠒⠤⢄⣀⡠⡧⠔⠒⠊⠉⠁    ⢸
                           ⢸           ⡇ ⡇         ⢸
                           ⢸           ⡇ ⡇         ⢸
                           ⢸           ⡇ ⡇         ⢸
                           ⢸           ⡇ ⡇         ⢸
                           ⡏           ⡇ ⡇          ⡇
                           ⡇           ⡇ ⡇          ⡇
                           ⡇           ⡇ ⡇          ⡇
                           ⡇           ⡇ ⡇          ⡇
                           ⡇       ⣀⡠⠤⠔⠓⠢⡧⠤⣀⣀⣀      ⡇
                           ⡇⣀⣀⠤⠔⠒⠋⠉      ⡇   ⠈⠉⠉⠑⠒⠒⣤⠇
                           ⠉⠒⠤⢄⡀         ⡇     ⢀⡠⠔⠉
                               ⠈⠉⠒⠦⢄⣀    ⡇  ⣀⠤⠚⠁
                                     ⠉⠒⠢⢄⡧⠔⠊

                                                                                ``````

答:
It seems the answer is the same as How to display special unicode characters using monospace font in HTML with preserved character width

The font does not contain this block of Unicode characters, so it is rendered with a more default system font, which is not unicode. Picking a font that contains these characters, like http://unifoundry.com/unifont.html or https://github.com/josuah/miniwi fixes the issue!

Title: <pre> not consistently monospace with braille characters

Body:
I am attempting to draw a cube using the Braille Patterns Unicode Block, via the node-drawille library.

However, it appears that the width of the braille characters is not consistent(?), even though the text is in a
 element.

I have included the demo, which prints the length of each line (80 characters). I have also included a picture of what I see when I highlight the entire
 element. (OSX 10.12)

I have tested both with the default monospace and the font I use in my terminal (Menlo Regular). The results are similar, the width is inconsistent even though the character count is the same.

Desired result (pasted exactly into terminal):

(For best results w/ demo, run in a full page, and highlight the entire pre element to see the variable widths).

var data = document.getElementById('cube').innerHTML;
data.split('\n').forEach(x => console.log(x.length))

                                        ⢀⡀
                                    ⢀⡠⠔⠊⠁⡏⠑⠤⡀
                                ⢀⡠⠔⠊⠁    ⡇  ⠈⠑⠤⡀
                            ⢀⡠⠔⠊⠁        ⡇     ⠈⠑⠤⡀
                           ⢸⠑⠒⠤⠤⣀⡀       ⡇    ⢀⣀⡠⠤⠜⢳
                           ⢸     ⠈⠉⠒⠒⠤⢄⣀⡠⡧⠔⠒⠊⠉⠁    ⢸
                           ⢸           ⡇ ⡇         ⢸
                           ⢸           ⡇ ⡇         ⢸
                           ⢸           ⡇ ⡇         ⢸
                           ⢸           ⡇ ⡇         ⢸
                           ⡏           ⡇ ⡇          ⡇
                           ⡇           ⡇ ⡇          ⡇
                           ⡇           ⡇ ⡇          ⡇
                           ⡇           ⡇ ⡇          ⡇
                           ⡇       ⣀⡠⠤⠔⠓⠢⡧⠤⣀⣀⣀      ⡇
                           ⡇⣀⣀⠤⠔⠒⠋⠉      ⡇   ⠈⠉⠉⠑⠒⠒⣤⠇
                           ⠉⠒⠤⢄⡀         ⡇     ⢀⡠⠔⠉
                               ⠈⠉⠒⠦⢄⣀    ⡇  ⣀⠤⠚⠁
                                     ⠉⠒⠢⢄⡧⠔⠊


问:
Flexbox: Flex-Item Aside

Hello, I've tried to achieve this design to no avail. Regarding the 2nd item: align-self: stretch doesn't work, and flex-basis only applies to the main axis. Any ideas?

答:
Here it's imo you can do. but with your code it should be better to help you

.container{
  width : 100vw;
  height : 100vh;
  display:flex;
}
.sub-container1{
  flex : 1;
  display:flex;
  flex-direction : column;
  background-color : #245878;
}
.item1{
  flex:1;
  background-color : #214585;
  margin : 5%;

}
.item2{
  flex:1;
  background-color : #548789;
  margin : 5%;
}
.sub-container2{
  flex:1;
  display:flex;
  background-color : #451589;
}
.item3{
  flex:1;
  background-color : #236589;
  margin : 5%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class=container>
  <div class="sub-container1">
    <div class="item1"></div>
    <div class="item2"></div>
  </div>
  <div class="sub-container2">
    <div class="item3"></div>
  </div>
</div></code>```

Title: Flexbox: Flex-Item Aside

Body:
Here it's imo you can do. but with your code it should be better to help you

.container{
  width : 100vw;
  height : 100vh;
  display:flex;
}
.sub-container1{
  flex : 1;
  display:flex;
  flex-direction : column;
  background-color : #245878;
}
.item1{
  flex:1;
  background-color : #214585;
  margin : 5%;

}
.item2{
  flex:1;
  background-color : #548789;
  margin : 5%;
}
.sub-container2{
  flex:1;
  display:flex;
  background-color : #451589;
}
.item3{
  flex:1;
  background-color : #236589;
  margin : 5%;
}

<div class=container>
  <div class="sub-container1">
    <div class="item1"></div>
    <div class="item2"></div>
  </div>
  <div class="sub-container2">
    <div class="item3"></div>
  </div>
</div>


问:
Query regarding a Numpy exercise in Datacamp
Just started learning python with Datacamp and I ran into a question on Numpy. When doing this problem(it's a standalone question so should be easy to understand without any context), I am confused by the instruction:"You can use a little trick here: use np_positions == 'GK' as an index for np_heights".

Nowhere in the code did it link np_heights and np_positions together, how could this index work? At first I thought I had to concatenate the two vertically but it turns out it's not necessary.

Is it because there are only two Numpy arrays and it just so happened that they have the same number of elements, Python decides to pair them up automatically? What if I have multiple Numpy arrays with the same number of elements and I use that index, will it be a problem?

答:
The only thing they have in common is their length. Other than that, they are not linked together. The length comes into play when you use boolean indexing.

Consider the following array:

```<code>arr = np.array([1, 2, 3])
</code>```

With boolean values, we can index into this array:

```<code>arr[[True, False, True]]
Out: array([1, 3])
</code>```

This returned values at positions 0 and 2 (where they have True values).

This boolean array may come from anywhere. It may come from the same array with a comparison, or from a different array of the same length.

```<code>arr1 = np.array(['a', 'b', 'a', 'c'])
</code>```

If I do arr1 == 'a' it will do an element-wise comparison and return

```<code>arr1 == 'a'
Out: array([ True, False,  True, False], dtype=bool)
</code>```

I can use this in the same array:

```<code>arr1[arr1=='a']
Out:
array(['a', 'a'],
      dtype='<U1')
</code>```

Or in a different array:

```<code>arr2 = np.array([2, 5, 1, 7])

arr2[arr1=='a']
Out: array([2, 1])
</code>```

Note that this is no different than arr2[[True, False, True, False]]. So we are not actually using arr1 here. In your example, np_positions == 'GK' will return a boolean array too. Since it will have the same size as the np_height array, you will only deal with positions where the boolean array has True values.

Body:
The only thing they have in common is their length. Other than that, they are not linked together. The length comes into play when you use boolean indexing.

Consider the following array:

arr = np.array([1, 2, 3])

With boolean values, we can index into this array:

arr[[True, False, True]]
Out: array([1, 3])

This returned values at positions 0 and 2 (where they have True values).

This boolean array may come from anywhere. It may come from the same array with a comparison, or from a different array of the same length.

arr1 = np.array(['a', 'b', 'a', 'c'])

If I do arr1 == 'a' it will do an element-wise comparison and return

arr1 == 'a'
Out: array([ True, False,  True, False], dtype=bool)

I can use this in the same array:

arr1[arr1=='a']
Out:
array(['a', 'a'],
      dtype='<U1')

Or in a different array:

arr2 = np.array([2, 5, 1, 7])

arr2[arr1=='a']
Out: array([2, 1])

Note that this is no different than arr2[[True, False, True, False]]. So we are not actually using arr1 here. In your example, np_positions == 'GK' will return a boolean array too. Since it will have the same size as the np_height array, you will only deal with positions where the boolean array has True values.


问:
Getting comboBox1.SelectedValue
```<code>private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        switchItem();
    }
private void switchItem()
        {
            var content = richTextBox1;
            switch (comboBox1.SelectedValue.ToString())
            {
                case "Fruit":
                    content.Text = "Apple";
                    break;
                default:
                    content.Rtf = "Not Selected";
                    break;
            }
        }
</code>```

As you can see, I'm trying to get the SelectedValue of comboBox1 and this object reference not set to an instance of an object error showed up. What should I do?

答:
Maybe you're looking for SelectedItem rather than SelectedValue

The error object reference not set to an instance of an object means that SelectedValue is null

Title: Getting comboBox1.SelectedValue

Body:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        switchItem();
    }
private void switchItem()
        {
            var content = richTextBox1;
            switch (comboBox1.SelectedValue.ToString())
            {
                case "Fruit":
                    content.Text = "Apple";
                    break;
                default:
                    content.Rtf = "Not Selected";
                    break;
            }
        }

As you can see, I'm trying to get the SelectedValue of comboBox1 and this object reference not set to an instance of an object error showed up. What should I do?


问:
TextBox stretches in stack view Xcode
I have 3 stacks inside another stack and text boxes stretch way too much. I tried to add hight constraint to a TextBox but it gets highlighted in red and TextBox doesn't shrink (screenshot attached). Can anybody recommend a solution?

答:
It looks like you want to lay out a form with three rows. The three rows are not enough content to fill the screen vertically, so you need to decide where you want the excess space to go, and you need to set up your constraints to put the excess space there.

Let's say you want the rows centered vertically. Then you need to constrain the vertical stack view's Y center to the root view's Y center. Don't put any other constraints on the vertical stack view's height or its top or bottom. Leaving it unconstrained lets it size itself to perfectly fit its arranged subviews without stretching or compressing them.

You're also getting uneven horizontal stretching of your labels and views. To fix this, constrain all of the labels to be equal width to each other. Then set the labels' horizontal content hugging priority to 251 and their horizontal content compression resistance priority to 750.  Set the text fields' horizontal content hugging priority to 250 (just less than the labels'). This tells the horizontal stack views to stretch the text fields, rather than the labels, to fill the excess horizontal space.

Result:

Here's my document outline:

Title: TextBox stretches in stack view Xcode


问:
Using JS to change three div IDs (carousel-esque), works twice, but then skips a div
I'm trying to create a carousel where all three items are visible, and they switch position when the navigation is clicked (at the moment only working on the left arrow).

I am doing this by assigning each div to a position using an id, and using JS to change the ids.

It works as intended, but when #pos3 (the banana) becomes #pos1, it for some reason gets skipped, and #pos2 and #pos3 just exchange places.

The CSS:

```<code>#pos1{
left:10%;
}

#pos2{
left:30%;
z-index:2;
top:50px;
background:rgba(255,255,255,0.9);
}

#pos3{
left:60%;
}
</code>```

The JS

```<code>document.getElementById("left").onclick = function (){
  document.getElementById("pos2").setAttribute("id", "pos1");
  document.getElementById("pos3").setAttribute("id", "pos2");
  document.getElementById("pos1").setAttribute("id", "pos3");
};
</code>```

Fiddle here

答:
document.getElementById("pos2").setAttribute("id", "pos1");
  document.getElementById("pos3").setAttribute("id", "pos2");

  document.getElementById("pos1").setAttribute("id", "pos3");

By the time third line is executed, pos1 doesn't exist as you've already changed that on 1st line.

Simply introduce a temporary id to fix this.

document.getElementById("pos1").setAttribute("id", "temp");
  document.getElementById("pos2").setAttribute("id", "pos1");
  document.getElementById("pos3").setAttribute("id", "pos2");

  document.getElementById("temp").setAttribute("id", "pos3");

Body:
I'm trying to create a carousel where all three items are visible, and they switch position when the navigation is clicked (at the moment only working on the left arrow).

I am doing this by assigning each div to a position using an id, and using JS to change the ids.

It works as intended, but when #pos3 (the banana) becomes #pos1, it for some reason gets skipped, and #pos2 and #pos3 just exchange places.

The CSS:

#pos1{
left:10%;
}

#pos2{
left:30%;
z-index:2;
top:50px;
background:rgba(255,255,255,0.9);
}

#pos3{
left:60%;
}

The JS

document.getElementById("left").onclick = function (){
  document.getElementById("pos2").setAttribute("id", "pos1");
  document.getElementById("pos3").setAttribute("id", "pos2");
  document.getElementById("pos1").setAttribute("id", "pos3");
};

Fiddle here


问:
Unable to install Docker on Ubuntu 17
I am installing Docker by following this official tutorial. It doesn't work for me. Is it because I am using Ubuntu 17?

```<code>sudo apt-get install docker-ce
</code>```

the error is

"E: Package 'docker-ce' has no installation candidate"

I did all the apt-get update.

looks like can not find docker-ce package. What should I do?

答:
I found answer here:

https://askubuntu.com/questions/909691/how-to-install-docker-on-ubuntu-17-04

The following procedure fixed my problem and I can install and run Docker on Ubuntu 17 with no issue:

Docker hasn't setup a repository for the latest ubuntu, but that's an easy fix because their release for ubuntu 16 is compatible. For the time being, just edit /etc/apt/sources.list and on the line:

deb [arch=amd64] https://download.docker.com/linux/ubuntu zesty stable
Replace zesty by xenial. Run sudo apt-get update and you can proceed with sudo apt-get install docker-ce

Title: Unable to install Docker on Ubuntu 17

Body:
I am installing Docker by following this official tutorial. It doesn't work for me. Is it because I am using Ubuntu 17?

sudo apt-get install docker-ce

the error is

"E: Package 'docker-ce' has no installation candidate"

I did all the apt-get update.

looks like can not find docker-ce package. What should I do?


问:
In Rails 5, how to inject the current_user.id into a controller#create method
I'm using Rails 5 to create an API. My controller looks like the following:

```<code>  ....
  def create
    @user_position = UserPosition.create(user_position_params)
    json_response(@user_position)
  end

private

  def user_position_params
    params.require(:user_position).permit(:job_title_id)
  end

  def json_response(object, status = :ok)
    render json: object, status: status
  end

end
</code>```

In the create method, how can I add :user_id => current_user.id With Rails 5, should this be in the user_position_params?

答:
As create would persist the new record with the user_position_params on the database once is "executed", you could use instead new to set a new UserPosition instance and then to set the user_id as the id from the current_user, after this, you can save it, try with:

```<code>@user_position = UserPosition.new(user_position_params)
@user_position.user_id = current_user.id
@user_position.save
</code>```

Body:
I'm using Rails 5 to create an API. My controller looks like the following:

  ....
  def create
    @user_position = UserPosition.create(user_position_params)
    json_response(@user_position)
  end

private

  def user_position_params
    params.require(:user_position).permit(:job_title_id)
  end

  def json_response(object, status = :ok)
    render json: object, status: status
  end

end

In the create method, how can I add :user_id => current_user.id With Rails 5, should this be in the user_position_params?

Body:
As create would persist the new record with the user_position_params on the database once is "executed", you could use instead new to set a new UserPosition instance and then to set the user_id as the id from the current_user, after this, you can save it, try with:

@user_position = UserPosition.new(user_position_params)
@user_position.user_id = current_user.id
@user_position.save


问:
Swagger UI with Tynamo Resteasy for Tapestry 5.4
I am using tynamo resteasy with my Tapestry 5.4 project.
I'd like to incorporate Swagger to document and share API with other other teams.
While I see that swagger is already in RestEasy's project dependency, it does not work "out of the box"

I've added

@Api to the "Resource" class (located in /rest/ package)
and
@ApiOperation to the GET method

Do I need to change AppModule or web.xml in anyway to hook the swagger UI?
Is there an example (github etc.) anywhere that I can follow?

Also, will the swagger api be available at localhost/swagger/myendpoint?

答:
Here's a step by step process:

Get swagger-jaxrs: https://mvnrepository.com/artifact/io.swagger/swagger-jaxrs/1.5.0

Create a SwaggerModule.java in "modules" directory (example: com.mysite.mypkg.modules)

```<code>public class SwaggerModule {
  @Contribute(SymbolProvider.class)
  @ApplicationDefaults
  public static void provideSymbols(MappedConfiguration<String, Object> configuration) {
    configuration.add(ResteasySymbols.CORS_ENABLED, true);
  }

  @Contribute(javax.ws.rs.core.Application.class)
  public static void contributeApplication(Configuration<Object> singletons) {
    singletons.addInstance(io.swagger.jaxrs.listing.ApiListingResource.class);
    singletons.addInstance(io.swagger.jaxrs.listing.SwaggerSerializers.class);
  }

  @Startup
  public static void swagger(javax.ws.rs.core.Application application,
      BaseURLSource baseURLSource,
      @Symbol(InternalConstants.TAPESTRY_APP_PACKAGE_PARAM) String basePackage,
      @Symbol(ResteasySymbols.MAPPING_PREFIX) String restPath,
      @Symbol(SymbolConstants.APPLICATION_VERSION) String version) {
    application.getSingletons();
    BeanConfig config = new BeanConfig();
    config.setSchemes(new String[]{"http"});
    config.setVersion("1.0.2");
    config.setHost("localhost:8080");
    config.setBasePath("/mysite" + restPath);
    config.setTitle("Mysite Rest Documentation");
    config.setResourcePackage("com.mysite.mypkg.rest");//where your rest resources are located
    config.setScan(true);
  }
</code>```

On your AppModule.java, import the SwaggerModule (Tapestry 5.4)

```<code>@ImportModule(SwaggerModule.class)
public class AppModule {...
}
</code>```

The swagger.json and swagger.yaml can now be accessed as:

```<code>http://localhost:8080/mysite/rest/swagger.json
</code>```

Many thanks to @ascandroli above for pointing out the basics

Body:
Here's a step by step process:

Get swagger-jaxrs: https://mvnrepository.com/artifact/io.swagger/swagger-jaxrs/1.5.0

Create a SwaggerModule.java in "modules" directory (example: com.mysite.mypkg.modules)

public class SwaggerModule {
  @Contribute(SymbolProvider.class)
  @ApplicationDefaults
  public static void provideSymbols(MappedConfiguration<String, Object> configuration) {
    configuration.add(ResteasySymbols.CORS_ENABLED, true);
  }

  @Contribute(javax.ws.rs.core.Application.class)
  public static void contributeApplication(Configuration<Object> singletons) {
    singletons.addInstance(io.swagger.jaxrs.listing.ApiListingResource.class);
    singletons.addInstance(io.swagger.jaxrs.listing.SwaggerSerializers.class);
  }

  @Startup
  public static void swagger(javax.ws.rs.core.Application application,
      BaseURLSource baseURLSource,
      @Symbol(InternalConstants.TAPESTRY_APP_PACKAGE_PARAM) String basePackage,
      @Symbol(ResteasySymbols.MAPPING_PREFIX) String restPath,
      @Symbol(SymbolConstants.APPLICATION_VERSION) String version) {
    application.getSingletons();
    BeanConfig config = new BeanConfig();
    config.setSchemes(new String[]{"http"});
    config.setVersion("1.0.2");
    config.setHost("localhost:8080");
    config.setBasePath("/mysite" + restPath);
    config.setTitle("Mysite Rest Documentation");
    config.setResourcePackage("com.mysite.mypkg.rest");//where your rest resources are located
    config.setScan(true);
  }

On your AppModule.java, import the SwaggerModule (Tapestry 5.4)

@ImportModule(SwaggerModule.class)
public class AppModule {...
}

The swagger.json and swagger.yaml can now be accessed as:

http://localhost:8080/mysite/rest/swagger.json

Many thanks to @ascandroli above for pointing out the basics


问:
Can't set adapter of ListView because the ListView has a null object reference
I am trying to make a TabLayout with a ViewPager, but whenever I leave the app (Don't close it, just switch to another app and back) the fragments kind of get killed. I don't know that for sure, but the fragment's need to reCreate, and then fail.

The code for creating the TabLayout, TabLayoutAdapter and the ViewPager:

```<code>    TabLayout tabLayout = (TabLayout) findViewById(R.id.tablayout);
    MyTabLayoutAdapter tabLayoutAdapter;
    ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);

    tabLayout.addTab(tabLayout.newTab().setText("-2"));
    tabLayout.addTab(tabLayout.newTab().setText("-1"));
    tabLayout.addTab(tabLayout.newTab().setText("0"));
    tabLayout.addTab(tabLayout.newTab().setText("1"));
    tabLayout.addTab(tabLayout.newTab().setText("2"));

    tabLayoutAdapter = new MyTabLayoutAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
    viewPager.setAdapter(tabLayoutAdapter);
    viewPager.setOffscreenPageLimit(3);
    tabLayout.setupWithViewPager(viewPager);
    viewPager.setCurrentItem(2);
</code>```

The code of my TabLayoutAdapter:

```<code>public class MyTabLayoutAdapter extends FragmentStatePagerAdapter {
    private MyFragment fragmentOne;
    private MyFragment fragmentTwo;
    private MyFragment fragmentDefault;
    private MyFragment fragmentFour;
    private MyFragment fragmentFive;
    private int numberOfTabs;

    public MyTabLayoutAdapter(FragmentManager fragmentManager, int numberOfTabs) {
        super(fragmentManager);
        fragmentOne = new MyFragment();
        fragmentTwo = new MyFragment();
        fragmentDefault = new MyFragment();
        fragmentFour = new MyFragment();
        fragmentFive = new MyFragment();
        this.numberOfTabs = numberOfTabs;
    }

    @Override
    public MyFragment getItem(int position) {
        switch (position) {
            case 0:
                return fragmentOne;
            case 1:
                return fragmentTwo;
            case 2:
                return fragmentDefault;
            case 3:
                return fragmentFour;
            case 4:
                return fragmentFive;
            default:
                return fragmentDefault;
        }
    }

    @Override
    public int getCount() {
        return numberOfTabs;
    }
}
</code>```

The MyFragment fragment:

```<code>public class MyFragment extends Fragment {
    private View currentView;
    private ListView listView;

    public MyFragment() {}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        currentView = LayoutInflater.from(getContext()).inflate(R.layout.my_fragment_layout, container, false);
        listView = (ListView) currentView.findViewById(R.id.listview);
        return currentView;
    }

    //This line throws a NullPointer when I resume the app
    public void populateListView(MyListAdapter myListAdapter) {
        listView.setAdapter(myListAdapter);
    }
}
</code>```

Whenever I call

```<code>MyListAdapter myListAdapter = new MyListAdapter(this, R.layout.my_item, justSomeStringArray);
tabLayoutAdapter.getItem(0).populateListView(myListAdapter);
</code>```

I get a NullPointerException saying that it can't set a adapter on a null object reference.

Anyone any idea how I can fix this?

答:
Here's an approach which lets the Fragment instance drive the data retrieval by using an AsyncTask implementation (GetDataForListViewTask).

But, to follow Commonsware's advice, GetDataForListViewTask merely obtains the data. It does not set up the adapter for use on the ListViews. Instead, setting up the ListAdapter is done in the Fragment itself.

GetDataForListViewTask passes the data back to the Fragment instance using EventBus. This keeps GetDataForListViewTask from having to maintain a reference to the ListView, Activity, Context or any of that risky stuff.

And, by not "reaching in" to a Fragment from the outside to change its widgets or even hand it data, this code also tries (very broadly) to follow another piece of CommonsWare's guidance:

In general, having code outside of a fragment attempt to manipulate
  the widgets inside that fragment — as you are doing here — is a bad
  idea.

In any case, if you use this approach, which is a bit different from your original approach, you'll want to modify the GetDataForListViewTask so that it obtains the data from elsewhere in your app or the network, etc.

GetDataForListViewTask.java

```<code>import android.os.AsyncTask;
import org.greenrobot.eventbus.EventBus;
import java.util.ArrayList;

class GetDataForListViewTask extends AsyncTask<Void, Void, ArrayList<String>> {

    @Override
    protected ArrayList<String> doInBackground(Void... ignored) {
        // since this method runs on a worker thread, you may
        // replace this code with a network call or a background computation
        // from another part of the app is ready
        ArrayList<String> listItems = new ArrayList<>();
        for (int i=0; i<10; i++) {
            listItems.add("item " + i);
        }

        return listItems;
    }

    @Override
    protected void onPostExecute(ArrayList<String> result) {
        super.onPostExecute(result);

        // post event so that Fragment can use the data to populate its ListView
        EventBus.getDefault().post(new MyFragment.ListViewDataReadyEvent(result));
    }

}
</code>```

MainActivity.java

```<code>import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

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

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tablayout);
        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);

        MyAdapter tabLayoutAdapter = new MyAdapter(getSupportFragmentManager(), 5);
        viewPager.setAdapter(tabLayoutAdapter);
        viewPager.setOffscreenPageLimit(3);
        tabLayout.setupWithViewPager(viewPager);
        viewPager.setCurrentItem(2);
    }

    class MyAdapter extends FragmentStatePagerAdapter {

        private final int count;

        public MyAdapter(FragmentManager fm, int count) {
            super(fm);
            this.count = count;
        }

        @Override
        public MyFragment getItem(int position) {
            return MyFragment.newInstance();
        }

        @Override
        public int getCount() {
            return this.count;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return "Tab " + position;
        }
    }

}
</code>```

MyFragment.java

```<code>import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

public class MyFragment extends Fragment {

        private ListView listView;
        private GetDataForListViewTask getDataForListViewTask;

        public static MyFragment newInstance() {
            return new MyFragment();
        }

        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setRetainInstance(true); // to support use of GetDataForListViewTask
            EventBus.getDefault().register(this);
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            listView = (ListView) LayoutInflater.from(getContext()).inflate(
                    R.layout.my_fragment_layout, container, false);
            getDataForListViewTask = new GetDataForListViewTask();
            getDataForListViewTask.execute();
            return listView;
        }

        @Override
        public void onDestroy() {
            if (getDataForListViewTask != null) {
                getDataForListViewTask.cancel(false);
            }
            EventBus.getDefault().unregister(this);
            super.onDestroy();
        }

        static class ListViewDataReadyEvent {

            ArrayList<String> data;
            ListViewDataReadyEvent(ArrayList<String> data) {
                this.data = data;
            }
        }

        @SuppressWarnings("unused")
        @Subscribe(threadMode = ThreadMode.MAIN)
        public void onMessageEvent(ListViewDataReadyEvent event) {
            if (listView != null) {
                ArrayAdapter<String> listAdapter = new ArrayAdapter<>(listView.getContext(),
                        android.R.layout.simple_list_item_1, event.data.toArray(new String[]{}));
                listView.setAdapter(listAdapter);
            }
        }
    }
</code>```

activity_main.xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical" android:padding="4dip"
    android:gravity="center_horizontal"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <android.support.design.widget.TabLayout
        android:id="@+id/tablayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="fixed"
        app:tabGravity="fill" />

    <android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </android.support.v4.view.ViewPager>

</LinearLayout>
</code>```

my_fragment_layout.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<ListView android:id="@+id/listview"
    android:layout_alignParentTop="true"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
</ListView>
</code>```

Selected compile statements for build.gradle

```<code>compile 'org.greenrobot:eventbus:3.0.0'
compile 'com.android.support:design:25.3.1'
compile 'com.android.support:appcompat-v7:25.3.1'
</code>```

Body:
I am trying to make a TabLayout with a ViewPager, but whenever I leave the app (Don't close it, just switch to another app and back) the fragments kind of get killed. I don't know that for sure, but the fragment's need to reCreate, and then fail.

The code for creating the TabLayout, TabLayoutAdapter and the ViewPager:

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tablayout);
    MyTabLayoutAdapter tabLayoutAdapter;
    ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);

    tabLayout.addTab(tabLayout.newTab().setText("-2"));
    tabLayout.addTab(tabLayout.newTab().setText("-1"));
    tabLayout.addTab(tabLayout.newTab().setText("0"));
    tabLayout.addTab(tabLayout.newTab().setText("1"));
    tabLayout.addTab(tabLayout.newTab().setText("2"));

    tabLayoutAdapter = new MyTabLayoutAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
    viewPager.setAdapter(tabLayoutAdapter);
    viewPager.setOffscreenPageLimit(3);
    tabLayout.setupWithViewPager(viewPager);
    viewPager.setCurrentItem(2);

The code of my TabLayoutAdapter:

public class MyTabLayoutAdapter extends FragmentStatePagerAdapter {
    private MyFragment fragmentOne;
    private MyFragment fragmentTwo;
    private MyFragment fragmentDefault;
    private MyFragment fragmentFour;
    private MyFragment fragmentFive;
    private int numberOfTabs;

    public MyTabLayoutAdapter(FragmentManager fragmentManager, int numberOfTabs) {
        super(fragmentManager);
        fragmentOne = new MyFragment();
        fragmentTwo = new MyFragment();
        fragmentDefault = new MyFragment();
        fragmentFour = new MyFragment();
        fragmentFive = new MyFragment();
        this.numberOfTabs = numberOfTabs;
    }

    @Override
    public MyFragment getItem(int position) {
        switch (position) {
            case 0:
                return fragmentOne;
            case 1:
                return fragmentTwo;
            case 2:
                return fragmentDefault;
            case 3:
                return fragmentFour;
            case 4:
                return fragmentFive;
            default:
                return fragmentDefault;
        }
    }

    @Override
    public int getCount() {
        return numberOfTabs;
    }
}

The MyFragment fragment:

public class MyFragment extends Fragment {
    private View currentView;
    private ListView listView;

    public MyFragment() {}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        currentView = LayoutInflater.from(getContext()).inflate(R.layout.my_fragment_layout, container, false);
        listView = (ListView) currentView.findViewById(R.id.listview);
        return currentView;
    }

    //This line throws a NullPointer when I resume the app
    public void populateListView(MyListAdapter myListAdapter) {
        listView.setAdapter(myListAdapter);
    }
}

Whenever I call

MyListAdapter myListAdapter = new MyListAdapter(this, R.layout.my_item, justSomeStringArray);
tabLayoutAdapter.getItem(0).populateListView(myListAdapter);

I get a NullPointerException saying that it can't set a adapter on a null object reference.

Anyone any idea how I can fix this?

Body:
Here's an approach which lets the Fragment instance drive the data retrieval by using an AsyncTask implementation (GetDataForListViewTask).

But, to follow Commonsware's advice, GetDataForListViewTask merely obtains the data. It does not set up the adapter for use on the ListViews. Instead, setting up the ListAdapter is done in the Fragment itself.

GetDataForListViewTask passes the data back to the Fragment instance using EventBus. This keeps GetDataForListViewTask from having to maintain a reference to the ListView, Activity, Context or any of that risky stuff.

And, by not "reaching in" to a Fragment from the outside to change its widgets or even hand it data, this code also tries (very broadly) to follow another piece of CommonsWare's guidance:

In general, having code outside of a fragment attempt to manipulate
  the widgets inside that fragment — as you are doing here — is a bad
  idea.

In any case, if you use this approach, which is a bit different from your original approach, you'll want to modify the GetDataForListViewTask so that it obtains the data from elsewhere in your app or the network, etc.

GetDataForListViewTask.java

import android.os.AsyncTask;
import org.greenrobot.eventbus.EventBus;
import java.util.ArrayList;

class GetDataForListViewTask extends AsyncTask<Void, Void, ArrayList<String>> {

    @Override
    protected ArrayList<String> doInBackground(Void... ignored) {
        // since this method runs on a worker thread, you may
        // replace this code with a network call or a background computation
        // from another part of the app is ready
        ArrayList<String> listItems = new ArrayList<>();
        for (int i=0; i<10; i++) {
            listItems.add("item " + i);
        }

        return listItems;
    }

    @Override
    protected void onPostExecute(ArrayList<String> result) {
        super.onPostExecute(result);

        // post event so that Fragment can use the data to populate its ListView
        EventBus.getDefault().post(new MyFragment.ListViewDataReadyEvent(result));
    }

}

MainActivity.java

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

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

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tablayout);
        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);

        MyAdapter tabLayoutAdapter = new MyAdapter(getSupportFragmentManager(), 5);
        viewPager.setAdapter(tabLayoutAdapter);
        viewPager.setOffscreenPageLimit(3);
        tabLayout.setupWithViewPager(viewPager);
        viewPager.setCurrentItem(2);
    }

    class MyAdapter extends FragmentStatePagerAdapter {

        private final int count;

        public MyAdapter(FragmentManager fm, int count) {
            super(fm);
            this.count = count;
        }

        @Override
        public MyFragment getItem(int position) {
            return MyFragment.newInstance();
        }

        @Override
        public int getCount() {
            return this.count;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return "Tab " + position;
        }
    }

}

MyFragment.java

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

public class MyFragment extends Fragment {

        private ListView listView;
        private GetDataForListViewTask getDataForListViewTask;

        public static MyFragment newInstance() {
            return new MyFragment();
        }

        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setRetainInstance(true); // to support use of GetDataForListViewTask
            EventBus.getDefault().register(this);
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            listView = (ListView) LayoutInflater.from(getContext()).inflate(
                    R.layout.my_fragment_layout, container, false);
            getDataForListViewTask = new GetDataForListViewTask();
            getDataForListViewTask.execute();
            return listView;
        }

        @Override
        public void onDestroy() {
            if (getDataForListViewTask != null) {
                getDataForListViewTask.cancel(false);
            }
            EventBus.getDefault().unregister(this);
            super.onDestroy();
        }

        static class ListViewDataReadyEvent {

            ArrayList<String> data;
            ListViewDataReadyEvent(ArrayList<String> data) {
                this.data = data;
            }
        }

        @SuppressWarnings("unused")
        @Subscribe(threadMode = ThreadMode.MAIN)
        public void onMessageEvent(ListViewDataReadyEvent event) {
            if (listView != null) {
                ArrayAdapter<String> listAdapter = new ArrayAdapter<>(listView.getContext(),
                        android.R.layout.simple_list_item_1, event.data.toArray(new String[]{}));
                listView.setAdapter(listAdapter);
            }
        }
    }

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical" android:padding="4dip"
    android:gravity="center_horizontal"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <android.support.design.widget.TabLayout
        android:id="@+id/tablayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="fixed"
        app:tabGravity="fill" />

    <android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </android.support.v4.view.ViewPager>

</LinearLayout>

my_fragment_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<ListView android:id="@+id/listview"
    android:layout_alignParentTop="true"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
</ListView>

Selected compile statements for build.gradle

compile 'org.greenrobot:eventbus:3.0.0'
compile 'com.android.support:design:25.3.1'
compile 'com.android.support:appcompat-v7:25.3.1'


问:
Change drawer gap between header group and first item menu
I need change the space between header group and first item menu, here's an example:

I have seen a lot of examples and posts but only be can change the space for all items, and I just need to change only for header group.

Any idea?

答:
Thanks to azizbekian, his answer gived to me a great idea (maybe not the best but in my case more simple and fast to implement).
Basically, I add a layout with the same name (this will override it).
After that I change all that I need, so the result is this:


问:
Is there a way to get directions(just routes) using google for mkmapview?
I'm using swift on iOS and using MKMapView.
I've been working on giving a user a from - to textfield and letting the user have a form of route between the from and to locations. I've got that working on mkmapview using the built in directions and geocoding api calls for Apple. However after using it for a while a realized that a lot of countries are not supported by Apple Apple - Supported Countries For Directions

So is there a way to get routes from the google maps SDK and translate them to a MKPolyline or MKOverlay? I haven't worked with google maps so keep that in mind. I saw this question iPhone: Using Google to get directions it has an answer, but the newest solution is 4 years old and its in objective-C. Although I do understand how to convert objective-C code to swift, I'd rather not have to go through a whole project. Keep in mind that this a part of a bigger project, so I can't switch the whole thing over to google maps.

答:
Using google api to find directions between origin and destination.

Required parameters:

origin : lat + long current location or place ID

.

destination : lat + long  destination location or place ID

.

Key: to create new google api key .

Optional parameters:

mode (defaults to driving) driving give you more options, or set

walking, bicycling, transit.

alternatives : false give u just one route, option true give all directions between origin and destinations, then you can choose which
route u want deponent on duration, or distance inside legs.

then convert points (inside overview_polyline) to list of    CLLocationCoordinate2D using Polyline library
https://github.com/raphaelmor/Polyline

Like this:

func convertPointToCoordinates() -> [CLLocationCoordinate2D]? {

let polyline = Polyline(encodedPolyline: overviewPolyline.points ?? "")

return polyline.coordinates

}

let coordinates = convertPointToCoordinates()

let polyLine = MKPolyline(coordinates: coordinates ?? [], count: (coordinates?.count ?? 0))

to add polyline on map view:

self.mapView.add(polyLine)

to focus on polyline region:

self.mapView.setVisibleMapRect(polyLine.boundingMapRect, edgePadding:     UIEdgeInsets.init(top: 60, left: 60, bottom: 60, right: 60), animated: true)


问:
While loading page in mozilla, First DIV code is not loaded
While loading page in mozilla, First DIV code is not loaded
tried to load html using inside

```<code><div id="mainContent"></div>
</code>```

with below call

```<code>if (destinationURL != null) {
$.get(destinationURL, function(data)
{
  $("#mainContent").attr("innerHTML",data);
});
}
</code>```

destinationURL refers below sample html

```<code><div id="A1">
<div id="B1">
    <div id="c1">
        <span>hi</span>
    </div>
    <div id="c2"></div>
</div>
    <div id="B2">
    <div id="D1">
        <span>hi2</span>
    </div>
    <div id="D2"></div>
</div>
<div id="B3">
    <div id="E1"></div>
    <div id="E2"></div>
</div>
<div id="B4">
    <div id="F1"></div>
    <div id="F2"></div>
</div>
</div>
</code>```

but, when html loads

```<code>$("#c1") refers null object
</code>```

if i see

```<code>$("#D1") contains html.
</code>```

if i give alert message on onLoad, i can able to get Html. Its happening only in mozilla

答:
```<code>is this right express what you intended?

   $("#mainContent").attr("innerHTML",data);

=> I think this expression will give you the answer you want.

  $("#mainContent").html(data);
</code>```

Body:
While loading page in mozilla, First DIV code is not loaded
tried to load html using inside

with below call

if (destinationURL != null) {
$.get(destinationURL, function(data)
{
  $("#mainContent").attr("innerHTML",data);
});
}

destinationURL refers below sample html

        hi

        hi2

but, when html loads

$("#c1") refers null object

if i see

$("#D1") contains html.

if i give alert message on onLoad, i can able to get Html. Its happening only in mozilla


问:
Clearing textboxs in tabcointrols in vb.net
I have tabcontrol of three tabs and each tabs contains textbox and i want to clear all textboxes in each tabs and a one click of button(button event or any alternate way to clear all textboxes)

i have already tried many code however that only effective for first tab only

```<code>Private Sub ClearFields(ByVal cntr As Control)
    For Each page As TabPage In TabControl1.TabPages
        For Each ctl As Control In page.Controls
            If TypeOf ctl Is TextBox Then
                ctl.Text = ""
            End If
            If TypeOf ctl Is ComboBox Then
                ctl.Text = ""
            End If
            If ctl.HasChildren Then
                For Each thing As Control In ctl.Controls
                    If TypeOf thing Is TextBox Then
                        thing.Text = ""
                    End If
                Next
            End If
        Next
    Next
End Sub
</code>```

答:
Here is another method which is setup as a language extension method. Create a new code module and replace the default code with the code below.

```<code>Public Module ControlExtensions
    <Runtime.CompilerServices.Extension()>
    Public Sub ClearSpecificControls(ByVal sender As Control)
        Dim currentControl As Control = sender.GetNextControl(sender, True)
        Dim cboControl As ComboBox = Nothing

        Do Until currentControl Is Nothing
            If TypeOf currentControl Is TextBox Then
                currentControl.Text = ""
            ElseIf TypeOf currentControl Is ComboBox Then
                cboControl = CType(currentControl, ComboBox)
                If cboControl.DataSource IsNot Nothing Then
                    cboControl.DataSource = Nothing
                Else
                    cboControl.Items.Clear()
                End If
            End If
            currentControl = sender.GetNextControl(currentControl, True)
        Loop
    End Sub
End Module
</code>```

Clear all TextBox and ComboBox controls within TabControl1.

```<code>TabControl1.ClearSpecificControls
</code>```

Clear all controls on a form

```<code>ClearSpecificControls
</code>```

Body:
I have tabcontrol of three tabs and each tabs contains textbox and i want to clear all textboxes in each tabs and a one click of button(button event or any alternate way to clear all textboxes)

i have already tried many code however that only effective for first tab only

Private Sub ClearFields(ByVal cntr As Control)
    For Each page As TabPage In TabControl1.TabPages
        For Each ctl As Control In page.Controls
            If TypeOf ctl Is TextBox Then
                ctl.Text = ""
            End If
            If TypeOf ctl Is ComboBox Then
                ctl.Text = ""
            End If
            If ctl.HasChildren Then
                For Each thing As Control In ctl.Controls
                    If TypeOf thing Is TextBox Then
                        thing.Text = ""
                    End If
                Next
            End If
        Next
    Next
End Sub

Body:
Here is another method which is setup as a language extension method. Create a new code module and replace the default code with the code below.

Public Module ControlExtensions
    <Runtime.CompilerServices.Extension()>
    Public Sub ClearSpecificControls(ByVal sender As Control)
        Dim currentControl As Control = sender.GetNextControl(sender, True)
        Dim cboControl As ComboBox = Nothing

        Do Until currentControl Is Nothing
            If TypeOf currentControl Is TextBox Then
                currentControl.Text = ""
            ElseIf TypeOf currentControl Is ComboBox Then
                cboControl = CType(currentControl, ComboBox)
                If cboControl.DataSource IsNot Nothing Then
                    cboControl.DataSource = Nothing
                Else
                    cboControl.Items.Clear()
                End If
            End If
            currentControl = sender.GetNextControl(currentControl, True)
        Loop
    End Sub
End Module

Clear all TextBox and ComboBox controls within TabControl1.

TabControl1.ClearSpecificControls

Clear all controls on a form

ClearSpecificControls


问:
Gitzilla: missing python http.cookiejar module
I am trying to get gitzilla to work for me on ubuntu 14.04 with python 2.7.6 and git 1.9.1.
This is my first time using either python or gitzilla.

After installing gitzilla and adding the symlinks for git hooks, pushing changes gives the following output:

```<code>geoff@jenkins:~/Example$ git push origin master
Counting objects: 5, done.
Writing objects: 100% (3/3), 282 bytes | 0 bytes/s, done.
Total 3 (delta 0), reused 0 (delta 0)
remote: Traceback (most recent call last):
remote:   File "hooks/update", line 9, in <module>
remote:     load_entry_point('gitzilla==2.0', 'console_scripts', 'gitzilla-update')()
remote:   File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 351, in load_entry_point
remote:     return get_distribution(dist).load_entry_point(group, name)
remote:   File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 2363, in load_entry_point
remote:     return ep.load()
remote:   File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 2088, in load
remote:     entry = __import__(self.module_name, globals(),globals(), ['__name__'])
remote:   File "build/bdist.linux-x86_64/egg/gitzilla/hookscripts.py", line 11, in <module>
remote:   File "build/bdist.linux-x86_64/egg/gitzilla/hooks.py", line 9, in <module>
remote:   File "build/bdist.linux-x86_64/egg/gitzilla/utils.py", line 10, in <module>
remote:   File "/usr/local/lib/python2.7/dist-packages/bugz/bugzilla.py", line 7, in <module>
remote:     import http.cookiejar
remote: ImportError: No module named http.cookiejar
remote: error: hook declined to update refs/heads/master
To /home/geoff/gitrepos/Example.git/
 ! [remote rejected] master -> master (hook declined)
error: failed to push some refs to '/home/geoff/gitrepos/Example.git/'
</code>```

From this I figure I need http.cookiejar (or cookielib) installed but I don't know how to get it.

I've tried without success:
pip install http.cookiejar and
pip install cookielib

Both times pip complained about not finding anything but then I tried pip install cookiejar which did appear to install it, but I still get the same error
pip install cookiejar

Now this runs without complaint: python -c "import cookiejar"

And this complains the module isn't found: python -c "import http.cookiejar"

Any ideas how to get this working?

答:
Alexander's comment pointed out the problem (almost 3 years ago) which led to the answer shown in the comments to the question.  As seen in the comments, it was a mixup between packages from python2.7 and python3.  If you came here looking to resolve the same actual problem with gitzilla, the patch has been entered back into the master branch now so please use a recent version or the one I linked to in my comments above.

I'm adding this to close the question to stop answer spamming.

Body:
I am trying to get gitzilla to work for me on ubuntu 14.04 with python 2.7.6 and git 1.9.1.
This is my first time using either python or gitzilla.

After installing gitzilla and adding the symlinks for git hooks, pushing changes gives the following output:

geoff@jenkins:~/Example$ git push origin master
Counting objects: 5, done.
Writing objects: 100% (3/3), 282 bytes | 0 bytes/s, done.
Total 3 (delta 0), reused 0 (delta 0)
remote: Traceback (most recent call last):
remote:   File "hooks/update", line 9, in <module>
remote:     load_entry_point('gitzilla==2.0', 'console_scripts', 'gitzilla-update')()
remote:   File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 351, in load_entry_point
remote:     return get_distribution(dist).load_entry_point(group, name)
remote:   File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 2363, in load_entry_point
remote:     return ep.load()
remote:   File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 2088, in load
remote:     entry = __import__(self.module_name, globals(),globals(), ['__name__'])
remote:   File "build/bdist.linux-x86_64/egg/gitzilla/hookscripts.py", line 11, in <module>
remote:   File "build/bdist.linux-x86_64/egg/gitzilla/hooks.py", line 9, in <module>
remote:   File "build/bdist.linux-x86_64/egg/gitzilla/utils.py", line 10, in <module>
remote:   File "/usr/local/lib/python2.7/dist-packages/bugz/bugzilla.py", line 7, in <module>
remote:     import http.cookiejar
remote: ImportError: No module named http.cookiejar
remote: error: hook declined to update refs/heads/master
To /home/geoff/gitrepos/Example.git/
 ! [remote rejected] master -> master (hook declined)
error: failed to push some refs to '/home/geoff/gitrepos/Example.git/'

From this I figure I need http.cookiejar (or cookielib) installed but I don't know how to get it.

I've tried without success:
pip install http.cookiejar and
pip install cookielib

Both times pip complained about not finding anything but then I tried pip install cookiejar which did appear to install it, but I still get the same error
pip install cookiejar

Now this runs without complaint: python -c "import cookiejar"

And this complains the module isn't found: python -c "import http.cookiejar"

Any ideas how to get this working?


问:
How do I create a cancel button?
I am having troubles getting my cancel button to work. I have this action connected to my cancel button and I plan to dismiss the view controller like so:

```<code>@IBAction func cancel(sender: UIBarButtonItem) {
     dismissViewControllerAnimated(true, completion: nil)
}
</code>```

I was wondering what obvious bit I am missing. (This is a bar button item for a table view).

答:
After you add the NavigationBar (and Navigation Item) to the Storyboard using IB, the reference to navigationItem var will be automatically mapped to your ViewController file. Add the code below to attach a cancel button to the navigationItem to dismiss the modal View Controller:</p>
```<code>@IBOutlet weak var navigationBar: UINavigationBar!

override func viewDidLoad() {
    super.viewDidLoad()
    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelClicked(sender:)))
}

func cancelClicked(sender: UIBarButtonItem) {
    print("Cancel clicked!")
    self.dismiss(animated: true, completion: nil)
}
</code>```

Title: How do I create a cancel button?

Body:
I am having troubles getting my cancel button to work. I have this action connected to my cancel button and I plan to dismiss the view controller like so:

@IBAction func cancel(sender: UIBarButtonItem) {
     dismissViewControllerAnimated(true, completion: nil)
}

I was wondering what obvious bit I am missing. (This is a bar button item for a table view).

Body:
After you add the NavigationBar (and Navigation Item) to the Storyboard using IB, the reference to navigationItem var will be automatically mapped to your ViewController file. Add the code below to attach a cancel button to the navigationItem to dismiss the modal View Controller:

@IBOutlet weak var navigationBar: UINavigationBar!

override func viewDidLoad() {
    super.viewDidLoad()
    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelClicked(sender:)))
}

func cancelClicked(sender: UIBarButtonItem) {
    print("Cancel clicked!")
    self.dismiss(animated: true, completion: nil)
}


问:
How to terminate a background while loop in Linux?
I cannot find a way to terminate a background while loop.

I started a Perl script in an infinite while loop (i.e. while true; do perl abc.pl; done) and my terminal session got disconnected.

Now I am trying to terminate that loop.

If I do ps -aux | grep perl, I see that a Perl script is running.

If I do kill -9 <process id>, it keeps showing up with different process IDs.

How can I terminate it for good?

The only work around I have found is to rename my script, and then it stops.

答:
What may be happening is that you are killing the perl program, but the loop throwing them off is still running. You need to kill the entire login tree.

ps -f -u$USER (or something like it, depends on the OS) shows the process id, parent process id, and tty of your processes.

Kill the process and the parent, all the way up the process tree to your unwanted shell running the loop. Notice the tty of the offending process... if different from your current tty kill all processes on that tty; you may need a new terminal window to get a different tty.

Alternate: Linux has ps xjf to show the processes in tree format... start with the relevant shell process and kill that and all child processes.

Extra info: processes that don't go away under kill -9, keeping the same PID (not your condition), are likely "zombie" processes that are waiting for their parent to read their exit status. Zombies have actually stopped and gone away and are not alive so you can't kill them. Only a ghost remains in the process table waiting for the parent to read the pending exit status. Killing the parent will reassign the process to init, which will read the status.


问:
Why is the logic not working in my rails app?
In my apps navbar, I have the following code:
apps/views/layout/application.html.erb:

```<code>    <ul class="nav navbar-nav navbar-right">
        <% if user_signed_in? %>
            <%if current_user.userinfo(&:info_complete) %>
                <li><%= link_to "My profile", userinfo_path(current_user.userinfo.id) %></li>
            <% elsif current_user.employer(&:info_complete)%>
                <li><%= link_to "My profile", employer_path(current_user.employer.id) %></li>
            <%else%>
                <li><%= link_to "Complete Profile", application_studoremp_path %></li>
            <%end%>
            <li><%= link_to "Sign Out", destroy_user_session_path, method: :delete %></li>
        <% else %>
            <li><%= link_to "Log In", new_user_session_path %></li>
            <li><%= link_to "Sign Up", new_user_registration_path %></li>
        <% end %>
    </ul>
</code>```

When a user signs up, they will be directed to a page to choose if they want to continue as an employer or student, then they will be directed to a page to fill out userinfo if they choose student, or fill out the employer info if they choose employer. So between signing up and filling out one of the forms, the user will not have "userinfo.id" OR "employer.id". That's why I redirect them to "application_studoremp_path". But the app throws an error saying userinfo.id is not found. Obviously it's not found because it's not created yet, that's why there is an "else" part. Why is the logic not working? :info_complete is a function in both the userinfo model and the employer model checking if the information has been filled out. Everything works fine if the user is already existing (If the userinfo.id or employer.id already exists).
This is the error:

My userinfo.rb model:

```<code>class Userinfo < ActiveRecord::Base
    belongs_to :user

    def info_complete?
        name? && email? && college? && gpa? && major?
    end
</code>```

答:
You are using method incorrectly.
The notation method(&:other) is a shorthand for method {|i| i.other}. What is happening here is prefix & is the same as calling to_proc method on object prefixed.

Now, userinfo is a getter, and you can pass it a block (of course) but it will be ignored, it is just a getter.

So all you actually do is check whether userinfo is not nil (or false). You also can tell, because (&:info_complete) does not even fire a NoMethodError (and it should, because there is no info_complete, there is info_complete?).

What you should do is to just use userinfo.info_complete? And if you are concerned user_info could be nil, do it with safe navigation operator: userinfo&.info_complete?

Further reading: Ampersand operator
Safe navigation operator

Body:
In my apps navbar, I have the following code:
apps/views/layout/application.html.erb:

        <% if user_signed_in? %>
            <%if current_user.userinfo(&:info_complete) %>

<%= link_to "My profile", userinfo_path(current_user.userinfo.id) %>

            <% elsif current_user.employer(&:info_complete)%>

<%= link_to "My profile", employer_path(current_user.employer.id) %>

            <%else%>

<%= link_to "Complete Profile", application_studoremp_path %>

            <%end%>

<%= link_to "Sign Out", destroy_user_session_path, method: :delete %>

        <% else %>

<%= link_to "Log In", new_user_session_path %>

<%= link_to "Sign Up", new_user_registration_path %>

        <% end %>

When a user signs up, they will be directed to a page to choose if they want to continue as an employer or student, then they will be directed to a page to fill out userinfo if they choose student, or fill out the employer info if they choose employer. So between signing up and filling out one of the forms, the user will not have "userinfo.id" OR "employer.id". That's why I redirect them to "application_studoremp_path". But the app throws an error saying userinfo.id is not found. Obviously it's not found because it's not created yet, that's why there is an "else" part. Why is the logic not working? :info_complete is a function in both the userinfo model and the employer model checking if the information has been filled out. Everything works fine if the user is already existing (If the userinfo.id or employer.id already exists).
This is the error:

My userinfo.rb model:

class Userinfo < ActiveRecord::Base
    belongs_to :user

    def info_complete?
        name? && email? && college? && gpa? && major?
    end


问:
RxJS Observables, check cache before making API request
I'm creating an Angular app and have an API service. My get method only makes an HTTP call if the requested data isn't in the cache. I'm using the Promise-based LocalForage library, and transform them into Observables.

```<code>export class CacheService {
  get(prop: string) {
    return Observable.fromPromise(localForage.getItem(prop));
  }
</code>```

Now in my API service, I'm racing my cache and http observables like so:

```<code>export class ApiService {
  get(uri: string) {
      return Observable.race(
        this.cache
          .get(uri)
          .filter(res => !!res),

        this.http.get(uri)
      );
  }
}
</code>```

Since Observable.race only returns the observable that emits first, I thought that as long I'm using that .filter() operator, everything would work out. However, neither of them are returning if the data isn't in the cache, so the HTTP request is never being made. If someone could point out my mistake or suggest a better solution, I'm all ears.

答:
The problem is race completes as soon as one of the observables is completed. Your cache call doesn't emit the null but completes immediately. You can use merge to keep going after completion and take(1) to consider the first result only:

```<code>export class ApiService {
  get(uri: string) {
      return Observable.merge(
        this.cache
          .get(uri)
          .filter(res => !!res),

        this.http.get(uri)
      ).take(1);
  }
}
</code>```

Body:
I'm creating an Angular app and have an API service. My get method only makes an HTTP call if the requested data isn't in the cache. I'm using the Promise-based LocalForage library, and transform them into Observables.

export class CacheService {
  get(prop: string) {
    return Observable.fromPromise(localForage.getItem(prop));
  }

Now in my API service, I'm racing my cache and http observables like so:

export class ApiService {
  get(uri: string) {
      return Observable.race(
        this.cache
          .get(uri)
          .filter(res => !!res),

        this.http.get(uri)
      );
  }
}

Since Observable.race only returns the observable that emits first, I thought that as long I'm using that .filter() operator, everything would work out. However, neither of them are returning if the data isn't in the cache, so the HTTP request is never being made. If someone could point out my mistake or suggest a better solution, I'm all ears.

Body:
The problem is race completes as soon as one of the observables is completed. Your cache call doesn't emit the null but completes immediately. You can use merge to keep going after completion and take(1) to consider the first result only:

export class ApiService {
  get(uri: string) {
      return Observable.merge(
        this.cache
          .get(uri)
          .filter(res => !!res),

        this.http.get(uri)
      ).take(1);
  }
}


问:
Regarding using date time in a string format
I am trying to figure out how to subtract a date time from today's date but it keeps coming back with a very large amount of days for whenever i enter an enroll date. Here is the code I have so far

```<code>    public string getTimeAsStudent(DateTime EnrolledDate)
    {
        return DateTime.Today.Subtract(EnrolledDate).ToString();

    }

    public string getTimeAsStudent()
    {
        return DateTime.Today.Subtract(oEnrolledDate).TotalDays.ToString();

    }
</code>```

and here is what I have for the test app

```<code> namespace StudentTestApp
   {
    public partial class Form1 : Form
    {
    public Form1()
    {
        InitializeComponent();
    }

    Student.StudentGrades myStudent = new Student.StudentGrades();

    private void getDate_Click(object sender, EventArgs e)
    {
        lblDate.Text = myStudent.getTimeAsStudent().ToString();
    }
}
</code>```

Helper variables

```<code>   public class StudentGrades
   {
    private string oStudentFirstName;
    private string oStudentMiddleName;
    private string oStudentLastName;
    private string oStudentID;
    private string oAddress;
    private string oEmail;
    private DateTime oEnrolledDate;
    private string oMajor;
    private string oPhone;
    private string oZip;
    private List<string> oCourseCompleted;
    private List<string> oCourseQtrYr;
    private List<double> oCourseGrade;
</code>```

However it outputs like 736,000 days for no matter what date i put in, Can anyone help with this??

答:
Here's types of Subtract methods

How To Get Subtract of two DateTime To Years

```<code>public static string getTimeAsYear(DateTime oEnrolledDate)
{
        return (Math.Abs(oEnrolledDate.Year - DateTime.Today.Year)).ToString();
}
</code>```

How To Get Subtract of two DateTime To Month

```<code>public static string getTimeAsMonth(DateTime oEnrolledDate)
{
        return ((Math.Abs(oEnrolledDate.Year - DateTime.Today.Year)) * 12).ToString();
}
</code>```

And Result

DateTime D = new DateTime(1995,01,17);
 Console.WriteLine(getTimeAsStudent(D));
 Console.WriteLine(getTimeAsYear(D));
 Console.WriteLine(getTimeAsMonth(D));

Body:
I am trying to figure out how to subtract a date time from today's date but it keeps coming back with a very large amount of days for whenever i enter an enroll date. Here is the code I have so far

    public string getTimeAsStudent(DateTime EnrolledDate)
    {
        return DateTime.Today.Subtract(EnrolledDate).ToString();

    }

    public string getTimeAsStudent()
    {
        return DateTime.Today.Subtract(oEnrolledDate).TotalDays.ToString();

    }

and here is what I have for the test app

 namespace StudentTestApp
   {
    public partial class Form1 : Form
    {
    public Form1()
    {
        InitializeComponent();
    }

    Student.StudentGrades myStudent = new Student.StudentGrades();

    private void getDate_Click(object sender, EventArgs e)
    {
        lblDate.Text = myStudent.getTimeAsStudent().ToString();
    }
}

Helper variables

   public class StudentGrades
   {
    private string oStudentFirstName;
    private string oStudentMiddleName;
    private string oStudentLastName;
    private string oStudentID;
    private string oAddress;
    private string oEmail;
    private DateTime oEnrolledDate;
    private string oMajor;
    private string oPhone;
    private string oZip;
    private List<string> oCourseCompleted;
    private List<string> oCourseQtrYr;
    private List<double> oCourseGrade;

However it outputs like 736,000 days for no matter what date i put in, Can anyone help with this??

Body:
Here's types of Subtract methods

How To Get Subtract of two DateTime To Years

public static string getTimeAsYear(DateTime oEnrolledDate)
{
        return (Math.Abs(oEnrolledDate.Year - DateTime.Today.Year)).ToString();
}

How To Get Subtract of two DateTime To Month

public static string getTimeAsMonth(DateTime oEnrolledDate)
{
        return ((Math.Abs(oEnrolledDate.Year - DateTime.Today.Year)) * 12).ToString();
}

And Result

DateTime D = new DateTime(1995,01,17);
 Console.WriteLine(getTimeAsStudent(D));
 Console.WriteLine(getTimeAsYear(D));
 Console.WriteLine(getTimeAsMonth(D));


问:
No associated item named wrap_under_create_rule found for type CGContext when using core-graphics
I'm trying to use Quartz2D from Rust in a Mac app through the core-graphics crate, but I'm having trouble using core-graphics. I can obtain a CGContextRef to the current context with:

```<code>let cg_context_ref: CGContextRef = unsafe {
    let ns_graphics_context: *mut Object = msg_send![Class::get("NSGraphicsContext").unwrap(), currentContext];
    msg_send![ns_graphics_context, CGContext]
}
</code>```

Then, I attempt to construct a CGContext from the CGContextRef using wrap_under_create_rule, which comes from pub trait TCFType from core-foundation:

```<code>let gc: CGContext = unsafe {
    CGContext::wrap_under_create_rule(unsafe {
        let ns_graphics_context: *mut Object = msg_send![Class::get("NSGraphicsContext").unwrap(), currentContext];
        msg_send![ns_graphics_context, CGContext]
    })
};
</code>```

However, compiling gives this error:

error: no associated item named `wrap_under_create_rule` found for type `core_graphics::context::CGContext` in the current scope
  --> src/lib.rs:45:9
   |
45 |         CGContext::wrap_under_create_rule(unsafe {
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = help: items from traits can only be used if the trait is in scope; the following trait is implemented but not in scope, perhaps add a `use` for it:
   = help: candidate #1: `use core_foundation::base::TCFType;`
```

<p>I already have <code>use core_foundation::base::TCFType;</code>, and in the same scope, though. It looks like this:</p>

```#[macro_use]
extern crate objc;
extern crate core_foundation;
extern crate core_graphics;

use objc::runtime::{Object, Class};
use core_foundation::base::TCFType;
use core_graphics::context::CGContext;

fn main() {
    let gc: CGContext = unsafe {
        CGContext::wrap_under_create_rule(unsafe {
            let ns_graphics_context: *mut Object = msg_send![Class::get("NSGraphicsContext").unwrap(), currentContext];
            msg_send![ns_graphics_context, CGContext]
        })
    };
}
```

I'm a bit of a Rust noob, so I got stuck here. Why won't this work, and how can I make it work? Modifying core-graphics is an option, since I'm going to have to do it later down the road anyways.

答:
Chances are good that you are dealing with two different versions of TCFType. Following your example, I saw the same error. I then ran cargo-tree:

$ cargo tree
cg v0.1.0 (file:///private/tmp/cg)
├── core-foundation v0.4.0               <---- here
│   ├── core-foundation-sys v0.4.0
│   │   └── libc v0.2.23
│   └── libc v0.2.23 (*)
├── core-graphics v0.8.1
│   ├── bitflags v0.8.2
│   ├── core-foundation v0.3.0           <---- here
│   │   ├── core-foundation-sys v0.3.1
│   │   │   └── libc v0.2.23 (*)
│   │   └── libc v0.2.23 (*)
│   └── libc v0.2.23 (*)
└── objc v0.2.2
    └── malloc_buf v0.0.6
        └── libc v0.2.23 (*)
```

From this, I can see that core-graphics is depending on core-foundation 0.3.0, but your crate depends on core-foundation 0.4.0.

Types provided by two different versions of crates are not the same, and the compiler tells you so. It just doesn't tell you that the versions differ.

To fix it, restrict your version of core-foundation to 0.3.0. Doing this caused this error to go away for me, but then there were some unrelated errors that were previously hidden.

Body:
I'm trying to use Quartz2D from Rust in a Mac app through the core-graphics crate, but I'm having trouble using core-graphics. I can obtain a CGContextRef to the current context with:

let cg_context_ref: CGContextRef = unsafe {
    let ns_graphics_context: *mut Object = msg_send![Class::get("NSGraphicsContext").unwrap(), currentContext];
    msg_send![ns_graphics_context, CGContext]
}

Then, I attempt to construct a CGContext from the CGContextRef using wrap_under_create_rule, which comes from pub trait TCFType from core-foundation:

let gc: CGContext = unsafe {
    CGContext::wrap_under_create_rule(unsafe {
        let ns_graphics_context: *mut Object = msg_send![Class::get("NSGraphicsContext").unwrap(), currentContext];
        msg_send![ns_graphics_context, CGContext]
    })
};

However, compiling gives this error:

error: no associated item named `wrap_under_create_rule` found for type `core_graphics::context::CGContext` in the current scope
  --> src/lib.rs:45:9
   |
45 |         CGContext::wrap_under_create_rule(unsafe {
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = help: items from traits can only be used if the trait is in scope; the following trait is implemented but not in scope, perhaps add a `use` for it:
   = help: candidate #1: `use core_foundation::base::TCFType;`

I already have use core_foundation::base::TCFType;, and in the same scope, though. It looks like this:

#[macro_use]
extern crate objc;
extern crate core_foundation;
extern crate core_graphics;

use objc::runtime::{Object, Class};
use core_foundation::base::TCFType;
use core_graphics::context::CGContext;

fn main() {
    let gc: CGContext = unsafe {
        CGContext::wrap_under_create_rule(unsafe {
            let ns_graphics_context: *mut Object = msg_send![Class::get("NSGraphicsContext").unwrap(), currentContext];
            msg_send![ns_graphics_context, CGContext]
        })
    };
}

I'm a bit of a Rust noob, so I got stuck here. Why won't this work, and how can I make it work? Modifying core-graphics is an option, since I'm going to have to do it later down the road anyways.

Body:
Chances are good that you are dealing with two different versions of TCFType. Following your example, I saw the same error. I then ran cargo-tree:

$ cargo tree
cg v0.1.0 (file:///private/tmp/cg)
├── core-foundation v0.4.0               <---- here
│   ├── core-foundation-sys v0.4.0
│   │   └── libc v0.2.23
│   └── libc v0.2.23 (*)
├── core-graphics v0.8.1
│   ├── bitflags v0.8.2
│   ├── core-foundation v0.3.0           <---- here
│   │   ├── core-foundation-sys v0.3.1
│   │   │   └── libc v0.2.23 (*)
│   │   └── libc v0.2.23 (*)
│   └── libc v0.2.23 (*)
└── objc v0.2.2
    └── malloc_buf v0.0.6
        └── libc v0.2.23 (*)

From this, I can see that core-graphics is depending on core-foundation 0.3.0, but your crate depends on core-foundation 0.4.0.

Types provided by two different versions of crates are not the same, and the compiler tells you so. It just doesn't tell you that the versions differ.

To fix it, restrict your version of core-foundation to 0.3.0. Doing this caused this error to go away for me, but then there were some unrelated errors that were previously hidden.


问:
Zsh returning `<function>:<linenumber> = not found`
I used the have the following tmux shortcut function defined in a separate script and aliased, which worked fine but was messy. I decided to move it to my .zshrc where it naturally belongs, and encountered a problem I wasn't able to figure out.

```<code>function t () {re='^[0-9]+$'
if [ "$1" == "kill" ]
then
        tmux kill-session -t $2
elif [[ "$1" =~ "$re" ]]
then
        tmux attach-session -d -t $1
fi}
</code>```

I source my .zshrc, call the function, and get:

```<code>t:1: = not found
</code>```

I know the function is defined:

```<code>╭─bennett@Io [~] using
╰─○ which t
t () {
    re='^[0-9]+$'
    if [ "$1" == "kill" ]
    then
            tmux kill-session -t $2
    elif [[ "$1" =~ "$re" ]]
    then
            tmux attach-session -d -t $1
    fi
}
</code>```

I'm assuming this is complaining about the first line of the function. I've tried shifting the first line of the function down several lines, which doesn't change anything except which line the error message refers to. Any clue what's going on? I haven't found anything relating to this specific issue on SO.

答:
The command [ (or test) only supports a single = to check for equality of two strings. Using == will result in a "= not found" error message. (See man 1 test)

zsh has the [ builtin mainly for compatibility reasons. It tries to implement POSIX where possible, with all the quirks this may bring (See the Zsh Manual).

Unless you need a script to be POSIX compliant (e.g. for compatibility with other shells), I would strongly suggest to use conditional expressions, that is [[ ... ]], instead of [ ... ]. It has more features, does not require quotes or other workarounds for possibly empty values and even allows to use arithmetic expressions.

Body:
I used the have the following tmux shortcut function defined in a separate script and aliased, which worked fine but was messy. I decided to move it to my .zshrc where it naturally belongs, and encountered a problem I wasn't able to figure out.

function t () {re='^[0-9]+$'
if [ "$1" == "kill" ]
then
        tmux kill-session -t $2
elif [[ "$1" =~ "$re" ]]
then
        tmux attach-session -d -t $1
fi}

I source my .zshrc, call the function, and get:

t:1: = not found

I know the function is defined:

╭─bennett@Io [~] using
╰─○ which t
t () {
    re='^[0-9]+$'
    if [ "$1" == "kill" ]
    then
            tmux kill-session -t $2
    elif [[ "$1" =~ "$re" ]]
    then
            tmux attach-session -d -t $1
    fi
}

I'm assuming this is complaining about the first line of the function. I've tried shifting the first line of the function down several lines, which doesn't change anything except which line the error message refers to. Any clue what's going on? I haven't found anything relating to this specific issue on SO.