问:
Pivoting a Pandas Dataframe containing strings - 'No numeric types to aggregate' error
There is a good number of questions about this error, but after looking around I'm still not able to find/wrap my mind around a solution yet.
I'm trying to pivot a data frame with strings, to get some row data to become columns, but not working out so far.

Shape of my df

```<code><class 'pandas.core.frame.DataFrame'>
Int64Index: 515932 entries, 0 to 515931
Data columns (total 5 columns):
id                 515932 non-null object
cc_contact_id      515932 non-null object
Network_Name       515932 non-null object
question           515932 non-null object
response_answer    515932 non-null object
dtypes: object(5)
memory usage: 23.6+ MB
</code>```

Sample format

```<code>id  contact_id  question    response_answer
16  137519  2206    State   Ca
17  137520  2206    State   Ca
18  137521  2206    State   Ca
19  137522  2206    State   Ca
20  137523  2208    City    Lancaster
21  137524  2208    City    Lancaster
22  137525  2208    City    Lancaster
23  137526  2208    City    Lancaster
24  137527  2208    Trip_End Location   Home
25  137528  2208    Trip_End Location   Home
26  137529  2208    Trip_End Location   Home
27  137530  2208    Trip_End Location   Home
</code>```

What I would like to pivot to

```<code>id  contact_id      State   City       Trip_End Location
16  137519  2206    Ca      None       None None
20  137523  2208    None    Lancaster  None None
24  137527  2208    None    None       None Home
etc. etc.
</code>```

Where the question values become the columns, with the response_answer being in it's corresponding column, and retaining the ids

What I have tried

```<code>unified_df = pd.DataFrame(unified_data, columns=target_table_headers, dtype=object)

pivot_table = unified_df.pivot_table('response_answer',['id','cc_contact_id'],'question')
# OR
pivot_table = unified_df.pivot_table('response_answer','question')
</code>```

DataError: No numeric types to aggregate

What is the way to pivot a data frame with string values?

答:
There are several ways.

1

```<code>df1 = df.groupby(["id","contact_id","Network_Name","question"])['response_answer'].aggregate(lambda x: x).unstack().reset_index()
df1.columns=df1.columns.tolist()
print (df1)
</code>```

2

```<code>df1 = df.set_index(["id","contact_id","Network_Name","question"])['response_answer'].unstack().reset_index()
df1.columns=df1.columns.tolist()
print (df1)
</code>```

3

```<code>df1 = df.groupby(["id","contact_id","Network_Name","question"])['response_answer'].aggregate('first').unstack().reset_index()
df1.columns=df1.columns.tolist()
print (df1)
</code>```

4

```<code>df1 = df.pivot_table(index=["id","contact_id","Network_Name"], columns='question', values=['response_answer'], aggfunc='first')
df1.columns = df1.columns.droplevel()
df1 = df1.reset_index()
df1.columns=df1.columns.tolist()
print (df1)
</code>```

Same ans.

```<code>    id  contact_id  Network_Name       City State Trip_End_Location
0   16      137519          2206       None    Ca              None
1   17      137520          2206       None    Ca              None
2   18      137521          2206       None    Ca              None
3   19      137522          2206       None    Ca              None
4   20      137523          2208  Lancaster  None              None
5   21      137524          2208  Lancaster  None              None
6   22      137525          2208  Lancaster  None              None
7   23      137526          2208  Lancaster  None              None
8   24      137527          2208       None  None              Home
9   25      137528          2208       None  None              Home
10  26      137529          2208       None  None              Home
11  27      137530          2208       None  None              Home
</code>```

Body:
There is a good number of questions about this error, but after looking around I'm still not able to find/wrap my mind around a solution yet.
I'm trying to pivot a data frame with strings, to get some row data to become columns, but not working out so far.

Shape of my df

<class 'pandas.core.frame.DataFrame'>
Int64Index: 515932 entries, 0 to 515931
Data columns (total 5 columns):
id                 515932 non-null object
cc_contact_id      515932 non-null object
Network_Name       515932 non-null object
question           515932 non-null object
response_answer    515932 non-null object
dtypes: object(5)
memory usage: 23.6+ MB

Sample format

id  contact_id  question    response_answer
16  137519  2206    State   Ca
17  137520  2206    State   Ca
18  137521  2206    State   Ca
19  137522  2206    State   Ca
20  137523  2208    City    Lancaster
21  137524  2208    City    Lancaster
22  137525  2208    City    Lancaster
23  137526  2208    City    Lancaster
24  137527  2208    Trip_End Location   Home
25  137528  2208    Trip_End Location   Home
26  137529  2208    Trip_End Location   Home
27  137530  2208    Trip_End Location   Home

What I would like to pivot to

id  contact_id      State   City       Trip_End Location
16  137519  2206    Ca      None       None None
20  137523  2208    None    Lancaster  None None
24  137527  2208    None    None       None Home
etc. etc.

Where the question values become the columns, with the response_answer being in it's corresponding column, and retaining the ids

What I have tried

unified_df = pd.DataFrame(unified_data, columns=target_table_headers, dtype=object)

pivot_table = unified_df.pivot_table('response_answer',['id','cc_contact_id'],'question')
# OR
pivot_table = unified_df.pivot_table('response_answer','question')

DataError: No numeric types to aggregate

What is the way to pivot a data frame with string values?

Body:
There are several ways.

1

df1 = df.groupby(["id","contact_id","Network_Name","question"])['response_answer'].aggregate(lambda x: x).unstack().reset_index()
df1.columns=df1.columns.tolist()
print (df1)

2

df1 = df.set_index(["id","contact_id","Network_Name","question"])['response_answer'].unstack().reset_index()
df1.columns=df1.columns.tolist()
print (df1)

3

df1 = df.groupby(["id","contact_id","Network_Name","question"])['response_answer'].aggregate('first').unstack().reset_index()
df1.columns=df1.columns.tolist()
print (df1)

4

df1 = df.pivot_table(index=["id","contact_id","Network_Name"], columns='question', values=['response_answer'], aggfunc='first')
df1.columns = df1.columns.droplevel()
df1 = df1.reset_index()
df1.columns=df1.columns.tolist()
print (df1)

Same ans.

    id  contact_id  Network_Name       City State Trip_End_Location
0   16      137519          2206       None    Ca              None
1   17      137520          2206       None    Ca              None
2   18      137521          2206       None    Ca              None
3   19      137522          2206       None    Ca              None
4   20      137523          2208  Lancaster  None              None
5   21      137524          2208  Lancaster  None              None
6   22      137525          2208  Lancaster  None              None
7   23      137526          2208  Lancaster  None              None
8   24      137527          2208       None  None              Home
9   25      137528          2208       None  None              Home
10  26      137529          2208       None  None              Home
11  27      137530          2208       None  None              Home


来源: stackexchange

问:
Add css to button
how could add css style to this button.
Button html:

```<code><html>
    <body>
        <button onclick="myFunction()">Player</button>
        <script>
            function myFunction() {
                alert('what ever');
            }
        </script>
    </body>
</html>
</code>```

CSS i want to add

```<code><style>
.button {
  background-color: #4CAF50;
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  cursor: pointer;
}
</style>
</code>```

If there is answered question, please send link. Thank you

答:
You could add class="button" to the button to make it work. Cause your CSS .button will be used on every element which has the class="button"

 function myFunction() {
    alert('what ever')
 }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.button {
background-color: #4CAF50;
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}</code>```

<button class="button" onclick="myFunction()">Player</button>```

Read more about how CSS Selectors work here

ContentLicense: CC BY-SA 3.0

Title: Add css to button

Body:
how could add css style to this button.
Button html:

        <button onclick="myFunction()">Player</button>

CSS i want to add

If there is answered question, please send link. Thank you

Body:
You could add class="button" to the button to make it work. Cause your CSS .button will be used on every element which has the class="button"

 function myFunction() {
    alert('what ever')
 }

.button {
background-color: #4CAF50;
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}

<button class="button" onclick="myFunction()">Player</button>

Read more about how CSS Selectors work here


问:
Remote ssh fails when server ip changes
I use Dyndns to provide a domain name to outside clients, e.g. ralph.com, so that when my provider changes my IP address, they can still access my site. This works. However, when I try to administer the server using ssh remotely, I get messages about invalid ssh key and “man in the middle” attacks. I am unable to connect to the server to correct the ssh key problem.  What can I do to either connect when this happens, or prevent this from happening?</p>

答:
The only thing you can do is to disable the host key verification.

ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no

See here for more details : http://linuxcommando.blogspot.fr/2008/10/how-to-disable-ssh-host-key-checking.html

Title: Remote ssh fails when server ip changes


问:
Check how long was a button pressed
I am making a simulator in which I have a button with different behavior depending on the duration of the press.

If the button is pressed less than 3 seconds, prints nothing, between 3 and 10, prints 1 and higher than 10 prints 2.

Should I try with MouseListener or ActionListener? Any example code would be great! Thanks.

答:
A simple hack:
Create a timer and start the timer as soon as the button is pressed. Set the interval of the timer to one second then have a counter that increments each time the timer event is fired to keep track of how many seconds it was pressed. As soon as the button is released stop the timer and perform any action you want to</p>

Title: Check how long was a button pressed


问:
Starting a screen and executing a bash command in Python
So in Python, I am trying to create a unix screen and have it execute a command but it does not work.
The screen isn't event created and I can't see it if I run screen -ls

This is the code:

```<code>def run_screen_with_command(command):
    screens = []

    command = ['screen', '-d', '-m', '-S', 'myscreen', 'bash', '-c', "'{}'".format(command)]
    process = subprocess.Popen(command,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT)

    process.wait()
    print(process.stderr, process.stdout.read())
    #returncode = process.wait()
    print ' '.join(command)

    return process

run_screen_with_command('sleep 10')
</code>```

答:
You don't need to quote the argument for bash -c, since the shell isn't executing it.

```<code>command = ['screen', '-d', '-m', '-S', 'myscreen', 'bash', '-c', command]
</code>```

Body:
So in Python, I am trying to create a unix screen and have it execute a command but it does not work.
The screen isn't event created and I can't see it if I run screen -ls

This is the code:

def run_screen_with_command(command):
    screens = []

    command = ['screen', '-d', '-m', '-S', 'myscreen', 'bash', '-c', "'{}'".format(command)]
    process = subprocess.Popen(command,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT)

    process.wait()
    print(process.stderr, process.stdout.read())
    #returncode = process.wait()
    print ' '.join(command)

    return process

run_screen_with_command('sleep 10')

Body:
You don't need to quote the argument for bash -c, since the shell isn't executing it.

command = ['screen', '-d', '-m', '-S', 'myscreen', 'bash', '-c', command]


问:
save image in xampp and show it in web php
The HTML upload form:

```<code><form action="InformationData.php" method="post" enctype="multipart/form-data">
    <label >Barangay Certification</label>
    <input name="BarangayCertification" type="file" id="exampleInputFile1">
    <button type="Submit" name="Submit" value="Upload">Submit</button>
</form>
</code>```

The InformationData.php:

```<code><?php
$conn = mysqli_connect("localhost", "root", "", "registration");

if($_POST['BarangayCertification']){
    $BarangayCertification =   $_POST['BarangayCertification'];
} else {
    $BarangayCertification =  "";
}

$sql = "INSERT INTO stakeholdersform (BarangayCertification) VALUES ($BarangayCertification);
?>
</code>```

Code to show the image:

```<code><?php
$conn = mysqli_connect("localhost", "root", "", "registration");
$informations = "SELECT * FROM stakeholderinformations";
$result = $conn->query($informations);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $BarangayCertification = $row['BarangayCertification'];
        echo $BarangayCertification;
    }
}
?>
</code>```

I tried to echo it but nothing happens, but I can see the image in the database.

答:
If connection to databases is set correctly.this below code work.But at first you must create a directory upload in the root

form

```<code><form action="InformationData.php" method="post" enctype="multipart/form-data">
    <label >Barangay Certification</label>
    <input name="BarangayCertification" type="file" id="exampleInputFile1">
    <button type="Submit" name="Submit" value="Upload">Submit</button>
</form>
</code>```

The InformationData.php:

```<code><?php
$conn = mysqli_connect("localhost", "root", "", "registration");

if (isset($_POST("Submit"))){
if($_POST['BarangayCertification']){
   // $BarangayCertification =   $_POST['BarangayCertification'];
            if (file_exists("upload/" . $_FILES["BarangayCertification"]["name"])) {
            echo $_FILES["BarangayCertification"]["name"] . " <b>already exists.</b> ";
            } else {
                 ///creat upload in root
            move_uploaded_file($_FILES["BarangayCertification"]["tmp_name"], "upload/" . $_FILES["BarangayCertification"]["name"]);
            $BarangayCertification = "//".$_SERVER['HTTP_HOST'].'//'. "upload/" . $_FILES["file"]["name"];

            }
} else {
    $BarangayCertification =  "";
}
}
$sql = "INSERT INTO stakeholdersform (BarangayCertification) VALUES ($BarangayCertification)";
?>
</code>```

Code to show the image:

```<code><?php
$conn = mysqli_connect("localhost", "root", "", "registration");
$informations = "SELECT * FROM stakeholderinformations";
$result = $conn->query($informations);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $BarangayCertification = $row['BarangayCertification'];
        echo "<img src=".$BarangayCertification.">";
    }
}
?>
</code>```

Body:
The HTML upload form:

<form action="InformationData.php" method="post" enctype="multipart/form-data">
    Barangay Certification
    <input name="BarangayCertification" type="file" id="exampleInputFile1">
    <button type="Submit" name="Submit" value="Upload">Submit</button>
</form>

The InformationData.php:

<?php
$conn = mysqli_connect("localhost", "root", "", "registration");

if($_POST['BarangayCertification']){
    $BarangayCertification =   $_POST['BarangayCertification'];
} else {
    $BarangayCertification =  "";
}

$sql = "INSERT INTO stakeholdersform (BarangayCertification) VALUES ($BarangayCertification);
?>

Code to show the image:

<?php
$conn = mysqli_connect("localhost", "root", "", "registration");
$informations = "SELECT * FROM stakeholderinformations";
$result = $conn->query($informations);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $BarangayCertification = $row['BarangayCertification'];
        echo $BarangayCertification;
    }
}
?>

I tried to echo it but nothing happens, but I can see the image in the database.

Body:
If connection to databases is set correctly.this below code work.But at first you must create a directory upload in the root

form

<form action="InformationData.php" method="post" enctype="multipart/form-data">
    <label >Barangay Certification</label>
    <input name="BarangayCertification" type="file" id="exampleInputFile1">
    <button type="Submit" name="Submit" value="Upload">Submit</button>
</form>

The InformationData.php:

<?php
$conn = mysqli_connect("localhost", "root", "", "registration");

if (isset($_POST("Submit"))){
if($_POST['BarangayCertification']){
   // $BarangayCertification =   $_POST['BarangayCertification'];
            if (file_exists("upload/" . $_FILES["BarangayCertification"]["name"])) {
            echo $_FILES["BarangayCertification"]["name"] . " <b>already exists.</b> ";
            } else {
                 ///creat upload in root
            move_uploaded_file($_FILES["BarangayCertification"]["tmp_name"], "upload/" . $_FILES["BarangayCertification"]["name"]);
            $BarangayCertification = "//".$_SERVER['HTTP_HOST'].'//'. "upload/" . $_FILES["file"]["name"];

            }
} else {
    $BarangayCertification =  "";
}
}
$sql = "INSERT INTO stakeholdersform (BarangayCertification) VALUES ($BarangayCertification)";
?>

Code to show the image:

<?php
$conn = mysqli_connect("localhost", "root", "", "registration");
$informations = "SELECT * FROM stakeholderinformations";
$result = $conn->query($informations);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $BarangayCertification = $row['BarangayCertification'];
        echo "<img src=".$BarangayCertification.">";
    }
}
?>


问:
Get precise position of user device with GPS
In my Android application i need to get the traveled road with car and i check it with google android directions API and GPS.

But the problem is that some times the GPS location is not precise and i can get an error of 10Km for some lecture and that means that in a total travel of 150km my "distance traveled" can be 250km and it's wrong!

Yesterday i test it in highway and the problem is that when the marker is located out from highway, the calculation of distance traveled from my current position and the last marker located by road is very wrong (in this case out of the highway).

There is some best way for getting traveled distance with car using the phone?
Maybe some better code for getting more precise GPS position?
Here is my code:

```<code>private void getUserLocation() {

    Log.d(TAG, "getUserLocation()");
    checkLocationPermission();
    mFusedLocationClient.getLastLocation()
            .addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    // Got last known location. In some rare situations this can be null.
                    if (location != null) {
                        // Logic to handle location object
                        String stringStartLat, stringStartLng;

                        double lat = location.getLatitude();
                        double lng = location.getLongitude();

                        //Start position of device
                        if (travelInfo.getStartLat() == 0 && travelInfo.getStartLng() == 0) {
                            travelInfo.setStartLat(lat);
                            travelInfo.setStartLng(lng);
                            //Set lastcoordinates equals to start
                            travelInfo.setLastLat(lat);
                            travelInfo.setLastLng(lng);
                        }
                        //Current position of device
                        travelInfo.setCurrentLat(lat);
                        travelInfo.setCurrentLng(lng);

                        stringStartLat = Double.toString(travelInfo.getStartLat());
                        stringStartLng = Double.toString(travelInfo.getStartLng());
                        //Set the TextView in the fragment with start coordinates
                        Log.d(TAG,"LatitudeStart: " + stringStartLat);
                        Log.d(TAG,"LongitudeStart: " + stringStartLng);

                        if (startMarker == null) {
                            //Add the user location to the map with a marker
                            LatLng userLoction = new LatLng(travelInfo.getStartLat(), travelInfo.getStartLng());
                            startMarker = googleMap.addMarker(new MarkerOptions()
                                    .position(userLoction)
                                    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE))
                                    .title("Start Position")
                                    .snippet("Show the start position of user"));

                            // For zooming automatically to the location of the marker
                            CameraPosition cameraPosition = new CameraPosition.Builder().target(userLoction).zoom(9).build();
                            googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
                        } else {

                            LatLng currentLocation = new LatLng(travelInfo.getCurrentLat(), travelInfo.getCurrentLng());
                            currentPositionMarker = googleMap.addMarker(new MarkerOptions()
                                    .position(currentLocation)
                                    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW))
                                    .title("Current Position")
                                    .snippet("Show the current position of user during travel"));

                            // For zooming automatically to the location of the marker
                            CameraPosition cameraPosition = new CameraPosition.Builder().target(currentLocation).zoom(11).build();
                            googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
                        }

                        if (travelInfo.getEndLat() != 0 && travelInfo.getEndLng() != 0) {
                            Log.i(TAG, "Dentro if userlocation");
                            //Get total distance of travel
                            getTotalDistanceTime(travelInfo);
                            //Get the percurred distance from last known coordinates
                            getPercurredDistance(travelInfo);
                        }
                    }
                }
            });
}
</code>```

And getpercurredDistance use google direction API with this url

```<code>    String url = "https://maps.googleapis.com/maps/api/directions/json?origin=" + obj.getLastLat() + "," + obj.getLastLng() + "&destination=" + obj.getCurrentLat() + "," + obj.getCurrentLng() + "&mode=driving&key=AI*******************I";
</code>```

For getting distance traveled from last marker and current position marker.
But some times it put the localized position too far from real position... how avoid this?

EDIT

The method that i use is good for my work? mFusedLocationClient.getLastLocation()

答:
There is no possibilities to get more precise GPS position from GPS sensor of android device, but you can filter "wrong" points this ways:

1) for each travel point get several values of Lat and Lng, discard the minimum and maximum and average the remaining ones;

2) log timestamps of each travel point and compare it for two neighboring points: speed (distance between that two points divided by time interval of that points)  grater than max. car speed (e.g. 250 km/h) that means the second point is wrong (if first point is good of course).

3) use Google Maps Roads API to find  best-fit road geometry for a given set of GPS coordinates.

Also take a look at this question.

Body:
In my Android application i need to get the traveled road with car and i check it with google android directions API and GPS.

But the problem is that some times the GPS location is not precise and i can get an error of 10Km for some lecture and that means that in a total travel of 150km my "distance traveled" can be 250km and it's wrong!

Yesterday i test it in highway and the problem is that when the marker is located out from highway, the calculation of distance traveled from my current position and the last marker located by road is very wrong (in this case out of the highway).

There is some best way for getting traveled distance with car using the phone?
Maybe some better code for getting more precise GPS position?
Here is my code:

private void getUserLocation() {

    Log.d(TAG, "getUserLocation()");
    checkLocationPermission();
    mFusedLocationClient.getLastLocation()
            .addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    // Got last known location. In some rare situations this can be null.
                    if (location != null) {
                        // Logic to handle location object
                        String stringStartLat, stringStartLng;

                        double lat = location.getLatitude();
                        double lng = location.getLongitude();

                        //Start position of device
                        if (travelInfo.getStartLat() == 0 && travelInfo.getStartLng() == 0) {
                            travelInfo.setStartLat(lat);
                            travelInfo.setStartLng(lng);
                            //Set lastcoordinates equals to start
                            travelInfo.setLastLat(lat);
                            travelInfo.setLastLng(lng);
                        }
                        //Current position of device
                        travelInfo.setCurrentLat(lat);
                        travelInfo.setCurrentLng(lng);

                        stringStartLat = Double.toString(travelInfo.getStartLat());
                        stringStartLng = Double.toString(travelInfo.getStartLng());
                        //Set the TextView in the fragment with start coordinates
                        Log.d(TAG,"LatitudeStart: " + stringStartLat);
                        Log.d(TAG,"LongitudeStart: " + stringStartLng);

                        if (startMarker == null) {
                            //Add the user location to the map with a marker
                            LatLng userLoction = new LatLng(travelInfo.getStartLat(), travelInfo.getStartLng());
                            startMarker = googleMap.addMarker(new MarkerOptions()
                                    .position(userLoction)
                                    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE))
                                    .title("Start Position")
                                    .snippet("Show the start position of user"));

                            // For zooming automatically to the location of the marker
                            CameraPosition cameraPosition = new CameraPosition.Builder().target(userLoction).zoom(9).build();
                            googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
                        } else {

                            LatLng currentLocation = new LatLng(travelInfo.getCurrentLat(), travelInfo.getCurrentLng());
                            currentPositionMarker = googleMap.addMarker(new MarkerOptions()
                                    .position(currentLocation)
                                    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW))
                                    .title("Current Position")
                                    .snippet("Show the current position of user during travel"));

                            // For zooming automatically to the location of the marker
                            CameraPosition cameraPosition = new CameraPosition.Builder().target(currentLocation).zoom(11).build();
                            googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
                        }

                        if (travelInfo.getEndLat() != 0 && travelInfo.getEndLng() != 0) {
                            Log.i(TAG, "Dentro if userlocation");
                            //Get total distance of travel
                            getTotalDistanceTime(travelInfo);
                            //Get the percurred distance from last known coordinates
                            getPercurredDistance(travelInfo);
                        }
                    }
                }
            });
}

And getpercurredDistance use google direction API with this url

    String url = "https://maps.googleapis.com/maps/api/directions/json?origin=" + obj.getLastLat() + "," + obj.getLastLng() + "&destination=" + obj.getCurrentLat() + "," + obj.getCurrentLng() + "&mode=driving&key=AI*******************I";

For getting distance traveled from last marker and current position marker.
But some times it put the localized position too far from real position... how avoid this?

EDIT

The method that i use is good for my work? mFusedLocationClient.getLastLocation()


问:
Restrict Login for All pages for not logged in User: Symfony3
I am using fos bundle for Symfony and it's working fine but now I want to restrict all pages for not logged user except (login and register). How can I achieve that?

答:
I assume, that you use FosUserBundle and as stated in the comments, it's all explained in the Docs.

Have a look at "Step 4: Configure your application's security.yml"


问:
Attached property of type list but without an encolsed tag
I'm following this answer, but when I comment out the container

```<code>            <tly:MyDataGridHelper.HiddenCols>
                <!--  <tly:LabelCollection>  -->
                    <Label Name="SomeProp"/>
                    <Label Name="DisplayName"/>
                <!--</tly:LabelCollection>  -->
            </tly:MyDataGridHelper.HiddenCols>
</code>```

and I change only the name of the string passed to RegisterAttached

```<code>    public static readonly DependencyProperty HiddenColsProperty =
        DependencyProperty.RegisterAttached("HiddenColsInternal", typeof(LabelCollection), typeof(MyDataGridHelper), new PropertyMetadata
        {
            PropertyChangedCallback = (obj, e) =>
            {
                var grid = (DataGrid)obj;
                if (grid != null) {
                    var arr = ((LabelCollection)e.NewValue).Cast<Label>().ToArray();
                    hidden[grid.Name] = (arr ?? new Label[0]).Select(l => l.Name).ToArray();
               }
            }
        });
</code>```

but if I have to initialize the collection in the getter

```<code>    public static LabelCollection GetHiddenCols(DependencyObject obj)
    {
        var collection = (LabelCollection)obj.GetValue(HiddenColsProperty);
        if (collection == null) {
            collection = new LabelCollection();
            obj.SetValue(HiddenColsProperty, collection);
        }
        return collection;
    }
</code>```

then my values (my label names: "SomeProp" and "DisplayName" for example) are lost. What am I doing wrong? How am I supposed to get them?

At the moment my workaround is to keep the envelop <tly:LabelCollection> (and everything works in this case)

答:
There is an important difference between the two versions of your XAML.

While

```<code><tly:MyDataGridHelper.HiddenCols>
    <tly:LabelCollection>
        <Label Name="SomeProp"/>
        <Label Name="DisplayName"/>
    </tly:LabelCollection>
</tly:MyDataGridHelper.HiddenCols>
</code>```

creates and populates a new collection object before assigning it to the HiddenCols property,

```<code><tly:MyDataGridHelper.HiddenCols>
    <Label Name="SomeProp"/>
    <Label Name="DisplayName"/>
</tly:MyDataGridHelper.HiddenCols>
</code>```

just populates an already created collection instance that had been assigned to the property before being populated.

However, your PropertyChanged callback expects an already populated collection, so you have to use the first variant.

For the second variant, the collection type could probably implement the INotifyCollectionChanged interface, and you could attach a CollectionChanged event handler. Or you access the property later, e.g. in a Loaded event handler.

Body:
I'm following this answer, but when I comment out the container

            <tly:MyDataGridHelper.HiddenCols>

            </tly:MyDataGridHelper.HiddenCols>

and I change only the name of the string passed to RegisterAttached

    public static readonly DependencyProperty HiddenColsProperty =
        DependencyProperty.RegisterAttached("HiddenColsInternal", typeof(LabelCollection), typeof(MyDataGridHelper), new PropertyMetadata
        {
            PropertyChangedCallback = (obj, e) =>
            {
                var grid = (DataGrid)obj;
                if (grid != null) {
                    var arr = ((LabelCollection)e.NewValue).Cast().ToArray();
                    hidden[grid.Name] = (arr ?? new Label[0]).Select(l => l.Name).ToArray();
               }
            }
        });

but if I have to initialize the collection in the getter

    public static LabelCollection GetHiddenCols(DependencyObject obj)
    {
        var collection = (LabelCollection)obj.GetValue(HiddenColsProperty);
        if (collection == null) {
            collection = new LabelCollection();
            obj.SetValue(HiddenColsProperty, collection);
        }
        return collection;
    }

then my values (my label names: "SomeProp" and "DisplayName" for example) are lost. What am I doing wrong? How am I supposed to get them?

At the moment my workaround is to keep the envelop <tly:LabelCollection> (and everything works in this case)

Body:
There is an important difference between the two versions of your XAML.

While

<tly:MyDataGridHelper.HiddenCols>
    <tly:LabelCollection>
        <Label Name="SomeProp"/>
        <Label Name="DisplayName"/>
    </tly:LabelCollection>
</tly:MyDataGridHelper.HiddenCols>

creates and populates a new collection object before assigning it to the HiddenCols property,

<tly:MyDataGridHelper.HiddenCols>
    <Label Name="SomeProp"/>
    <Label Name="DisplayName"/>
</tly:MyDataGridHelper.HiddenCols>

just populates an already created collection instance that had been assigned to the property before being populated.

However, your PropertyChanged callback expects an already populated collection, so you have to use the first variant.

For the second variant, the collection type could probably implement the INotifyCollectionChanged interface, and you could attach a CollectionChanged event handler. Or you access the property later, e.g. in a Loaded event handler.


问:
Capturing html code from a website - The remote server returned an error: (407) Proxy Authentication Required
I'd like to capture the HTML code off a page and place it into a text file. Unfortunatel I get an error of the following:

"The remote server returned an error: (407) Proxy Authentication Required."

Anyone know how to solve this?

```<code>    string url = @"http://www.panalpina.com/www/global/en/tools_resources/unit_converter/currency_codes.html";
    HttpWebRequest myWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
    myWebRequest.Method = "GET";
    // make request for web page
    myWebRequest.ToString();

    HttpWebResponse myWebResponse = (HttpWebResponse)myWebRequest.GetResponse();
    StreamReader myWebSource = new StreamReader(myWebResponse.GetResponseStream());
    string myPageSource = string.Empty;
    myPageSource = myWebSource.ReadToEnd();
    myWebResponse.Close();

    `
</code>```

答:
It seems you are using proxy server to connect to internet.
If yes add next code before http request send:</p>

```<code>myWebRequest.Proxy = new WebProxy("you_proxy_machine", 8080 /*port*/);
myWebRequest.Proxy.Credentials = new NetworkCredential("proxy_username", proxy_password");
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'd like to capture the HTML code off a page and place it into a text file. Unfortunatel I get an error of the following:

"The remote server returned an error: (407) Proxy Authentication Required."

Anyone know how to solve this?

    string url = @"http://www.panalpina.com/www/global/en/tools_resources/unit_converter/currency_codes.html";
    HttpWebRequest myWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
    myWebRequest.Method = "GET";
    // make request for web page
    myWebRequest.ToString();

    HttpWebResponse myWebResponse = (HttpWebResponse)myWebRequest.GetResponse();
    StreamReader myWebSource = new StreamReader(myWebResponse.GetResponseStream());
    string myPageSource = string.Empty;
    myPageSource = myWebSource.ReadToEnd();
    myWebResponse.Close();

    `

Body:
It seems you are using proxy server to connect to internet.
If yes add next code before http request send:

myWebRequest.Proxy = new WebProxy("you_proxy_machine", 8080 /*port*/);
myWebRequest.Proxy.Credentials = new NetworkCredential("proxy_username", proxy_password");


问:
XPath 1.0 select siblings with namespaces
I have the following xml file

```<code><root xmlns="http://mynamespace">
  <parent>
    <first>text</first>
    <second>more</second>
  </parent>
  <parent>
    <first>2</first>
    <second>3</second>
  </parent>
  <parent>
    <first>aa</first>
    <second>bb</second>
  </parent>
</root>
</code>```

I'm trying to get first and second children of parent.

C# seems to have problems with the following code (the error is on the last line):

```<code>var rawXml = @"<root xmlns=""http://mynamespace"">
              <parent>
                <first>text</first>
                <second>more</second>
                <third>hello</third>
              </parent>
              <parent>
                <first>2</first>
                <second>3</second>
                <parent>
                  <first>a</first>
                  <second>b</second>
                </parent>
              </parent>
              <parent>
                <first>aa</first>
                <second>bb</second>
              </parent>
            </root>";

var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(rawXml);

var ns = new XmlNamespaceManager(xmlDoc.NameTable);
ns.AddNamespace("m", "http://mynamespace");

var nav = xmlDoc.CreateNavigator();

var parents = nav.Select("//m:parent", ns);

Console.Write($"Got {parents.Count} parents.");

// this does not work
// error: Expression must evaluate to a node-set.
//var siblings = nav.Select("//m:parent/(m:first|m:second)", ns);

// but this does
var siblings = nav.Select("//m:parent/m:first|//m:parent/m:second", ns);
Console.Write($"Got {siblings.Count} children.");
</code>```

Am I missing something? Is the first XPath expression wrong?

答:
Is the first XPath expression wrong?

Yes, it's not valid XPath 1.0 syntax. You can't have a ( after a / in XPath 1.0.

You can achieve what you're trying to do, without repeating any node names, by using this path:

/m:root/m:parent/*[self::m:first or self::m:second]
```

Side note: avoid using // unless you have a specific reason to use it. It's bad for performance.

Body:
I have the following xml file

<root xmlns="http://mynamespace">
  <parent>
    <first>text</first>
    <second>more</second>
  </parent>
  <parent>
    <first>2</first>
    <second>3</second>
  </parent>
  <parent>
    <first>aa</first>
    <second>bb</second>
  </parent>
</root>

I'm trying to get first and second children of parent.

C# seems to have problems with the following code (the error is on the last line):

var rawXml = @"<root xmlns=""http://mynamespace"">
              <parent>
                <first>text</first>
                <second>more</second>
                <third>hello</third>
              </parent>
              <parent>
                <first>2</first>
                <second>3</second>
                <parent>
                  <first>a</first>
                  <second>b</second>
                </parent>
              </parent>
              <parent>
                <first>aa</first>
                <second>bb</second>
              </parent>
            </root>";

var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(rawXml);

var ns = new XmlNamespaceManager(xmlDoc.NameTable);
ns.AddNamespace("m", "http://mynamespace");

var nav = xmlDoc.CreateNavigator();

var parents = nav.Select("//m:parent", ns);

Console.Write($"Got {parents.Count} parents.");

// this does not work
// error: Expression must evaluate to a node-set.
//var siblings = nav.Select("//m:parent/(m:first|m:second)", ns);

// but this does
var siblings = nav.Select("//m:parent/m:first|//m:parent/m:second", ns);
Console.Write($"Got {siblings.Count} children.");

Am I missing something? Is the first XPath expression wrong?

Body:
Is the first XPath expression wrong?

Yes, it's not valid XPath 1.0 syntax. You can't have a ( after a / in XPath 1.0.

You can achieve what you're trying to do, without repeating any node names, by using this path:

/m:root/m:parent/*[self::m:first or self::m:second]

Side note: avoid using // unless you have a specific reason to use it. It's bad for performance.


问:
Set CornerRadius of CheckBox in code behind
I have an application that allows multiple selection of items in the UI with checkboxes. The thing is checkboxes are generated from a file because the company adds or removes selections from the search.

Since I read a file to get all the possible selections available, the checkbox is generated in C# code, not XAML and one requirement for the UI is to have rounded checkboxes. How can I achieve this in C#?

I did this in XAML:

```<code><CheckBox Content="QA Standard" IsEnabled="{Binding CanEdit, UpdateSourceTrigger=PropertyChanged}"
      ToolTip="{Binding StatusInfo, UpdateSourceTrigger=PropertyChanged}"
      BorderBrush="{Binding StatusColor, UpdateSourceTrigger=PropertyChanged}"
      BorderThickness="2"
      Margin="5" >
<CheckBox.Resources>
    <Style TargetType="{x:Type Border}">
        <Setter Property="CornerRadius" Value="12" />
    </Style>
</CheckBox.Resources>
</code>```

Tried to redo it in C# but doesn't seems to work:

```<code>CheckBox c = new CheckBox() { BorderThickness = new Thickness(2), Content = b, Margin = new Thickness(5) };

var enabled = new Binding() { Source = DataContext, Path = new PropertyPath("CanEdit"), Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged };
var tooltip = new Binding() { Source = DataContext, Path = new PropertyPath("StatusInfo"), Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged };
var border = new Binding() { Source = DataContext, Path = new PropertyPath("StatusColor"), Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged };

BindingOperations.SetBinding( c, CheckBox.IsEnabledProperty, enabled );
BindingOperations.SetBinding( c, CheckBox.ToolTipProperty, tooltip );
BindingOperations.SetBinding( c, CheckBox.BorderBrushProperty, border );

var cStyle = new Style( typeof(Border) );
cStyle.Setters.Add( new Setter( Border.CornerRadiusProperty, new CornerRadius( 12.0 ) ) );
c.Resources.Add( "CornerRadiusBorder", cStyle );

Boxes.Children.Add( c );
</code>```

答:
Just change the key of the resource:</p>

```<code>var cStyle = new Style(typeof(Border));
cStyle.Setters.Add(new Setter(Border.CornerRadiusProperty, new CornerRadius(12.0)));
c.Resources.Add(typeof(Border), cStyle);
</code>```

Body:
I have an application that allows multiple selection of items in the UI with checkboxes. The thing is checkboxes are generated from a file because the company adds or removes selections from the search.

Since I read a file to get all the possible selections available, the checkbox is generated in C# code, not XAML and one requirement for the UI is to have rounded checkboxes. How can I achieve this in C#?

I did this in XAML:

<CheckBox Content="QA Standard" IsEnabled="{Binding CanEdit, UpdateSourceTrigger=PropertyChanged}"
      ToolTip="{Binding StatusInfo, UpdateSourceTrigger=PropertyChanged}"
      BorderBrush="{Binding StatusColor, UpdateSourceTrigger=PropertyChanged}"
      BorderThickness="2"
      Margin="5" >
<CheckBox.Resources>

</CheckBox.Resources>

Tried to redo it in C# but doesn't seems to work:

CheckBox c = new CheckBox() { BorderThickness = new Thickness(2), Content = b, Margin = new Thickness(5) };

var enabled = new Binding() { Source = DataContext, Path = new PropertyPath("CanEdit"), Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged };
var tooltip = new Binding() { Source = DataContext, Path = new PropertyPath("StatusInfo"), Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged };
var border = new Binding() { Source = DataContext, Path = new PropertyPath("StatusColor"), Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged };

BindingOperations.SetBinding( c, CheckBox.IsEnabledProperty, enabled );
BindingOperations.SetBinding( c, CheckBox.ToolTipProperty, tooltip );
BindingOperations.SetBinding( c, CheckBox.BorderBrushProperty, border );

var cStyle = new Style( typeof(Border) );
cStyle.Setters.Add( new Setter( Border.CornerRadiusProperty, new CornerRadius( 12.0 ) ) );
c.Resources.Add( "CornerRadiusBorder", cStyle );

Boxes.Children.Add( c );

Body:
Just change the key of the resource:

var cStyle = new Style(typeof(Border));
cStyle.Setters.Add(new Setter(Border.CornerRadiusProperty, new CornerRadius(12.0)));
c.Resources.Add(typeof(Border), cStyle);


问:
atom-editor cmd-click for multi-cursors not working anymore after cmd-click on a hyperlink
atom editor on mac osx related:

I did cmd-click on a hyperlink and got a popup (lost it before able to read),
and now my cmd-click to set multiple cursors is not working any more.

anybody can tell me how to reactivate multi-cursor by cmd-click again?

答: I've solved this issue by changing the trigger keys to shift+control+click, in atom-ide-ui, under the Hyperclick section.


问:
Is C++ compilable with OpenMP and boost on MacOS?
I have tried many things now and have come to some conclusions. Maybe, I oversee something but it seems that I cannot accomplish what I desire.

The question is: Is there any possibility to compile C++ on MacOS High Sierra with OpenMP and boost?

Some findings (correct me if I am wrong):

OpenMP is supported by Clang BUT not by the standard MacOS-clang compiler delivered with MacOS which is ALSO the only compiler XCode9 supports

g++ supports OpenMP

If I install Boost via homebrew, then it will use the clang compiler (which cannot be changed easily), so that libc++ will be used

g++ uses libstdc++ by default which is not easy to change

As a consequence, it seems that I cannot have both... OpenMP is only supported if I use gcc. But gcc uses libstdc++ instead of libc++, so that I get linker errors if I try to link against boost installed via homebrew with libc++.

Is there any chance to get both OpenMP and and boost running?

PS: Please don't link to some >1 year old threads, XCode8 is another story (earlier XCode versions support different compilers) and clang-omp would be another story (it is no longer supported).

答:
Since you mentioned in passing brew install clang-omp, it's been merged into brew install llvm. That's really a very useful choice if you are willing to do it, since you get llvm 5 and C++17 if you need it. It's fully OpenMP compatible using the standard options (ie, -fopenmp).

You can also try my brew formula to use the built-in clang, but you'd still need to set up custom options as in Alexey Bataev's answer. Install with brew:

```<code>brew install cliutils/apple/libomp
</code>```

This only adds the openMP dynamic library and header, nothing else. Then build with:

```<code>clang++ -Xpreprocessor -fopenmp -lomp <other arguments...>
</code>```

See the readme. If you are using cmake, the helper file here might help.

Body:
Since you mentioned in passing brew install clang-omp, it's been merged into brew install llvm. That's really a very useful choice if you are willing to do it, since you get llvm 5 and C++17 if you need it. It's fully OpenMP compatible using the standard options (ie, -fopenmp).

You can also try my brew formula to use the built-in clang, but you'd still need to set up custom options as in Alexey Bataev's answer. Install with brew:

brew install cliutils/apple/libomp

This only adds the openMP dynamic library and header, nothing else. Then build with:

clang++ -Xpreprocessor -fopenmp -lomp <other arguments...>

See the readme. If you are using cmake, the helper file here might help.


答:
```<code><button class="button" onclick="myFunction()">Player</button>
</code>```

As your button class you've set it ".button" add "button" as a class like above
Anything you put after the . will match the name of the class in the element

https://css-tricks.com/the-difference-between-id-and-class/ explains how you use classes, ids and what they do in good detail

Title: Add css to button

Body:
<button class="button" onclick="myFunction()">Player</button>

As your button class you've set it ".button" add "button" as a class like above
Anything you put after the . will match the name of the class in the element

https://css-tricks.com/the-difference-between-id-and-class/ explains how you use classes, ids and what they do in good detail


问:
How to send a notification to another PC?
Is there a way i can send a notification/message to another PC in C/C++? I think something like net send, but i don't know if there is another way to send a notification/message. I created an application which will run on every PC, and i want, that if my application has finished it should send a notification to my PC, that it has finished running. I don't know if there is a solution for my question, but if yes, could someone tell me, how to do that?

Thanks,

kampi

答:
If you want something like "NET SEND" use mailslots!

Here more info on MSDN: http://msdn.microsoft.com/en-us/library/aa365576.aspx


问:
Prevent new line in VS code after formatting
I want the a tag to be in the same line of the li tag here. what setting do i need to change in VS code to fix it.

答:
VSCode has these settings:

// List of tags, comma separated, that shouldn't be reformatted. 'null' defaults to all tags listed at https://www.w3.org/TR/html5/dom.html#phrasing-content.

```<code>  "html.format.unformatted": "wbr",
</code>```

// List of tags, comma separated, where the content shouldn't be
  reformatted. 'null' defaults to the 'pre' tag.

```<code>"html.format.contentUnformatted": "pre,code,textarea",
</code>```

You want to add li to the second option:

```<code>"html.format.contentUnformatted": "pre,code,textarea,li",
</code>```

[Alternatively you could just turn off all html formatting but you probably don't want that.]

// Enable/disable default HTML formatter

```<code> "html.format.enable": false,
</code>```

Body:
VSCode has these settings:

// List of tags, comma separated, that shouldn't be reformatted. 'null' defaults to all tags listed at https://www.w3.org/TR/html5/dom.html#phrasing-content.

  "html.format.unformatted": "wbr",

// List of tags, comma separated, where the content shouldn't be
  reformatted. 'null' defaults to the 'pre' tag.

"html.format.contentUnformatted": "pre,code,textarea",

You want to add li to the second option:

"html.format.contentUnformatted": "pre,code,textarea,li",

[Alternatively you could just turn off all html formatting but you probably don't want that.]

// Enable/disable default HTML formatter

 "html.format.enable": false,


问:
How to keep data sources synchronized with firebase realtime database with Swift?
I am using Firebase realtime database. Data structure is an array of posts, which user can also comment and like.

I retrieve data like this and put them into a local posts array:

```<code>ref.observe(.childAdded, with: { (snapshot) -> Void in
  self.posts.append(snapshot)
  self.tableView.reloadData()
})
</code>```

They are displayed correctly and no problems so far. Now let's say user likes a post. I add his id to likers array of post in local posts array. However firebase database don't know this yet.

My question is what is the correct way to keep local data and firebase data synchronized?

答:
The trick with Firebase is usually to only update the database when the user performs an action, such as liking a post. From that database update you then get a new event, for example a .childChanged for updating the likes. You then update your UI based on the event from the database.

This is sometimes known as a reactive model, or more formally as Command Query Responsibility Segregation: you separate the flow of the commands (from user to database) from the flow of the queries (from database to views).

Body:
I am using Firebase realtime database. Data structure is an array of posts, which user can also comment and like.

I retrieve data like this and put them into a local posts array:

ref.observe(.childAdded, with: { (snapshot) -> Void in
  self.posts.append(snapshot)
  self.tableView.reloadData()
})

They are displayed correctly and no problems so far. Now let's say user likes a post. I add his id to likers array of post in local posts array. However firebase database don't know this yet.

My question is what is the correct way to keep local data and firebase data synchronized?


问:
How to throw observable error in .map for a http status 200 response in Angular 4
In my Angular 4 app, I call a server's login api with http post.  The server always responds with a stauts 200 whether or not the login was successful.  I want to throw an error based on the server response data.

```<code>export class AuthenticationService {
...
login(username: string, password: string): Observable<any> {
    let body = `method=login&username=${username}&password=${password}`;

    return this.http.post('http://localhost/rest.php', body)
        .map((response: Response) => {
            let responsedata = response.json();
            if (responsedata && responsedata.success == 1) {
                localStorage.setItem('loggedin',1);
            } else {
                // Not logged in successfully
                Observable.throw(new Error('Not logged in'));
            }

        });
}
</code>```

And my code calling login()

```<code>trytologin() {
    this.loading = true;
    this.authenticationService.login(this.model.username, this.model.password)
        .subscribe(
            data => {
                // Always returns here regarless of result of login
                this.router.navigate([this.returnUrl]);
            },
            error => {
                // ONLY returns here on a NON-server 200 status
                this.alertService.error(error);
                this.loading = false;
            });
}
</code>```

I think I could intercept the response and change the headers by using HttpInterceptor, however this seems like overkill.  Is there another way to get the subscribe error to trigger from a 200 status response?

EDIT

I tried implementing a HttpInterceptor without success.

```<code>import {HttpClient, HttpHeaders} from '@angular/common/http';
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse,HttpHeaderResponse, HttpErrorResponse} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/map';

@Injectable()
export class LoginInterceptor implements HttpInterceptor {

constructor() {}

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // Need to .map so we can go through each event looking for the HttpResponse
    // Can't use .do() as it doesn't update per the docs
    return next.handle(req).map(event => {
        if (event instanceof HttpResponse) {

            let e2 = new HttpErrorResponse({status: 405, statusText: 'Auth error'});
            // return Observable(e2);   // Cannot return as HttpErrorResponse is NOT part of HttpEvent<any>
            Observable.throw(e2);  // <-- Still triggers the success in .subscribe().  Does NOT trigger the .subscribe() error
            event = event.clone({status: 405, statusText: 'Auth error'});  // <-- change the event status.  Can't return HttpErrorResponse as
        }

        return event;
    });

}
}
</code>```

The .subscribe() success is always called.

I was incorrect.  :-/
EDIT #2

After LOTS of digging, I now know why my code was failing.  But I still don't have a solution!!

The HttpInterceptor is the way to go.....but the Observer.throw() will only work only if the HttpClient.post() is on the same domain!!  The subscribe() error is called if I post() to localhost.  If I call a post() to another domain, it fails to call the subscribe() error.  I put a console.log() immediately after the Observer.throw().  There is log output if I have a different domain.  There is no log output if the domain is the same.    I don't know if this is a CORS issue as I have control over the server output and have included a Access-Control-Allow-Origin: * header item.

Is this possibly a bug in the HttpClient and/or HttpInterceptor???  Or maybe a problem with rxjs??

Edit #3

If I simply return an Observable.throw() in the intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> block my error code gets triggered.  This however will trigger on the http request only. I need to process and throw an error on the http response. In order to do this I need to use return next.handle(req).map() to look for each HttpResponse event.

If I try and execute an Observer.throw() inside the map() it does NOT trigger my error code and is not caught anywhere.  The line after the Observer.throw() is executed.

I can't return Observer.throw() from the map() as it is the incorrect return type.

However, calling a plain javascript throw() inside of the map() will trigger my error code.

I'm not sure if a plain throw() is best practice or if I should be doing something else.

答:
You will have to import proper libraries and methods of Observable to get this code working like

```<code>import { HttpInterceptor, HttpErrorResponse } from '@angular/common/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/Observable/of';
</code>```

You can intercept the response and from that response you can take a decision,

```<code>export class YourInterceptor implements HttpInterceptor{
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>{
              //check your conditions if fall true send this response as given //below
                return Observable.throw(new HttpErrorResponse({status:401, statusText:"Error of auth"}));
        }
}
</code>```

Find the screenshot of a sample code that I tried today,

Body:
In my Angular 4 app, I call a server's login api with http post.  The server always responds with a stauts 200 whether or not the login was successful.  I want to throw an error based on the server response data.

export class AuthenticationService {
...
login(username: string, password: string): Observable<any> {
    let body = `method=login&username=${username}&password=${password}`;

    return this.http.post('http://localhost/rest.php', body)
        .map((response: Response) => {
            let responsedata = response.json();
            if (responsedata && responsedata.success == 1) {
                localStorage.setItem('loggedin',1);
            } else {
                // Not logged in successfully
                Observable.throw(new Error('Not logged in'));
            }

        });
}

And my code calling login()

trytologin() {
    this.loading = true;
    this.authenticationService.login(this.model.username, this.model.password)
        .subscribe(
            data => {
                // Always returns here regarless of result of login
                this.router.navigate([this.returnUrl]);
            },
            error => {
                // ONLY returns here on a NON-server 200 status
                this.alertService.error(error);
                this.loading = false;
            });
}

I think I could intercept the response and change the headers by using HttpInterceptor, however this seems like overkill.  Is there another way to get the subscribe error to trigger from a 200 status response?

EDIT

I tried implementing a HttpInterceptor without success.

import {HttpClient, HttpHeaders} from '@angular/common/http';
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse,HttpHeaderResponse, HttpErrorResponse} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/map';

@Injectable()
export class LoginInterceptor implements HttpInterceptor {

constructor() {}

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // Need to .map so we can go through each event looking for the HttpResponse
    // Can't use .do() as it doesn't update per the docs
    return next.handle(req).map(event => {
        if (event instanceof HttpResponse) {

            let e2 = new HttpErrorResponse({status: 405, statusText: 'Auth error'});
            // return Observable(e2);   // Cannot return as HttpErrorResponse is NOT part of HttpEvent<any>
            Observable.throw(e2);  // <-- Still triggers the success in .subscribe().  Does NOT trigger the .subscribe() error
            event = event.clone({status: 405, statusText: 'Auth error'});  // <-- change the event status.  Can't return HttpErrorResponse as
        }

        return event;
    });

}
}

The .subscribe() success is always called.

I was incorrect.  :-/
EDIT #2

After LOTS of digging, I now know why my code was failing.  But I still don't have a solution!!

The HttpInterceptor is the way to go.....but the Observer.throw() will only work only if the HttpClient.post() is on the same domain!!  The subscribe() error is called if I post() to localhost.  If I call a post() to another domain, it fails to call the subscribe() error.  I put a console.log() immediately after the Observer.throw().  There is log output if I have a different domain.  There is no log output if the domain is the same.    I don't know if this is a CORS issue as I have control over the server output and have included a Access-Control-Allow-Origin: * header item.

Is this possibly a bug in the HttpClient and/or HttpInterceptor???  Or maybe a problem with rxjs??

Edit #3

If I simply return an Observable.throw() in the intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> block my error code gets triggered.  This however will trigger on the http request only. I need to process and throw an error on the http response. In order to do this I need to use return next.handle(req).map() to look for each HttpResponse event.

If I try and execute an Observer.throw() inside the map() it does NOT trigger my error code and is not caught anywhere.  The line after the Observer.throw() is executed.

I can't return Observer.throw() from the map() as it is the incorrect return type.

However, calling a plain javascript throw() inside of the map() will trigger my error code.

I'm not sure if a plain throw() is best practice or if I should be doing something else.

Body:
You will have to import proper libraries and methods of Observable to get this code working like

import { HttpInterceptor, HttpErrorResponse } from '@angular/common/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/Observable/of';

You can intercept the response and from that response you can take a decision,

export class YourInterceptor implements HttpInterceptor{
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>{
              //check your conditions if fall true send this response as given //below
                return Observable.throw(new HttpErrorResponse({status:401, statusText:"Error of auth"}));
        }
}

Find the screenshot of a sample code that I tried today,


问:
Why is my ICollection null?
I established a relationshop One-To-Many between two entities.

And everytime I add a new record with its respective relationship, it isn't being mapped to the other entity with the collection.

This is my class Typology:

```<code>public class Typology
{
    // Rest of fields removed...
    public virtual ICollection<Project> Projects { get; set; }
}
</code>```

And this is my other class (Project):

```<code>public class Project
{
    // Rest of fields removed...
    public Typology Typology { get; set; }
}
</code>```

And I established the relationship through this way:

```<code>// This is my EntityTypeConfiguration for Project.
.HasRequired<Typology>(p => p.Typology)
.WithMany(t => t.Projects);
</code>```

Everytime I need to create a Project, I do it like so:

```<code>Typology typology = dbContext.Typologies.Where(t => t.Id == projectDTO.TypologyId).First();
projectContext.Typology = typology;
</code>```

And then I add and save changes like:

```<code>dbContext.Projects.Add(projectContext);
dbContext.SaveChanges();
</code>```

Now, since this is a One-To-Many Relationship and I add a Typology to my Project object, logically, the project should be added "behind the scenes" to the collection of that typology automatically.

Well, that isn't the case.

While debugging, I tried to get that typology like this:

```<code>Typology typology = dbContext.Typologies.Where(t => t.Id == id).First();
</code>```

The result was that I got all the fields of that typology such as Id, Description, etc, BUT the collection of projects is null.

答:
PROBLEM SOLVED:

I just needed to change this line to my db context's constructor:

Configuration.ProxyCreationEnabled = true;

Since it was marked as false before.

Title: Why is my ICollection null?

Body:
I established a relationshop One-To-Many between two entities.

And everytime I add a new record with its respective relationship, it isn't being mapped to the other entity with the collection.

This is my class Typology:

public class Typology
{
    // Rest of fields removed...
    public virtual ICollection<Project> Projects { get; set; }
}

And this is my other class (Project):

public class Project
{
    // Rest of fields removed...
    public Typology Typology { get; set; }
}

And I established the relationship through this way:

// This is my EntityTypeConfiguration for Project.
.HasRequired<Typology>(p => p.Typology)
.WithMany(t => t.Projects);

Everytime I need to create a Project, I do it like so:

Typology typology = dbContext.Typologies.Where(t => t.Id == projectDTO.TypologyId).First();
projectContext.Typology = typology;

And then I add and save changes like:

dbContext.Projects.Add(projectContext);
dbContext.SaveChanges();

Now, since this is a One-To-Many Relationship and I add a Typology to my Project object, logically, the project should be added "behind the scenes" to the collection of that typology automatically.

Well, that isn't the case.

While debugging, I tried to get that typology like this:

Typology typology = dbContext.Typologies.Where(t => t.Id == id).First();

The result was that I got all the fields of that typology such as Id, Description, etc, BUT the collection of projects is null.


问:
What is the maximal normalized number and what is the maximal not normalized number that can be represented using IEEE-754 Single?
I would love to understand the answers to these queastions :

What is the maximal not normalized number that can be represented using IEEE-754 Single ?

What is the maximal normalized number that can be represented using IEEE-754 Single ?

答:
... to understand the answers to these questions :

Look at the number in its bit pattern and review IEEE-754 Single with its 8 bit biased exponent, and its 23-bit fraction.

Also, look at it with a hexadecimal significant and decimal power-of-2 exponent.  In C, this is done with printf("%a", x);

What is the maximal normalized number that can be represented using IEEE-754 Single ?

```<code>v--------------------------------- Sign
  v------v------------------------ 8 bit biased exponent - max value for finite numbers
           v---------------------v Fraction part of 1.xxx...xxx significand - max value
0 11111110 11111111111111111111111

  v------v-------- All 23 bits of the encoded significand and the implied 1.
            v-v--- Maximum exponent for finite numbers.
0x1.fffffep+127

In decimal
printf("%.9e\n", pow(2,128) - pow(2,128-24));
3.402823466e+38  (approximate)
340282346638528859811704183484516925440   (exact)
</code>```

What is the maximal not normalized number that can be represented using IEEE-754 Single ?

```<code>v--------------------------------- Sign
  v------v------------------------ 8 bit minimum exponent - same as 1 - bias
           v---------------------v Fraction part of 0.xxx...xxx significand  - max value
0 00000000 11111111111111111111111

  v------v-------- All 23 bits of the encoded significand and no implied 1.
            v-v--- Maximum exponent for finite numbers.
0x1.fffffcp-127

In decimal
printf("%.9e\n", pow(2,-126) - pow(2,-126-23));
1.175494211e-38  (approximate)
</code>```

.

```<code>(exact)
1.175494210692441075487029444849287348827052428745893333857174530571588870475618904265502351336181163787841796875e-38
</code>```

Note: rarely are exact decimal values needed.  Values rounded to 9 leading significant decimal digits are sufficient to differentiate all the possible IEEE-754 single.

Body:
... to understand the answers to these questions :

Look at the number in its bit pattern and review IEEE-754 Single with its 8 bit biased exponent, and its 23-bit fraction.

Also, look at it with a hexadecimal significant and decimal power-of-2 exponent.  In C, this is done with printf("%a", x);

What is the maximal normalized number that can be represented using IEEE-754 Single ?

v--------------------------------- Sign
  v------v------------------------ 8 bit biased exponent - max value for finite numbers
           v---------------------v Fraction part of 1.xxx...xxx significand - max value
0 11111110 11111111111111111111111

  v------v-------- All 23 bits of the encoded significand and the implied 1.
            v-v--- Maximum exponent for finite numbers.
0x1.fffffep+127

In decimal
printf("%.9e\n", pow(2,128) - pow(2,128-24));
3.402823466e+38  (approximate)
340282346638528859811704183484516925440   (exact)

What is the maximal not normalized number that can be represented using IEEE-754 Single ?

v--------------------------------- Sign
  v------v------------------------ 8 bit minimum exponent - same as 1 - bias
           v---------------------v Fraction part of 0.xxx...xxx significand  - max value
0 00000000 11111111111111111111111

  v------v-------- All 23 bits of the encoded significand and no implied 1.
            v-v--- Maximum exponent for finite numbers.
0x1.fffffcp-127

In decimal
printf("%.9e\n", pow(2,-126) - pow(2,-126-23));
1.175494211e-38  (approximate)

.

(exact)
1.175494210692441075487029444849287348827052428745893333857174530571588870475618904265502351336181163787841796875e-38

Note: rarely are exact decimal values needed.  Values rounded to 9 leading significant decimal digits are sufficient to differentiate all the possible IEEE-754 single.


问:
IndexOutOfBoundsException?
I'm trying to subtract two positions of different ArrayLists and save the result in another ArrayList but i'm getting the IndexOutOfBoundsException error. I understand how works this error and what it means.
The problem is that when I run my code with the debugger it works fine, but if I run it normally it gives me the error.

Here I declare the variables

Here is the for loop code.

Here is the error

Both Lists, "accels" and "gravs" have the same size 252. I don't understand why step by step it works and all continous no.

答:
This will fix it.    </p>

```<code>for(int i = 0; i < accels.size() && i < gravs.size(); i++) {

}
</code>```

Title: IndexOutOfBoundsException?

Body:
This will fix it.

for(int i = 0; i < accels.size() && i < gravs.size(); i++) {

}


问:
How to use python list in "IN" operator Python Cassandra Driver?
i am using Python Cassandra driver and CQL on back end, i want to update the data with IN operator

a = [1,2,3,4]

I want to run the following query

query = session.execute("update users set status=True where userid IN(%s)",[a])

but it does not work, i want to update the record where userid in list

Can any body help me please?

答:
Try this:</p>

```<code>from cassandra import query

yourquery = session.execute("update users set status=True where userid IN %s", query.ValueSequence([a]));
</code>```

Body:
Try this:

from cassandra import query

yourquery = session.execute("update users set status=True where userid IN %s", query.ValueSequence([a]));

ContentLicense: CC BY-SA 4.0


问:
Fix Github commits which are not counted
I made some commits to github in different times from different clients. Now I see, in my profile some of them don't show up. When I go and check the commit, I can see it there but without my profile picture. From it I understand, this is because of my local configs of clients.

Is there a way I can edit past commits or make the ones with wrong configs show up in my profile ?

EDIT: I can view my commits at github. But ones i made from my mac with profile picture and ones i made from my windows pc, without profile picture. Now i know, when i fix it, my future commits will be counted. What i am asking is what about the past ones ?

答:
Author and committer identity are an integral part of a commit; so to fix existing commits you have to rebase them (that is, replace them with new commits that have the correct metadata).

If anyone else might have fetched the commit as it exists now (or, more accurately, might have fetched any ref that can reach the commit as it exists now) then you need to coordinate with all such users.  If there are many other users, or especially if there are users who are in loose communication and might not immediately be aware of what's going on, then it may not be worth the headaches it will cause.  Also the more new work is based on the commit, the higher the cost of editing it.

If you understand the above and still want to fix it, then the best procedure is

1) Get everyone to push all of their work to the remote
2) Get everyone to discard their clones
3) Fix the commits locally
4) Force-push the fix to the remote
5) Everyone can re-clone

If that's impractical, then you can refer to the section "recovering from upstream rebase" in the git rebase documentation for tips about how each developer can recover without discarding/recloning.

As for how to do the rewrite itself... that again depends on the topology of "other" commits (and refs) that can reach the commit(s) you want to fix.  In the simplest case, if you have

```<code>A -- x1 -- B -- x2 -- C <--(master)
</code>```

with no other refs, no merges, and nobody already working locally on branches that can reach x1, then you can

```<code>git rebase -i --root master
</code>```

You'll get a TODO list with an entry for each commit; locate x1 and x2 and change their command from pick to edit.  After each commit marked for edit, git will pause the rebase.  You can then say

```<code>git commit --amend --reset-author
</code>```

(assuming you've fixed your local config).

If there are multiple branches and/or merges, things get more complicated quickly.  Merges that might contain conflict resolutions (or "evil" changes) are a particular problem.  There are many variations, so if given the above information you need additional help with a specific situation, then I'd need more information (like a sample commit/ref graph).

Body:
Author and committer identity are an integral part of a commit; so to fix existing commits you have to rebase them (that is, replace them with new commits that have the correct metadata).

If anyone else might have fetched the commit as it exists now (or, more accurately, might have fetched any ref that can reach the commit as it exists now) then you need to coordinate with all such users.  If there are many other users, or especially if there are users who are in loose communication and might not immediately be aware of what's going on, then it may not be worth the headaches it will cause.  Also the more new work is based on the commit, the higher the cost of editing it.

If you understand the above and still want to fix it, then the best procedure is

1) Get everyone to push all of their work to the remote
2) Get everyone to discard their clones
3) Fix the commits locally
4) Force-push the fix to the remote
5) Everyone can re-clone

If that's impractical, then you can refer to the section "recovering from upstream rebase" in the git rebase documentation for tips about how each developer can recover without discarding/recloning.

As for how to do the rewrite itself... that again depends on the topology of "other" commits (and refs) that can reach the commit(s) you want to fix.  In the simplest case, if you have

A -- x1 -- B -- x2 -- C <--(master)

with no other refs, no merges, and nobody already working locally on branches that can reach x1, then you can

git rebase -i --root master

You'll get a TODO list with an entry for each commit; locate x1 and x2 and change their command from pick to edit.  After each commit marked for edit, git will pause the rebase.  You can then say

git commit --amend --reset-author

(assuming you've fixed your local config).

If there are multiple branches and/or merges, things get more complicated quickly.  Merges that might contain conflict resolutions (or "evil" changes) are a particular problem.  There are many variations, so if given the above information you need additional help with a specific situation, then I'd need more information (like a sample commit/ref graph).


问:
Rails rack attack gem throttle
I don't know why I can not use rack-attack gem
Here what I did

Gemfile

```<code>gem 'rack-attack'
</code>```

I ve installed the gem

config/application.rb

```<code>config.middleware.use Rack::Attack
</code>```

initializers/rack-attack.rb

```<code>class Rack::Attack

throttle('logins/ip', :limit => 5, :period => 60.seconds) do |req|
  if req.path == '/login' && req.post?
  Rails.logger.error("Rack::Attack Too many login attempts from IP: #{req.ip}")
  req.ip
  end
end

end
</code>```

routes.rb

```<code>post   'login'   => 'index#create'
root 'index#new'
get 'login' => 'index#new'
</code>```

I am using Rails 4.2.3 and the rack-attack gem 4.3.0

I wonder what I miss

答:
make sure you configure cache.store in your initializers/rack-attack.rb file
you can configure it like that:

```<code>class Rack::Attack
  ...
  cache.store = ActiveSupport::Cache::MemoryStore.new
  ...
end
</code>```

Title: Rails rack attack gem throttle

Body:
I don't know why I can not use rack-attack gem
Here what I did

Gemfile

gem 'rack-attack'

I ve installed the gem

config/application.rb

config.middleware.use Rack::Attack

initializers/rack-attack.rb

class Rack::Attack

throttle('logins/ip', :limit => 5, :period => 60.seconds) do |req|
  if req.path == '/login' && req.post?
  Rails.logger.error("Rack::Attack Too many login attempts from IP: #{req.ip}")
  req.ip
  end
end

end

routes.rb

post   'login'   => 'index#create'
root 'index#new'
get 'login' => 'index#new'

I am using Rails 4.2.3 and the rack-attack gem 4.3.0

I wonder what I miss

Body:
make sure you configure cache.store in your initializers/rack-attack.rb file
you can configure it like that:

class Rack::Attack
  ...
  cache.store = ActiveSupport::Cache::MemoryStore.new
  ...
end


问:
Restrict Login for All pages for not logged in User: Symfony3
I am using fos bundle for Symfony and it's working fine but now I want to restrict all pages for not logged user except (login and register). How can I achieve that?

答:
security.yml need to look like this:

```<code>    access_control:
    - { path: ^/(register|login)?$, roles: IS_AUTHENTICATED_ANONYMOUSLY}
    - { path: ^/?$, roles: ROLE_USER}
</code>```

Check Documentation for more Security Symfony !

Greetings Violence

Body:
security.yml need to look like this:

    access_control:
    - { path: ^/(register|login)?$, roles: IS_AUTHENTICATED_ANONYMOUSLY}
    - { path: ^/?$, roles: ROLE_USER}

Check Documentation for more Security Symfony !

Greetings Violence


问:
Remove console.logs with Webpack & Uglify
I am trying to remove console.logs with Webpack's Uglify plugin but it seems that Uglify plugin that comes bundled with Webpack doesn't have that option, its not mentioned in the documentation.

I am initializing uglify from webpack like this:

```<code>new webpack.optimize.UglifyJsPlugin()
</code>```

My understanding is that I can use standalone Uglify lib to get all the options, but I don't know which one?

The problem is that drop_console isn't working.

答:
For uglifyjs-webpack-plugin, wrap options inside an uglifyOptions object: </p>

```<code>    plugins: [
    new UglifyJSPlugin({
        uglifyOptions: {
            compress: {
                drop_console: true
            }
        }
    })
]
</code>```

Body:
I am trying to remove console.logs with Webpack's Uglify plugin but it seems that Uglify plugin that comes bundled with Webpack doesn't have that option, its not mentioned in the documentation.

I am initializing uglify from webpack like this:

new webpack.optimize.UglifyJsPlugin()

My understanding is that I can use standalone Uglify lib to get all the options, but I don't know which one?

The problem is that drop_console isn't working.

Body:
For uglifyjs-webpack-plugin, wrap options inside an uglifyOptions object:

    plugins: [
    new UglifyJSPlugin({
        uglifyOptions: {
            compress: {
                drop_console: true
            }
        }
    })
]


问:
Which plugin do you use for SVN in Visual Studio?
I'm considering using SVN for my .Net projects, and I'd like to know what plugins are available for integrating the source control capabilities directly into the Visual Studio IDE.

I already know about the following Visual Studio extensions:

VisualSVN, which seems great but is not free. It is implemented as a low-level VS package extension. Is anyone using it?

AnkhSVN, which is free but I've heard it's a bit buggy. It is implemented as a VS add-in extension. Is anyone using it? are you experiencing problems? Edit: The 2.0 version is a complete rewrite and seems to solve the problem I've heard about (which were related to the 1.x versions)

Edit : TortoiseSVN + Mindscape's FileExplorer VS Extension, which is not a real IDE integration but somewhat eases the use of TortoiseSVN from Visual Studio.

Edit : I've found a few comparison posts between AnkhSVN and VisualSVN here, here and here.

答:
I use VisualSVN, and love it. It may not be free but I found it extremely reliable, very well integrated, and very much worth the $49 per license. By setting up a few key-bindings comitting and updating become almost second-nature to my entire team (most of whom had no previous SVN/SCC experience).

Being able to quickly scan the solution explorer to see which files had changed was very useful for keeping tabs on things for writing status reports and the like (but that's probably specific to my overly beurocratic manager).

The "Checkout Solution from SVN" feature was great for quickly getting the summer student interns setup and giving them a gentle introduction to version control. Again, this is probably specific to our needs so may not be of interest to you.

So a thumbs-up for VisualSVN and the convenience it gives us.

OwnerDisplayName: Brann

LastEditorDisplayName: Brann

OwnerDisplayName: Chris


问:
Visual Studio displaying errors even if projects build
I have a problem with Visual Studio on a C# solution. It displays totally random errors, but the projects build. Right now, I have 33 files with errors, and I can see red squiggly lines in all of them.

I tried cleaning / rebuilding the solution, closing Visual Studio and even restarting my computer. I can modify .cs files and I see the changes in the solution.

Does anyone have an idea about why it does that?

答:
For my specific case it was a service reference another developer merged into the main branch. Which was perfectly fine except syntax highlight failed to resolve the generated service class and source was all red underlined. Cleaning, rebuilding, restarting did nothing.

All I had to do was refresh the service reference and VS managed to put the pieces together behind the scenes. No changes in the source code or generated files.


问:
Flakiness encountered when attempting to read table row data after an async operation
I have a test suite which involves making selections from a couple of select inputs (using Angular Material) which in turn trigger a table to render some results after an async operation completes.

Once the operation completes, I am attempting to read out the values of a single table row so I can perform some assertions on the values in the table cell.

I am making use of a couple of helpers, one of which takes a string value and uses xpath query to attempt to extract a table row where is finds a row containing table cell that contains the passed in string.

The problem I am facing is that I my expectation expect(cells).toBeDefined() is returning undefined. This happens intermittently, but I would say 75% of the time it fails, so I think the xpath approach is probably not suitable, or I should at least try and wait for at least one table row of data to appear before attempting any assertions. It's worst on our ci server (Jenkins) where it very rarely passes, so it feels like a timing issue of sorts to me.

The screenshot taken by protractor on the test failure is as follows:

Here the comparison period input has been selected from and the table does show a single record, so hence why I feel like this is a timing issue where the data row has not quite rendered in the table between the time the async fetch of data completes and the expectation is performed.

Has anyone got any suggestions of things I could try here? Any recommended recipes I should be following?

答:
I suggest to use cssContainingText as locator. It seems much more suitable for your case

You can get the desired row in once that way just by element-chaining.

It will be something like this:

```<code>cells = element(by.cssContainingText('td span', 'TAYSIDE')).element(by.xpath('ancestor::tr')).all(by.css('td'));
//first part selects the element of the desired row
//second part of the chain selects the next <tr>-parent-element above
//third part selects all td-elements below the selected <tr>-element

//alternatives:
cells = element(by.cssContainingText('td span', value)).element(by.xpath('..')).$$('td');
//by.xpath('..') to select direct parent
//"$$()" is short for "element.all(by.css())"
</code>```

Overall it would look like this:

```<code>describe("full scenario", function(){
    var cells;

    beforeAll(function(){
        common.selectComparisonPeriod(initialPeriod);
        //probably no need to use "then()" here.
        browser.wait(helper.waitForElementToHide(common.spinner), 5000);
        cells = element(by.cssContainingText('td span', value))
            .element(by.xpath('ancestor::tr'))
            .$$('td');
    });
    it("executes test", function(){
        expect(cells).toBeDefined();
    });
});
</code>```

further Options:

use it() instead of beforeAll()

use a browser.wait()-condition to ensure cells-definition

in code:

```<code>describe("full scenario", function(){
    var cells;

    //instead beforeAll, use another it()-block
    it("shall load the correct grid", function(done){
        common.selectComparisonPeriod(initialPeriod);
        //probably no need to use "then()" here.
        browser.wait(helper.waitForElementToHide(common.spinner), 5000);
        cells = element(by.cssContainingText('td span', value))
            .element(by.xpath('ancestor::tr'))
            .$$('td');
        done();
    });
    it("executes test", function(){
        //simplest to just wait for all promises to be resolved (if controlFlow enabled)
        browser.waitForAngular();
        //waits until cells is defined, but for max 5 secs
        browser.wait(typeof(cells) != 'undefined', 5000);
        expect(cells).toBeDefined();
    });
});
</code>```

Body:
I suggest to use cssContainingText as locator. It seems much more suitable for your case

You can get the desired row in once that way just by element-chaining.

It will be something like this:

cells = element(by.cssContainingText('td span', 'TAYSIDE')).element(by.xpath('ancestor::tr')).all(by.css('td'));
//first part selects the element of the desired row
//second part of the chain selects the next <tr>-parent-element above
//third part selects all td-elements below the selected <tr>-element

//alternatives:
cells = element(by.cssContainingText('td span', value)).element(by.xpath('..')).$$('td');
//by.xpath('..') to select direct parent
//"$$()" is short for "element.all(by.css())"

Overall it would look like this:

describe("full scenario", function(){
    var cells;

    beforeAll(function(){
        common.selectComparisonPeriod(initialPeriod);
        //probably no need to use "then()" here.
        browser.wait(helper.waitForElementToHide(common.spinner), 5000);
        cells = element(by.cssContainingText('td span', value))
            .element(by.xpath('ancestor::tr'))
            .$$('td');
    });
    it("executes test", function(){
        expect(cells).toBeDefined();
    });
});

further Options:

use it() instead of beforeAll()

use a browser.wait()-condition to ensure cells-definition

in code:

describe("full scenario", function(){
    var cells;

    //instead beforeAll, use another it()-block
    it("shall load the correct grid", function(done){
        common.selectComparisonPeriod(initialPeriod);
        //probably no need to use "then()" here.
        browser.wait(helper.waitForElementToHide(common.spinner), 5000);
        cells = element(by.cssContainingText('td span', value))
            .element(by.xpath('ancestor::tr'))
            .$$('td');
        done();
    });
    it("executes test", function(){
        //simplest to just wait for all promises to be resolved (if controlFlow enabled)
        browser.waitForAngular();
        //waits until cells is defined, but for max 5 secs
        browser.wait(typeof(cells) != 'undefined', 5000);
        expect(cells).toBeDefined();
    });
});


问:
Add tomcat9 to Eclipse neon
I want to add tomcat 9 to eclipse neon, I go to preferences/Server/Runtime environments/ to add tomcat 9, but there is no apache tomcat 9 to select, the highest selection item is apache tomcat 7, so How to add tomcat 9 to eclipse neon? the eclipse is the newest version, and my computer is Mac os 10.13.

答:
I have even tried to add Tomcat 9 in Eclipse Neon and Luna, and guess what happened, I was getting many errors. So, what is I did I downloaded Eclipse Oxygen and Import all my projects to oxygen. And added Tomcat 9 to "Oxygen" its working fine. The thing is that you need to upgrade the editor. Eclipse has nothing to do with your OS.
I hope this helps you.

Title: Add tomcat9 to Eclipse neon


问:
Integrating maven changes plugin with Jira agile
We have recently migrated to jira agile and the issues have changed from tasks bugs to stories. We have been using maven changes plugin to automatically send notification for new releases and it successfully includes issues resolved and so on. Now that we have stories, it does not include them to the message body. I have updated the configuration properties to include stories also and all possible issue types (Bug, New Feature, Task, Improvement, Sub-task,Story) but still no success. The jira report that is generated by the same plugin is correct but the mail still does not include them.

I also tried to attach the jira report (${basedir}/target/site/jira-report.html) but with no success.

Can anyone propose a solution or a work around too this issue?

答:
After some further research and a lot of code checking in the source code of maven changes plug-in I found out that you have to include the following mapping in your configuration

```<code>            <issueTypes>
                <add>Story</add>
                <fix>Bug</fix>
                <update>Task</update>
            </issueTypes>
</code>```

This will inform the maven changes plug-in to map the build in xsd add,fix,update to Story, Bug, Task issues that are created with agile jira

Body:
After some further research and a lot of code checking in the source code of maven changes plug-in I found out that you have to include the following mapping in your configuration

            <issueTypes>
                <add>Story</add>
                <fix>Bug</fix>
                <update>Task</update>
            </issueTypes>

This will inform the maven changes plug-in to map the build in xsd add,fix,update to Story, Bug, Task issues that are created with agile jira