问:
How to serialize WCF message using DataContractSerializer?
I am trying to serialize WCF message using DataContractSerializer to get the message size (without using service trace viewer). Following is the code snippet:

```<code>public void BeforeSendReply(ref Message reply, object correlationState)
        {
            byte[] bytes = null;
            var messageBuffer = reply.CreateBufferedCopy(Int32.MaxValue);
            var message = messageBuffer.CreateMessage();
            var dcs = new DataContractSerializer(typeof(Message));
            using (var ms = new MemoryStream())
            {
                dcs.WriteObject(ms, message);
                bytes = ms.ToArray();
                Console.WriteLine(String.Format("Message size = {0}", bytes.Count()));
            }
        }
</code>```

On doing so it raises the following exception:

Type
  'System.ServiceModel.Channels.BodyWriterMessage'
  cannot be serialized. Cons ider
  marking it with the
  DataContractAttribute attribute, and
  marking all of its  members you want
  serialized with the
  DataMemberAttribute attribute.  If the
  typ e is a collection, consider
  marking it with the
  CollectionDataContractAttribute.

What can be done?

答: You can call WriteMessage(XmlWriter) on a Message instance in the Created state, if you need to serialize it.

Body:
I am trying to serialize WCF message using DataContractSerializer to get the message size (without using service trace viewer). Following is the code snippet:

public void BeforeSendReply(ref Message reply, object correlationState)
        {
            byte[] bytes = null;
            var messageBuffer = reply.CreateBufferedCopy(Int32.MaxValue);
            var message = messageBuffer.CreateMessage();
            var dcs = new DataContractSerializer(typeof(Message));
            using (var ms = new MemoryStream())
            {
                dcs.WriteObject(ms, message);
                bytes = ms.ToArray();
                Console.WriteLine(String.Format("Message size = {0}", bytes.Count()));
            }
        }

On doing so it raises the following exception:

Type
  'System.ServiceModel.Channels.BodyWriterMessage'
  cannot be serialized. Cons ider
  marking it with the
  DataContractAttribute attribute, and
  marking all of its  members you want
  serialized with the
  DataMemberAttribute attribute.  If the
  typ e is a collection, consider
  marking it with the
  CollectionDataContractAttribute.

What can be done?


来源: stackexchange

问:
How to click on specific element out of the webelements in selenium webdriver in java
If the date from the list of dates is matching with the given date which is string format then it should click on that element from that list of dates which when fetched is converted to string only.
I have list of dates like below when converted to string:

```<code>2017-10-13
2017-09-29
2017-09-22
2017-09-15
2017-09-08
2017-09-01
2017-08-25
2017-08-18
</code>```

So now if the input which is "2017-Sep-29" which when parsed to another format gives 2017-09-29 matches with the second date from the list then it should be clicked but it is throwing an error.

Below is my java code with comments :

```<code>WebDriver driver;
List<WebElement> stageListOfFilters;
String finalSnapshot = "", finalSnapshot1 = "";

@Test
public void getDateAndclick()
{
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
    try {
        Date varDate = dateFormat.parse("18-Aug-2017");
        dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        finalSnapshot1 = dateFormat.format(varDate).toString();
        System.out.println("Date: " + finalSnapshot1); // Prints 2017-08-18
        driver.findElement(By.xpath(config.getsnapshotFilter())).click();
        Thread.sleep(2000);
        finalSnap = finalSnapshot1.substring(5, 10);
        System.out.println("Date for final Comparison: " + finalSnap); // Prints 08-18 since i want to click on 18th august date
        stageListOfFilters = driver.findElements(By.xpath(".//*[@class='QvFrame DS']")); // This collects the list
                                                                                // of dates which is
                                                                                // fetched later on in
                                                                                // for loop
        Thread.sleep(2000);
        for (int i = 0; i < stageListOfFilters.size(); i++) {
            System.out.println(stageListOfFilters.get(i).getText());
            Thread.sleep(2000);
            if (finalSnap.contains(stageListOfFilters.get(i).getText())) {
                driver.findElement(By.xpath(".//*[@class='QvFrame DS']/div/div/div[1]/div[2]/div[" + i + "]"))
                        .click();// If it matches at that index then it should click on element present at that index
                Thread.sleep(2000);
            }
        }
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }
</code>```

So now it should click on the last element since date which is being passed is 18th August but it still clicks on 2017-09-29. I figured out that I am not getting value using get(i).getText() in if loop which is under for loop. Why is it so ?

Code for getAttribute("title") data :

```<code>stageListOfFilters = driver.findElements(By.xpath(".//*[@id='DS']")); // This collects the list
                                                                                // of dates which is
                                                                                // fetched later on in
                                                                                // for loop

            for (WebElement element : stageListOfFilters) {
                System.out.println("Dates are: " + element.getAttribute("title"));
            }
</code>```

答:
Try to access the web elements in loop like show below:</p>

```<code>stageListOfFilters = driver.findElements(By.xpath(".//*[@class='QvFrame DS']"));
Thread.sleep(2000);
for ( WebElement we: stageListOfFilters ) {
    System.out.println(stageListOfFilters.getText());
    if (finalSnapshot1.contains(we.getText())) {
        we.click();
        System.out.println("Data" + we.getText());
        Thread.sleep(2000);
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If the date from the list of dates is matching with the given date which is string format then it should click on that element from that list of dates which when fetched is converted to string only.
I have list of dates like below when converted to string:

2017-10-13
2017-09-29
2017-09-22
2017-09-15
2017-09-08
2017-09-01
2017-08-25
2017-08-18

So now if the input which is "2017-Sep-29" which when parsed to another format gives 2017-09-29 matches with the second date from the list then it should be clicked but it is throwing an error.

Below is my java code with comments :

WebDriver driver;
List<WebElement> stageListOfFilters;
String finalSnapshot = "", finalSnapshot1 = "";

@Test
public void getDateAndclick()
{
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
    try {
        Date varDate = dateFormat.parse("18-Aug-2017");
        dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        finalSnapshot1 = dateFormat.format(varDate).toString();
        System.out.println("Date: " + finalSnapshot1); // Prints 2017-08-18
        driver.findElement(By.xpath(config.getsnapshotFilter())).click();
        Thread.sleep(2000);
        finalSnap = finalSnapshot1.substring(5, 10);
        System.out.println("Date for final Comparison: " + finalSnap); // Prints 08-18 since i want to click on 18th august date
        stageListOfFilters = driver.findElements(By.xpath(".//*[@class='QvFrame DS']")); // This collects the list
                                                                                // of dates which is
                                                                                // fetched later on in
                                                                                // for loop
        Thread.sleep(2000);
        for (int i = 0; i < stageListOfFilters.size(); i++) {
            System.out.println(stageListOfFilters.get(i).getText());
            Thread.sleep(2000);
            if (finalSnap.contains(stageListOfFilters.get(i).getText())) {
                driver.findElement(By.xpath(".//*[@class='QvFrame DS']/div/div/div[1]/div[2]/div[" + i + "]"))
                        .click();// If it matches at that index then it should click on element present at that index
                Thread.sleep(2000);
            }
        }
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }

So now it should click on the last element since date which is being passed is 18th August but it still clicks on 2017-09-29. I figured out that I am not getting value using get(i).getText() in if loop which is under for loop. Why is it so ?

Code for getAttribute("title") data :

stageListOfFilters = driver.findElements(By.xpath(".//*[@id='DS']")); // This collects the list
                                                                                // of dates which is
                                                                                // fetched later on in
                                                                                // for loop

            for (WebElement element : stageListOfFilters) {
                System.out.println("Dates are: " + element.getAttribute("title"));
            }

Body:
Try to access the web elements in loop like show below:

stageListOfFilters = driver.findElements(By.xpath(".//*[@class='QvFrame DS']"));
Thread.sleep(2000);
for ( WebElement we: stageListOfFilters ) {
    System.out.println(stageListOfFilters.getText());
    if (finalSnapshot1.contains(we.getText())) {
        we.click();
        System.out.println("Data" + we.getText());
        Thread.sleep(2000);
    }
}


问:
How to get value from Node in Selenium Webdriver and Print in Console?
I have tried using Webelement to store value but
facing Error like :
[Below is the image of which I want to get value that is K1]

I am Not Getting value through Weblelement as It is displaying Error as

```<code>org.openqa.selenium.InvalidSelectorException: The given selector //div[2]/label/strong/following-sibling::text()
is either invalid or does not result in a WebElement.
</code>```

I just want to store value in variable and print it, I have tried below code but no result :

WebElement Key = driver.findElement(By.xpath("//div[2]/label/strong/following-sibling::text()"));
String vs =Key.getText();
System.out.println("key Name..!!!" + vs);

Suggest Me Opinions

答:
Try with this Xpath to obtain the WebElement:

.//strong[text()='Key']/../..//label

After that with  element.getText() you should have the value : K1

Body:
I have tried using Webelement to store value but
facing Error like :
[Below is the image of which I want to get value that is K1]

I am Not Getting value through Weblelement as It is displaying Error as

org.openqa.selenium.InvalidSelectorException: The given selector //div[2]/label/strong/following-sibling::text()
is either invalid or does not result in a WebElement.

I just want to store value in variable and print it, I have tried below code but no result :

WebElement Key = driver.findElement(By.xpath("//div[2]/label/strong/following-sibling::text()"));
String vs =Key.getText();
System.out.println("key Name..!!!" + vs);

Suggest Me Opinions


问:
Does usage of COSMOS data migration tool consuming any RUs?
Does usage of COSMOS data migration tool for periodical backups (export data to blob storage and then restore it when needed) consuming any RUs ? And does it affect performance or availability of my db operations?
What is recommended solution to implement in COSMOS smth like snapshots for blobs in az storage?</p>

答:
Any operation against Cosmos DB is going to consume RU (that is, each operation has an RU cost). If you're reading content to back up to another source, it's still going to cost you RU during the reads.

As for affecting performance of other db operations: depends on your RU capacity. If you exceed your committed capacity, then you're throttled. If you find yourself being throttled while backing up, you'll need to increase RU accordingly.

There is no "best" solution for backup. Up to you.


问:
Undefined variable: users (View: C:\xampp\htdocs\rentalmobil\resources\views\admin\user.blade.php)

SOLVED

i am confusing that i think i have already make a true code with laravel. i have seen on many references for me to know how to read database. yes i'm newbie and still learning. well here is my code

from model. admin.php is the name of folder:

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Admin extends Model
{
    protected $table = "admin";
}
</code>```

here is my controller. my controller name is UserController.php

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Admin;

class UserController extends Controller
{
    public function users(){
        $users = Admin::all();
        return view('admin.user', ['admin' => $users]);
    }

}
</code>```

and here is my view, it is located in view/admin/ named user.blade.php:

```<code>@extends('admin.header')

@section('content')
<div class="col-md-12">
    <div class="card">
        <div class="header">
            <h4 class="title">Striped Table</h4>
            <p class="category">Here is a subtitle for this table</p>
        </div>
        <div class="content table-responsive table-full-width">
            <table class="table table-striped">
                <thead>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Salary</th>
                    <th>Country</th>
                    <th>City</th>
                </thead>
                <tbody>
                    <tr>
                        <td>1</td>
                        <td>{{ $users->email }}</td>
                        <td>$36,738</td>
                        <td>Niger</td>
                        <td>Oud-Turnhout</td>
                    </tr>
                </tbody>
            </table>

        </div>
    </div>
</div>
@endsection
</code>```

and here is my error

i call from my browser with this http://localhost:8000/users

sorry for bad English :(

答:
Please update your view/admin/user.blade.php and UserController  like:

UserController:

```<code>class UserController extends Controller
{
    public function users(){
        $users = Admin::all();
        return view('admin.user', compact('users'));
    }

}
</code>```

view/admin/user.blade.php:

```<code><tbody>

 @foreach($users as $user)
   <tr>
       <td>1</td>
       <td>{{ $user->email }}</td>
       <td>$36,738</td>
       <td>Niger</td>
       <td>Oud-Turnhout</td>
   </tr>
</tbody>
</code>```

Body:
SOLVED

i am confusing that i think i have already make a true code with laravel. i have seen on many references for me to know how to read database. yes i'm newbie and still learning. well here is my code

from model. admin.php is the name of folder:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Admin extends Model
{
    protected $table = "admin";
}

here is my controller. my controller name is UserController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Admin;

class UserController extends Controller
{
    public function users(){
        $users = Admin::all();
        return view('admin.user', ['admin' => $users]);
    }

}

and here is my view, it is located in view/admin/ named user.blade.php:

@extends('admin.header')

@section('content')

Striped Table

Here is a subtitle for this table

                    ID
                    Name
                    Salary
                    Country
                    City

                        1
                        {{ $users->email }}
                        $36,738
                        Niger
                        Oud-Turnhout

@endsection

and here is my error

i call from my browser with this http://localhost:8000/users

sorry for bad English :(

Body:
Please update your view/admin/user.blade.php and UserController  like:

UserController:

class UserController extends Controller
{
    public function users(){
        $users = Admin::all();
        return view('admin.user', compact('users'));
    }

}

view/admin/user.blade.php:

<tbody>

 @foreach($users as $user)
   <tr>
       <td>1</td>
       <td>{{ $user->email }}</td>
       <td>$36,738</td>
       <td>Niger</td>
       <td>Oud-Turnhout</td>
   </tr>
</tbody>


问:
ANDROID: Error W/DynamiteModule: Local module descriptor class for com.google.android.gms.googlecertificates not found
I am trying to do a MapActivity using Android Studio. It has to show the user’s location.

Well, I know I need a key in order to use the API, and believe me, I changed that key at least four times… I also have the permissions in the AndroidManifest.xml.

The thing is I can show the map without the user’s location, but if I try to show his/her location, then the app compiles well BUT when I try to execute it, it stops and I obtain this error:

```<code>11-12 09:13:28.416 21576-21653/raquel.mapapplication W/DynamiteModule: Local module descriptor class for com.google.android.gms.googlecertificates not found.
11-12 09:13:28.424 21576-21653/raquel.mapapplication I/DynamiteModule: Considering local module com.google.android.gms.googlecertificates:0 and remote module com.google.android.gms.googlecertificates:2
11-12 09:13:28.424 21576-21653/raquel.mapapplication I/DynamiteModule: Selected remote version of com.google.android.gms.googlecertificates, version >= 2
11-12 09:13:28.432 21576-21653/raquel.mapapplication W/System: ClassLoader referenced unknown path: /data/user/0/com.google.android.gms/app_chimera/m/0000000b/n/armeabi
11-12 09:13:28.436 21576-21653/raquel.mapapplication D/GoogleCertificates: com.google.android.gms.googlecertificates module is loaded
11-12 09:13:28.504 21576-21653/raquel.mapapplication D/GoogleCertificatesImpl: Fetched 190 Google release certificates
11-12 09:13:28.505 21576-21653/raquel.mapapplication D/GoogleCertificatesImpl: Fetched 363 Google certificates
11-12 09:13:31.235 21576-21576/raquel.mapapplication I/Process: Sending signal. PID: 21576 SIG: 9
</code>```

It mentions something about Google Certificates, and that is why I thought maybe it has something to do with the key… But I am not sure and I do not have idea what I am doing wrong.

Thank you for your help.

////////

Ok, I will try to post some code... I have been changing the code all the time, but this is the last I tried (I also tried setMyLocationEnable(true), because getMyLocation() is deprecated, but I obtain the same error):

```<code>public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        Location location=mMap.getMyLocation();

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

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(lat, lon);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
}
</code>```

Thanks the person who answered me and the person who edited my comment... I still do not well how to format text...

答:
Loading certificates may be the bug in API and i think somewhere any google developer also have described it that play service is trying to do sign in to verify play app or third party app so that could be error. I do not know more further about it.

but if you are still having trouble with placing marker on user,s position you can try below code i have tested it and is working in application

```<code>@Override
public void onMapReady(GoogleMap googleMap)

{
    myGoogleMap = googleMap;
    placeMarkerOnPosition();
}

public void placeMarkerOnPosition() {
//// check permissions to access resources /////////
if (ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {

    return;
}
    LocationManager locationManager = (LocationManager)
    getSystemService(Context.LOCATION_SERVICE);
</code>```

Now you can find it with two ways

```<code>////////////////  find location if GPS provider is available (GPS should
enable to envoke this callback)

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
new LocationListener()
{
 @Override
 public void onLocationChanged(Location location) {

try {
    Geocoder geocoder = new Geocoder(getApplicationContext());
    myLatitude = location.getLatitude();
    myLongitude = location.getLongitude();
    LatLng myPosition = new LatLng(myLatitude,myLongitude);
    List<Address> places=geocoder.getFromLocation(myLatitude,
    myLongitude,1);
    myLocation = places.get(0).getSubLocality()
                 +""+places.get(0).getLocality();

    myGoogleMap.clear();
    myGoogleMap.addMarker(new
    MarkerOptions().position(myPosition).title(myLocation));

    myGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myPosition,
                                                                 13.5f));

    } catch (IOException e) {
      e.printStackTrace();
    }
   }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {

    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {

    }
    });

////////////////   checking with network providers   /////////

if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {

locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,
                                       0, new LocationListener() {
@Override
public void onLocationChanged(Location location) {
myLatitude = location.getLatitude();
myLongitude = location.getLongitude();
LatLng myPosition = new LatLng(myLatitude, myLongitude);
myGoogleMap.clear();
myGoogleMap.addMarker(new MarkerOptions().position(myPosition).title("My
                                                             Position"));

myGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myPosition,
                                                              13.5f));
</code>```

}

```<code>                @Override
                public void onStatusChanged(String s, int i, Bundle bundle)
                {

                }

                @Override
                public void onProviderEnabled(String s) {

                }

                @Override
                public void onProviderDisabled(String s) {

                }
            });

        }

   ////////  Or you can find it with user  recent location //////////

   Criteria criteria = new Criteria();
   String bestProvider = locationManager.getBestProvider(criteria,true);
   Locationlocation=locationManager.getLastKnownLocation(bestProvider);

   //////////   load your location from last recent locations ////////
            if (location != null) {
                Geocoder geocoder = new Geocoder(getApplicationContext());

                try {
                    myLatitude = location.getLatitude();
                    myLongitude = location.getLongitude();
                    LatLng myPosition = new LatLng(myLatitude, myLongitude);
                    List<Address> places =
                    geocoder.getFromLocation(myLatitude, myLongitude, 1);
                    myLocation = places.get(0).getSubLocality() + " " + places.get(0).getLocality();

                    myGoogleMap.clear();
                    myGoogleMap.addMarker(new MarkerOptions().position(myPosition).title(myLocation));
                    myGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myPosition, 13.5f));

                } catch (IOException e) {
                    e.printStackTrace();
                }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to do a MapActivity using Android Studio. It has to show the user’s location.

Well, I know I need a key in order to use the API, and believe me, I changed that key at least four times… I also have the permissions in the AndroidManifest.xml.

The thing is I can show the map without the user’s location, but if I try to show his/her location, then the app compiles well BUT when I try to execute it, it stops and I obtain this error:

11-12 09:13:28.416 21576-21653/raquel.mapapplication W/DynamiteModule: Local module descriptor class for com.google.android.gms.googlecertificates not found.
11-12 09:13:28.424 21576-21653/raquel.mapapplication I/DynamiteModule: Considering local module com.google.android.gms.googlecertificates:0 and remote module com.google.android.gms.googlecertificates:2
11-12 09:13:28.424 21576-21653/raquel.mapapplication I/DynamiteModule: Selected remote version of com.google.android.gms.googlecertificates, version >= 2
11-12 09:13:28.432 21576-21653/raquel.mapapplication W/System: ClassLoader referenced unknown path: /data/user/0/com.google.android.gms/app_chimera/m/0000000b/n/armeabi
11-12 09:13:28.436 21576-21653/raquel.mapapplication D/GoogleCertificates: com.google.android.gms.googlecertificates module is loaded
11-12 09:13:28.504 21576-21653/raquel.mapapplication D/GoogleCertificatesImpl: Fetched 190 Google release certificates
11-12 09:13:28.505 21576-21653/raquel.mapapplication D/GoogleCertificatesImpl: Fetched 363 Google certificates
11-12 09:13:31.235 21576-21576/raquel.mapapplication I/Process: Sending signal. PID: 21576 SIG: 9

It mentions something about Google Certificates, and that is why I thought maybe it has something to do with the key… But I am not sure and I do not have idea what I am doing wrong.

Thank you for your help.

////////

Ok, I will try to post some code... I have been changing the code all the time, but this is the last I tried (I also tried setMyLocationEnable(true), because getMyLocation() is deprecated, but I obtain the same error):

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        Location location=mMap.getMyLocation();

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

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(lat, lon);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
}

Thanks the person who answered me and the person who edited my comment... I still do not well how to format text...

Body:
Loading certificates may be the bug in API and i think somewhere any google developer also have described it that play service is trying to do sign in to verify play app or third party app so that could be error. I do not know more further about it.

but if you are still having trouble with placing marker on user,s position you can try below code i have tested it and is working in application

@Override
public void onMapReady(GoogleMap googleMap)

{
    myGoogleMap = googleMap;
    placeMarkerOnPosition();
}

public void placeMarkerOnPosition() {
//// check permissions to access resources /////////
if (ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {

    return;
}
    LocationManager locationManager = (LocationManager)
    getSystemService(Context.LOCATION_SERVICE);

Now you can find it with two ways

////////////////  find location if GPS provider is available (GPS should
enable to envoke this callback)

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
new LocationListener()
{
 @Override
 public void onLocationChanged(Location location) {

try {
    Geocoder geocoder = new Geocoder(getApplicationContext());
    myLatitude = location.getLatitude();
    myLongitude = location.getLongitude();
    LatLng myPosition = new LatLng(myLatitude,myLongitude);
    List<Address> places=geocoder.getFromLocation(myLatitude,
    myLongitude,1);
    myLocation = places.get(0).getSubLocality()
                 +""+places.get(0).getLocality();

    myGoogleMap.clear();
    myGoogleMap.addMarker(new
    MarkerOptions().position(myPosition).title(myLocation));

    myGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myPosition,
                                                                 13.5f));

    } catch (IOException e) {
      e.printStackTrace();
    }
   }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {

    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {

    }
    });

////////////////   checking with network providers   /////////

if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {

locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,
                                       0, new LocationListener() {
@Override
public void onLocationChanged(Location location) {
myLatitude = location.getLatitude();
myLongitude = location.getLongitude();
LatLng myPosition = new LatLng(myLatitude, myLongitude);
myGoogleMap.clear();
myGoogleMap.addMarker(new MarkerOptions().position(myPosition).title("My
                                                             Position"));

myGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myPosition,
                                                              13.5f));

}

                @Override
                public void onStatusChanged(String s, int i, Bundle bundle)
                {

                }

                @Override
                public void onProviderEnabled(String s) {

                }

                @Override
                public void onProviderDisabled(String s) {

                }
            });

        }

   ////////  Or you can find it with user  recent location //////////

   Criteria criteria = new Criteria();
   String bestProvider = locationManager.getBestProvider(criteria,true);
   Locationlocation=locationManager.getLastKnownLocation(bestProvider);

   //////////   load your location from last recent locations ////////
            if (location != null) {
                Geocoder geocoder = new Geocoder(getApplicationContext());

                try {
                    myLatitude = location.getLatitude();
                    myLongitude = location.getLongitude();
                    LatLng myPosition = new LatLng(myLatitude, myLongitude);
                    List<Address> places =
                    geocoder.getFromLocation(myLatitude, myLongitude, 1);
                    myLocation = places.get(0).getSubLocality() + " " + places.get(0).getLocality();

                    myGoogleMap.clear();
                    myGoogleMap.addMarker(new MarkerOptions().position(myPosition).title(myLocation));
                    myGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myPosition, 13.5f));

                } catch (IOException e) {
                    e.printStackTrace();
                }


问:
query display data on one row
How can I get the values that are displayd at the rows Total, free, used on one row instead of three rows under each other.

```<code>SELECT
h.host as 'Server',
i.key_,max(x.clock),
case when i.key_ like '%Total%' then x.value end as 'Total',
case when i.key_ like '%free%' then x.value end as 'free',
case when i.key_ like '%used%' then x.value end as 'used',
x.itemid,
x.value
FROM `history_uint` as x
left join items as i on x.itemid = i.itemid
left join hosts as h on h.hostid = i.hostid
Where i.key_ LIKE 'vfs.fs.size%'
group by h.host
</code>```

This is the output I receive at this moment
[Recieved1

Wanted

答:
i.key_ in the select is pointless - it will be indeterminate, otherwise I thing you need conditional aggregation perhaps like this.</p>

```<code>SELECT
 h.host as 'Server',
 max(x.clock),
 sum(case when i.key_ like '%Total%' then x.value else 0 end) as 'Total',
 sum(case when i.key_ like '%free%' then x.value else 0 end) as 'free',
 sum(case when i.key_ like '%used%' then x.value else 0 end) as 'used',
 x.itemid,
 x.value
 FROM `history_uint` as x
 left join items as i on x.itemid = i.itemid
 left join hosts as h on h.hostid = i.hostid
 Where i.key_ LIKE 'vfs.fs.size%'
 group by h.host
</code>```

Title: query display data on one row

Body:
How can I get the values that are displayd at the rows Total, free, used on one row instead of three rows under each other.

SELECT
h.host as 'Server',
i.key_,max(x.clock),
case when i.key_ like '%Total%' then x.value end as 'Total',
case when i.key_ like '%free%' then x.value end as 'free',
case when i.key_ like '%used%' then x.value end as 'used',
x.itemid,
x.value
FROM `history_uint` as x
left join items as i on x.itemid = i.itemid
left join hosts as h on h.hostid = i.hostid
Where i.key_ LIKE 'vfs.fs.size%'
group by h.host

This is the output I receive at this moment
[Recieved1

Wanted

Body:
i.key_ in the select is pointless - it will be indeterminate, otherwise I thing you need conditional aggregation perhaps like this.

SELECT
 h.host as 'Server',
 max(x.clock),
 sum(case when i.key_ like '%Total%' then x.value else 0 end) as 'Total',
 sum(case when i.key_ like '%free%' then x.value else 0 end) as 'free',
 sum(case when i.key_ like '%used%' then x.value else 0 end) as 'used',
 x.itemid,
 x.value
 FROM `history_uint` as x
 left join items as i on x.itemid = i.itemid
 left join hosts as h on h.hostid = i.hostid
 Where i.key_ LIKE 'vfs.fs.size%'
 group by h.host


问:
WebRTC: Does it matter where my TURN server is?
Context: I am going to be setting up a support app for global customers. All my customers are going to be connecting to our support agents who are in one location.

Question: Is there any advantage to also having TURN servers closer to the customers, or is it just as well to have all my TURN servers near my support agents?

Current Understanding: If I understand it right, the connection between Peer 1 and Peer 2 is linear through the TURN servers, i.e.

Peer 1 -> TURN 1 -> TURN 2 -> Peer 2

It seems that it wouldn't matter which leg of that journey is longer unless there's some non-linear behavior leading to a lengthier round-trip leg.

答:
It depends on whether the customer is using TURN/TCP on the Peer 1 -> TURN 1 leg. Doing that on high-latency global links is probably going to result in slightly worse quality than having a udp TURN 1 -> TURN 2 link.

See this blog post for TURN deployment considerations and metrics to track.


问:
distinct, max and group by query in sql
I have a dataset like:

```<code>list1     list2
a          e
a          e
b          w
a          e
a          r
b          c
</code>```

I want to find most frequent item in list2 grouped by list1.

```<code>list1     list2    max
  a         e       3
  b         w       1
</code>```

How can I get rid of the equal number of elements like b,w,1 and b,c,1 ?
I want to have one of them at random.

I tried something like this

```<code>SELECT clf1 as clf2, first(value_count) as max_value
FROM (SELECT list1 as clf1, list2, count(list2) AS value_count FROM table GROUP BY list2,clf1 order by value_count desc)
GROUP BY clf2
</code>```

答:
```<code>Select list1 , List2 , count(List2)  AS value_count
From table Group By list1 , List2
</code>```

Title: distinct, max and group by query in sql

Body:
I have a dataset like:

list1     list2
a          e
a          e
b          w
a          e
a          r
b          c

I want to find most frequent item in list2 grouped by list1.

list1     list2    max
  a         e       3
  b         w       1

How can I get rid of the equal number of elements like b,w,1 and b,c,1 ?
I want to have one of them at random.

I tried something like this

SELECT clf1 as clf2, first(value_count) as max_value
FROM (SELECT list1 as clf1, list2, count(list2) AS value_count FROM table GROUP BY list2,clf1 order by value_count desc)
GROUP BY clf2


问:
How to detect if android phone has dual back camera
How do I detect if android phone has dual back camera

I tried

```<code>CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
    try {
        for(String id: manager.getCameraIdList())
            Log.e("dualtest", id);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
</code>```

but it gives me only 2 ids 0 and 1.

答: Just a personal opinion here, but I don't think that this is possible (although I don't have any proof for this). Usually, the 2 dual cameras are very different on their own: aperture, zoom, colours and so on. They may not work so well on their own, but do a great job when the software combines the input from both. But if the processing software is very good, you don't even need the dual camera setup (take Google's camera app which does an excellent job at this). In conclusion, there is a big variety of how this dual cameras are made, and if a single camera work on some setups, on others it may be totally useless. This is why I believe that even though you have 2 cameras on the back, they are treated as a single camera by the system. Also, given the amount of Android phones manufacturers, there would be hard to align all of them in order to develop an unified API. Depending on the manufacturer, they may give you some APIs to access only one camera, but that will work only on their phones, and until Google doesn't switch to the dual camera setup, I don't believe that there will be an API that provides this feature.</p>

Body:
How do I detect if android phone has dual back camera

I tried

CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
    try {
        for(String id: manager.getCameraIdList())
            Log.e("dualtest", id);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }

but it gives me only 2 ids 0 and 1.


问:
Accessing Android drawable resource with a string
I apologize if this seems really simple but I can't figure it out. I have an ImageButton that I want to change the image of at run-time based on a button click. I have 5 images in my res folder. When the user hits the "Next" button, I want it to go to the next image. The file names of the images are image1.png, image2.png, etc.

I know I you can change the image by doing:

```<code>imgButton.setImageResource(R.drawable.image2);
</code>```

I have a counter (int) to keep track of the image number being displayed. But how would i change the image to the next image? Any help would be appreciated.

答:
You can use reflection to get the id of an image based on a string filename.

```<code>Field f = R.getClass().getField("image2");
int id = f.getInt(null); // use null for static fields
imgButton.setImageResource(id);
</code>```

Edit:
Or as this other question mentioned, you can ask Resources for the id using getIdentifier().  This is slower than getting by static const, but might work for you.

ContentLicense: CC BY-SA 2.5

Body:
I apologize if this seems really simple but I can't figure it out. I have an ImageButton that I want to change the image of at run-time based on a button click. I have 5 images in my res folder. When the user hits the "Next" button, I want it to go to the next image. The file names of the images are image1.png, image2.png, etc.

I know I you can change the image by doing:

imgButton.setImageResource(R.drawable.image2);

I have a counter (int) to keep track of the image number being displayed. But how would i change the image to the next image? Any help would be appreciated.

Body:
You can use reflection to get the id of an image based on a string filename.

Field f = R.getClass().getField("image2");
int id = f.getInt(null); // use null for static fields
imgButton.setImageResource(id);

Edit:
Or as this other question mentioned, you can ask Resources for the id using getIdentifier().  This is slower than getting by static const, but might work for you.


问:
How to print Chinese characters in text file
I am reading the data From text file and Printing in HTML file using java and Html code, But junk characters printing in HTML file

report.reportGenerator("result.txt", reportHTMLFile, testCaseSheetMasterMap, environmentUrl, "01/01/01", "02/02/02");

StringBuilder htmlStringBuilder = new StringBuilder();

        // append html header and title
        //<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
        htmlStringBuilder.append(
                " <meta charset=\"UTF-8\"><title>CitiGR Automation Report</title>");
        // append body
        htmlStringBuilder.append("");
        htmlStringBuilder.append("

" + pageTitle + "

");
        htmlStringBuilder.append("
Environment URL : "+environmentUrl+"");
        htmlStringBuilder.append("

Start Run Time: "+startRunTime);
        htmlStringBuilder.append("
End  Run Time  : "+endRunTime+"
");

        /* append 1st table */
        htmlStringBuilder.append(
                "
<col width=\"50\"><col width=\"200\"><col width=\"200\"><col width=\"100\"><col width=\"100\"><col width=\"100\"><col width=\"100\">");
        // append row - table header
        htmlStringBuilder.append(
                "
"
                + "Si.No.	"
                + "TestCase Name	"
                + "Total no. of scripts executed	"
                + "Pass	"
                + "Fail	"
                + "Pass %	"
                + "Fail %	"
                + "
");

        int count=1;
        for (int i = 0; i < eachTestCaseMenuList.size(); ) {
            htmlStringBuilder.append(""
                    + "
"
                    + ""+count+"	"
                    + ""+ eachTestCaseMenuList.get(i) + "	"
                    + ""+ eachTestCaseMenuList.get(i+1) + "	"
                    + "" + eachTestCaseMenuList.get(i+2)+ "	"
                    + "" + eachTestCaseMenuList.get(i+3) + "	"
                    + "" + eachTestCaseMenuList.get(i+4)+ "	"
                    + "" + eachTestCaseMenuList.get(i+5) + "	"
                    + "
");
            i+=6;
            count++;
        }

        htmlStringBuilder.append(
                "
"
                + "	"
                + "Total	"
                + ""+totalTestCaseCount+"	"
                + ""+totalPassCount+"	"
                + ""+totalFailCount+"	"
                + ""+totalPassPercent+" %	"
                + ""+totalFailPercent+" %	"
                + "
");
```

答:
This will need to go in the  section of your web page.

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

The server should be sending a response header like this:

```<code>Content-Type: text/html; charset=UTF-8
</code>```

If the "charset=UTF-8" bit is missing from the Content-Type response header, or if it says something other than "UTF-8", then this will cause you problems.

Body:
This will need to go in the < head > section of your web page.

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

The server should be sending a response header like this:

Content-Type: text/html; charset=UTF-8

If the "charset=UTF-8" bit is missing from the Content-Type response header, or if it says something other than "UTF-8", then this will cause you problems.


问:
Find element child in WebView byEspressoWeb
Is there any possibility to perform action on WebView page element which does not have any id or name?

```<code>    onWebView()
            .withElement( (...) )
            .perform(webKeys("text"));
</code>```

I am looking for solution in EspressoWeb but if it is not possible in this library, please recommend me better solution.

答:
Try using Locator.XPATH

For example:

```<code>onWebView()
.withElement(findElement(Locator.XPATH,
  "//input[@class='elementClass']"))
.perform(webKeys("text"))
</code>```

Have a look at XPath locator examples for more xpath options.

Body:
Is there any possibility to perform action on WebView page element which does not have any id or name?

    onWebView()
            .withElement( (...) )
            .perform(webKeys("text"));

I am looking for solution in EspressoWeb but if it is not possible in this library, please recommend me better solution.

Body:
Try using Locator.XPATH

For example:

onWebView()
.withElement(findElement(Locator.XPATH,
  "//input[@class='elementClass']"))
.perform(webKeys("text"))

Have a look at XPath locator examples for more xpath options.


问:
How can I pass the response data successfully with function parameter in javascript?
I am working on single page application, which is implementing based on Angular JS, JavaScript, JSON. I am calling one API then I am getting response and this response I want pass as a parameter in function call. I am sharing my code:

abc.JS

```<code> Rh.get('------API URL----').then(function(response){
    var data=response;
          var item = '<a class="btn btn-xs" ng-click="sendDataPost('+"'"+JSON.stringify(data)+"'"+')" >'
           '</a>'
    })

 $scope.sendDataPost = function (data) {
    alert("--");
    console.log(data);
}
</code>```

When I click on anchor tag then sendDataPost function is call and comes into the function definition($scope.sendDataPost). only [object Object] is showing in console. I am not able to pass JSON Data as a parameter. I have seen one link but still I am not able to do because in this link using onclick, but I am using ng-click.
How to pass a json object in js funcion as a function parameter?

I am sharing my sample URL.

JSON SAMPLE URL.

http://www.json-generator.com/api/json/get/cgwLpLgbyq?indent=2

I editing my question. I solve when I am parsing the data in parameter, It is breaking. I am sharing screen shot

sendDataPost parameter is breaking in console and  breaking html page. All json data display in HTML page. How can I pass the response data successfully with function parameter.

答:
Why not you try to holding value in scope variable this below?

```<code>$scope.result = [];
Rh.get('------API URL----').then(function(response){
    $scope.result = response;
})

$scope.sendDataPost = function (data) {
    console.log(data);
}
</code>```

in HTML

```<code>ng-click="sendDataPost(result)"
</code>```

Body:
I am working on single page application, which is implementing based on Angular JS, JavaScript, JSON. I am calling one API then I am getting response and this response I want pass as a parameter in function call. I am sharing my code:

abc.JS

 Rh.get('------API URL----').then(function(response){
    var data=response;
          var item = ''
           ''
    })

 $scope.sendDataPost = function (data) {
    alert("--");
    console.log(data);
}

When I click on anchor tag then sendDataPost function is call and comes into the function definition($scope.sendDataPost). only [object Object] is showing in console. I am not able to pass JSON Data as a parameter. I have seen one link but still I am not able to do because in this link using onclick, but I am using ng-click.
How to pass a json object in js funcion as a function parameter?

I am sharing my sample URL.

JSON SAMPLE URL.

http://www.json-generator.com/api/json/get/cgwLpLgbyq?indent=2

I editing my question. I solve when I am parsing the data in parameter, It is breaking. I am sharing screen shot

sendDataPost parameter is breaking in console and  breaking html page. All json data display in HTML page. How can I pass the response data successfully with function parameter.

Body:
Why not you try to holding value in scope variable this below?

$scope.result = [];
Rh.get('------API URL----').then(function(response){
    $scope.result = response;
})

$scope.sendDataPost = function (data) {
    console.log(data);
}

in HTML

ng-click="sendDataPost(result)"


问:
Are there samples somewhere which use "iPhoneOSGameView"?
Recently I stumbled over "iPhoneOSGameView" which seems to be part of MonoTouch (or MONO?). It seems to be a base view for game development but I cannot find any samples on how to use it. Is there more to it, like animation helpers or sprites? Or is it only a OpenGL wrapper?

René

答: There is an example in the MonoTouch samples here: https://github.com/migueldeicaza/monotouch-samples/blob/master/GLPaint-GV/GLPaint.cs</p>


问:
ERROR: syntax error at or near "student_info" SQL state: 42601 Character: 8
```<code>DELETE student_info,admission_details,parent_info
FROM student_info LEFT JOIN admission_details
ON student_info.student_id = admission_details.student_id
LEFT JOIN parent_info ON admission_details.student_id = parent_info.student_id
WHERE student_info.student_id = 234
</code>```

I am getting error in this code using Postgres 9.1. I used this query for the deleting the 3 tables data.

答:
You can't delete from more than one table at a time. You have to write individual delete statement for each table. You can use joins if you need.

This link may help you solve the problem. Here there is an accepted solution. It uses transaction for deleting from multiple tables.

Body:
DELETE student_info,admission_details,parent_info
FROM student_info LEFT JOIN admission_details
ON student_info.student_id = admission_details.student_id
LEFT JOIN parent_info ON admission_details.student_id = parent_info.student_id
WHERE student_info.student_id = 234

I am getting error in this code using Postgres 9.1. I used this query for the deleting the 3 tables data.


问:
How to open a thread in MFC to run a cuda function?
I now change my cuda program into an MFC project, I wrote the function of .cu as an interface function, So I can call it in MFC's dlg,Because I now use the UI thread call, I want to open a work thread to call, but failed.I am making AfxBeginThread, but it does not recognize my interface function.

I use vs2013, win7.
my interface function like this:

```<code>extern "C" float solveGPU(M_args Parameter_, double Mtime)
</code>```

答:
You could AfxBeginThread use but you have to call yout function from a new function or a static method with he following prototype:

```<code>UINT __cdecl MyControllingFunction( LPVOID pParam );
</code>```

like this:

```<code>UINT __cdecl SolveGPUThreadFunction( LPVOID pParam )
{
    YourDialogClass* pThis = (YourDialogClass*)(pParam);

    pThis->result= solveGPU(pThis->Parameter_, pThis->Mtime);
}
</code>```

and pass this pointer of your dialog as pParam of AfxBeginThread:

```<code>CWinThread* pCUDAThread = AfxBeginThread(&SolveGPUThreadFunction, this);
</code>```

But you can think about using the std::thread instead.

Body:
I now change my cuda program into an MFC project, I wrote the function of .cu as an interface function, So I can call it in MFC's dlg,Because I now use the UI thread call, I want to open a work thread to call, but failed.I am making AfxBeginThread, but it does not recognize my interface function.

I use vs2013, win7.
my interface function like this:

extern "C" float solveGPU(M_args Parameter_, double Mtime)

Body:
You could AfxBeginThread use but you have to call yout function from a new function or a static method with he following prototype:

UINT __cdecl MyControllingFunction( LPVOID pParam );

like this:

UINT __cdecl SolveGPUThreadFunction( LPVOID pParam )
{
    YourDialogClass* pThis = (YourDialogClass*)(pParam);

    pThis->result= solveGPU(pThis->Parameter_, pThis->Mtime);
}

and pass this pointer of your dialog as pParam of AfxBeginThread:

CWinThread* pCUDAThread = AfxBeginThread(&SolveGPUThreadFunction, this);

But you can think about using the std::thread instead.


问:
Querying for a String inside a Set in Spring Data MongodDB repository
I have Set inside a class as follows:

```<code>@Document(collection="Foo")
public class Foo {

   @Id
   String id;

   @Indexed
   Set<String> bars = new HashSet<String>();
}
</code>```

I then have the following repository for it:

```<code>public interface FooRepository  extends PagingAndSortingRepository<Foo, String>{

   public List<Foo> findByBars(String bar);

}
</code>```

The code works fine (all Junits I have for it work) but, unfortunately, I get a compilation warning:

FooRepository.java    Parameter type (String) does not match domain class
  property definition (Set).    Unknown Spring Data Problem

If I change the parameter from "String bar" to "Set< String> bar" the compilation warning goes away. But I do want to query with String and not have to create a Set. Any idea how to resolve?

答: Method findByBars generate a query by field bars. Parameter bar should have same type with bars.

Body:
I have Set inside a class as follows:

@Document(collection="Foo")
public class Foo {

   @Id
   String id;

   @Indexed
   Set<String> bars = new HashSet<String>();
}

I then have the following repository for it:

public interface FooRepository  extends PagingAndSortingRepository<Foo, String>{

   public List<Foo> findByBars(String bar);

}

The code works fine (all Junits I have for it work) but, unfortunately, I get a compilation warning:

FooRepository.java    Parameter type (String) does not match domain class
  property definition (Set).    Unknown Spring Data Problem

If I change the parameter from "String bar" to "Set< String> bar" the compilation warning goes away. But I do want to query with String and not have to create a Set. Any idea how to resolve?


问:
Verifying checksum for files in HDFS
I'm using webhdfs to ingest data from Local file system to HDFS. Now I want to ensure integrity of files ingested into HDFS.

How can I make sure transferred files are not corrrupted/altered etc?

I used below webhdfs command to get the checksum of file

```<code>curl -i -L --negotiate -u: -X GET "http://$hostname:$port/webhdfs/v1/user/path?op=GETFILECHECKSUM"
</code>```

How should I use above checksum to ensure the integrity of Ingested files? please suggest

Below is the steps I'm following

```<code>>md5sum locale_file
740c461879b484f4f5960aa4f67a145b

 >hadoop fs -checksum locale_file
locale_file     MD5-of-0MD5-of-512CRC32C        000002000000000000000000f4ec0c298cd6196ffdd8148ae536c9fe
</code>```

Checksum of file on local system is different than same file on HDFS I need to compare checksum how can I do that?

答:
It can be done from the console like below

```<code>$ md5sum locale_file
740c461879b484f4f5960aa4f67a145b

$ hadoop fs -cat locale_file |md5sum -
740c461879b484f4f5960aa4f67a145b -
</code>```

You can also verify local file via code

```<code>import java.io._
import org.apache.commons.codec.digest.DigestUtils;

val md5sum = DigestUtils.md5Hex("locale_file")
</code>```

and for the Hadoop

```<code>import org.apache.hadoop.fs._
import org.apache.hadoop.io._

val md5sum = MD5Hash.digest(FileSystem.get(hadoopConfiguration).open(new Path("locale_file"))).toString
</code>```

Title: Verifying checksum for files in HDFS

Body:
I'm using webhdfs to ingest data from Local file system to HDFS. Now I want to ensure integrity of files ingested into HDFS.

How can I make sure transferred files are not corrrupted/altered etc?

I used below webhdfs command to get the checksum of file

curl -i -L --negotiate -u: -X GET "http://$hostname:$port/webhdfs/v1/user/path?op=GETFILECHECKSUM"

How should I use above checksum to ensure the integrity of Ingested files? please suggest

Below is the steps I'm following

>md5sum locale_file
740c461879b484f4f5960aa4f67a145b

 >hadoop fs -checksum locale_file
locale_file     MD5-of-0MD5-of-512CRC32C        000002000000000000000000f4ec0c298cd6196ffdd8148ae536c9fe

Checksum of file on local system is different than same file on HDFS I need to compare checksum how can I do that?

Body:
It can be done from the console like below

$ md5sum locale_file
740c461879b484f4f5960aa4f67a145b

$ hadoop fs -cat locale_file |md5sum -
740c461879b484f4f5960aa4f67a145b -

You can also verify local file via code

import java.io._
import org.apache.commons.codec.digest.DigestUtils;

val md5sum = DigestUtils.md5Hex("locale_file")

and for the Hadoop

import org.apache.hadoop.fs._
import org.apache.hadoop.io._

val md5sum = MD5Hash.digest(FileSystem.get(hadoopConfiguration).open(new Path("locale_file"))).toString


问:
Type mismatch: cannot convert from double to int
Need to write a program to calculate sum of all digits and then give results when the total sum vaue ends with 5 or 8.Please help correct this code!</p>

```<code>import java.util.Scanner;
public class Main {

    public static void main(String[] args) {

        Scanner in= new Scanner(System.in);
        int customerID = in.nextInt();
        while(customerID > 0)
        {
        int Reminder = customerID % 10;
        int sum = sum+ Reminder;
        customerID = customerID / 10;
        }
        if(sum%5||sum%8)
        {
        System.out.println("Lucky Customer");
        }else
        {
        System.out.println("Unlucky Customer");
        }
        if(sum <0)
        {
        System.out.println("Invalid Input");
        }
        }
        }
</code>```

答:
Please correct your code to remove some compilation errors...</p>

```<code>import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner in= new Scanner(System.in);
        int customerID = in.nextInt();
        int sum = 0;
        while(customerID > 0) {
            int Reminder = customerID % 10;
            sum = sum + Reminder;
            customerID = customerID / 10;
        }
        if(sum % 5 == 0 || sum % 8 == 0) {
            System.out.println("Lucky Customer");
        } else {
            System.out.println("Unlucky Customer");
        }
        if(sum <0) {
            System.out.println("Invalid Input");
        }
    }
}
</code>```

Body:
Need to write a program to calculate sum of all digits and then give results when the total sum vaue ends with 5 or 8.Please help correct this code!

import java.util.Scanner;
public class Main {

    public static void main(String[] args) {

        Scanner in= new Scanner(System.in);
        int customerID = in.nextInt();
        while(customerID > 0)
        {
        int Reminder = customerID % 10;
        int sum = sum+ Reminder;
        customerID = customerID / 10;
        }
        if(sum%5||sum%8)
        {
        System.out.println("Lucky Customer");
        }else
        {
        System.out.println("Unlucky Customer");
        }
        if(sum <0)
        {
        System.out.println("Invalid Input");
        }
        }
        }

Body:
Please correct your code to remove some compilation errors...

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner in= new Scanner(System.in);
        int customerID = in.nextInt();
        int sum = 0;
        while(customerID > 0) {
            int Reminder = customerID % 10;
            sum = sum + Reminder;
            customerID = customerID / 10;
        }
        if(sum % 5 == 0 || sum % 8 == 0) {
            System.out.println("Lucky Customer");
        } else {
            System.out.println("Unlucky Customer");
        }
        if(sum <0) {
            System.out.println("Invalid Input");
        }
    }
}


问:
MessageBox.Show issue
I have a lot of code like this and it usually works

```<code>private void button_Click(object sender, EventArgs e)
{
    try
    {
        DialogResult result;
        result = MessageBox.Show( "Questa operazione potrebbe richiedere alcuni minuti,\r\nsei sicuro di voler continuare?", "Attenzione", MessageBoxButtons.YesNo, MessageBoxIcon.Warning );
        if ( result == System.Windows.Forms.DialogResult.Yes )
        {
            DoSomething();
        }
        else
        {
            DoSomethingElse();
        }
    }
    Catch (Exception ex)
    {
        LogExceptio(ex);
    }
}
</code>```

but for some reason on a specific Windows Form the MessageBox is not showing.
If I press Enter it proceed like I have made a click on YES;
If I press the ALT key the MessageBox magically appear on the screen.

Any idea?
What can I do to solve this issue?

答:
Because Of using some Threads in your application MessageBox May appear on background.
 So, You have to Pass MessageBox also in lambda expression Thread Like Below mentioned

```<code>new Thread(() =>
 {
    MessageBox.Show("Your Text");
 }).Start();
</code>```

Hope It Will Help You...

Title: MessageBox.Show issue

Body:
I have a lot of code like this and it usually works

private void button_Click(object sender, EventArgs e)
{
    try
    {
        DialogResult result;
        result = MessageBox.Show( "Questa operazione potrebbe richiedere alcuni minuti,\r\nsei sicuro di voler continuare?", "Attenzione", MessageBoxButtons.YesNo, MessageBoxIcon.Warning );
        if ( result == System.Windows.Forms.DialogResult.Yes )
        {
            DoSomething();
        }
        else
        {
            DoSomethingElse();
        }
    }
    Catch (Exception ex)
    {
        LogExceptio(ex);
    }
}

but for some reason on a specific Windows Form the MessageBox is not showing.
If I press Enter it proceed like I have made a click on YES;
If I press the ALT key the MessageBox magically appear on the screen.

Any idea?
What can I do to solve this issue?

Body:
Because Of using some Threads in your application MessageBox May appear on background.
 So, You have to Pass MessageBox also in lambda expression Thread Like Below mentioned

new Thread(() =>
 {
    MessageBox.Show("Your Text");
 }).Start();

Hope It Will Help You...


问:
WPF TreeviewItem Width
i am trying to prevent my treeviewitems from overflowing the window size when
the content is too long.I have tried various approaches (Binding ActualWidth of parent, HorizontalContentAlign, Wrapping into other containers,...) but without success.

I want to achieve 2 things:

All TreeviewItems must fill the remaining space (Stretch)

I do not want a horizontal scrollbar, instead i want the text within the
textbox overflowing.

That's my code so far.

Any ideas??

KR Manu

```<code> <TreeView x:Name="tv">
        <TreeView.Resources>
            <Style TargetType="{x:Type TreeViewItem}">
                <Setter Property="KeyboardNavigation.TabNavigation" Value="Continue"/>
                <Setter Property="IsTabStop" Value="True"/>
                <Setter Property="Focusable" Value="False" />
                <Setter Property="IsExpanded" Value="True" />
                <Setter Property="Background" Value="Transparent"/>
                <Setter Property="HorizontalAlignment" Value="Stretch"/>
                <Setter Property="HorizontalContentAlignment" Value="Stretch" />
                <Setter Property="Padding" Value="1,0,0,1"/>
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type TreeViewItem}">
                            <Grid>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition MinWidth="19" Width="Auto"/>
                                    <ColumnDefinition Width="*"/>
                                </Grid.ColumnDefinitions>
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="Auto"/>
                                    <RowDefinition/>
                                </Grid.RowDefinitions>

                                <!-- Connecting Lines -->
                                <Rectangle x:Name="HorLn" Margin="9,1,0,0" Height="1" Stroke="Red" SnapsToDevicePixels="True"/>
                                <Rectangle x:Name="VerLn" Width="1" Stroke="Red" Margin="0,0,1,0" Grid.RowSpan="2" SnapsToDevicePixels="true"/>
                                <ToggleButton Margin="-1,0,0,0" x:Name="Expander" Visibility="Hidden"  IsChecked="{Binding IsExpanded, RelativeSource={RelativeSource TemplatedParent}}" ClickMode="Press"/>
                                <Border x:Name="Bd" Grid.Column="1" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="True">
                                    <ContentPresenter Grid.Column="1" x:Name="PART_Header" ContentSource="Header" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" MinWidth="20"/>
                                </Border>
                                <ItemsPresenter x:Name="ItemsHost" Grid.Row="1" Grid.Column="1"/>
                            </Grid>
                            <ControlTemplate.Triggers>
                                <Trigger Property="IsExpanded" Value="false">
                                    <Setter TargetName="ItemsHost" Property="Visibility" Value="Collapsed"/>
                                </Trigger>
                                <Trigger Property="HasItems" Value="false">
                                    <Setter TargetName="Expander" Property="Visibility" Value="Hidden"/>
                                </Trigger>
                                <MultiTrigger>
                                    <MultiTrigger.Conditions>
                                        <Condition Property="HasHeader" Value="false"/>
                                        <Condition Property="Width" Value="Auto"/>
                                    </MultiTrigger.Conditions>
                                    <Setter TargetName="PART_Header" Property="MinWidth" Value="75"/>
                                </MultiTrigger>
                                <MultiTrigger>
                                    <MultiTrigger.Conditions>
                                        <Condition Property="HasHeader" Value="false"/>
                                        <Condition Property="Height" Value="Auto"/>
                                    </MultiTrigger.Conditions>
                                    <Setter TargetName="PART_Header" Property="MinHeight" Value="19"/>
                                </MultiTrigger>
                                <Trigger Property="IsSelected" Value="true">
                                    <Setter TargetName="Bd" Property="Background" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
                                    <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"/>
                                </Trigger>
                                <MultiTrigger>
                                    <MultiTrigger.Conditions>
                                        <Condition Property="IsSelected" Value="true"/>
                                        <Condition Property="IsSelectionActive" Value="false"/>
                                    </MultiTrigger.Conditions>
                                    <Setter TargetName="Bd" Property="Background" Value="Transparent"/>
                                    <Setter Property="Foreground" Value="White"/>
                                </MultiTrigger>
                                <Trigger Property="IsEnabled" Value="false">
                                    <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
                                </Trigger>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </TreeView.Resources>
        <TreeView.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <TextBox Text="{Binding Mode=OneWay}" />
                </Grid>
            </DataTemplate>
        </TreeView.ItemTemplate>
    </TreeView>
</code>```

答:
Unfortionatly Birke's answer does not solve the problem.
I have modified my TreeviewItem Template like this:

```<code>  <TreeView.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Border BorderThickness="1" BorderBrush="Red">
                        <TextBlock TextTrimming="CharacterEllipsis" Text="{Binding Mode=OneWay}" />
                    </Border>
                </Grid>
            </DataTemplate>
        </TreeView.ItemTemplate>
</code>```

The Item is still overflowing the window width.

Title: WPF TreeviewItem Width

Body:
i am trying to prevent my treeviewitems from overflowing the window size when
the content is too long.I have tried various approaches (Binding ActualWidth of parent, HorizontalContentAlign, Wrapping into other containers,...) but without success.

I want to achieve 2 things:

All TreeviewItems must fill the remaining space (Stretch)

I do not want a horizontal scrollbar, instead i want the text within the
textbox overflowing.

That's my code so far.

Any ideas??

KR Manu

 <TreeView x:Name="tv">
        <TreeView.Resources>

        </TreeView.Resources>
        <TreeView.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <TextBox Text="{Binding Mode=OneWay}" />
                </Grid>
            </DataTemplate>
        </TreeView.ItemTemplate>
    </TreeView>

Body:
Unfortionatly Birke's answer does not solve the problem.
I have modified my TreeviewItem Template like this:

  <TreeView.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Border BorderThickness="1" BorderBrush="Red">
                        <TextBlock TextTrimming="CharacterEllipsis" Text="{Binding Mode=OneWay}" />
                    </Border>
                </Grid>
            </DataTemplate>
        </TreeView.ItemTemplate>

The Item is still overflowing the window width.


问:
Specific Angular 2/4 & Meteor quickstart/tutorial?
I've been all over the Meteor and Angular-Meteor websites (and Angular-Meteor github) looking for a pure Angular 2/4 guide to using Meteor (all I can seem to find is an Ionic one).  Kind of confused as to how to use the CLI's together.  Does anyone have a tutorial or know the steps to setting this up without Ionic?  Or should I just be trying to follow the Ionic tutorial but using Angular CLI instead?</p>

答:
For anyone who is interested.

I spent most the day trying to use https://github.com/Urigo/angular-meteor with my app (used the quickstart), copied most of my apps src into the clients/imports directory and tried to keep the same app structure as the one on github, with a bit of messing around was able to get the angular bit working however if you are planning on using @angular/material, especially with a custom theme then you're in for a world of hurt (quite a few issues and comments re importing scss mixins from node_modules on the meteor github, meteors build system doesn't seem to like it).

To make it all work properly, follow the steps in The process I've done to recreate this section at https://github.com/Urigo/angular-meteor/examples/angularcli-meteor

If you already have an angular 4 app partially built then start in your apps root directory at step 3 (ng eject).

Instructions are fairly straight forward. Any steps where there isn't code examples (Now we need to create api/tsconfig.json) copy the file in question from the repo.

Hope that saves some others a heap of time.


问:
Minimum Xcode/swift version for App Store submission
From time to time Apple levels up the minimum Xcode/Swift versions needed for app store submission, this needs to be tracked down somewhere to be updated whenever apple raises the minimum versions,

According to Apple:

If your app is written in Swift, you can continue to submit apps in Swift 3.2 to the App Store

Does it mean that current minimum swift version is 3.2 ?

I really need to know in a clear way What is the current minimum versions of swift/Xcode for App store submission.

And what if a Pod used by my app has a lower swift version ?

答:
Minimum swift version is swift 3.2 on 15-11-2017.

About your pods that didn't support swift 4, you can make of the following choices:

Check if the pod library that it supports swift 3.2 then you shout change your pod settings from swift 4 to swift 3.2

Contact the pod owner to support at least 3.2, May be he had another branch that support swift 3.2.

Or you can create fork from the pod then update its code to swift 3.2


问:
how to convert date 2017-sep-12 To 2017-09-12 in HIVE
I am facing one issue in converting the date in hive. I need to convert 2017-sep-12 To 2017-09-12 . How can i achieve this in HIVE </p>

答:
Use unix_timestamp(string date, string pattern) to convert given date format to seconds passed from 1970-01-01. Then use from_unixtime() to convert to given format:

```<code>hive> select from_unixtime(unix_timestamp('2017-sep-12' ,'yyyy-MMM-dd'), 'dd-MM-yyyy');
OK
12-09-2017
</code>```

Body:
Use unix_timestamp(string date, string pattern) to convert given date format to seconds passed from 1970-01-01. Then use from_unixtime() to convert to given format:

hive> select from_unixtime(unix_timestamp('2017-sep-12' ,'yyyy-MMM-dd'), 'dd-MM-yyyy');
OK
12-09-2017


问:
Centos 7 ssh login failed using LDAP and sssd
I've setup an LDAP server running on Centos 7.  id, getent passwd, on users works.  But 'ssh' failed.  From /var/log/secure, it seems like authentication succeeded, but pam doesn't like something else.  I'm not sure how to narrow down where the problem is.

/var/log/secure:

```<code>May 11 16:33:40 localhost sshd[45055]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=ldapserver.abc.com  user=user1
May 11 16:33:40 localhost sshd[45055]: pam_sss(sshd:auth): authentication success; logname= uid=0 euid=0 tty=ssh ruser= rhost=ldapserver.abc.com user=user1
May 11 16:33:40 localhost sshd[45055]: pam_sss(sshd:account): Access denied for user user1: 6 (Permission denied)
May 11 16:33:40 localhost sshd[45055]: Failed password for user1 from ldapserver.abc.com port 55185 ssh2
May 11 16:33:40 localhost sshd[45055]: fatal: Access denied for user user1 by PAM account configuration [preauth]
</code>```

/etc/sssd/sssd.conf:

```<code>[sssd]
services = nss, pam, autofs, ssh
config_file_version = 2
domains = default

[nss]
homedir_substring = /home
filter_users = root,ldap,named,avahi,haldaemon,dbus,radiusd,newsnsdc,nscd

[domain/default]
enumerate = False
ldap_tls_reqcert = never
autofs_provider = ldap
cache_credentials = True
krb5_realm = #
ldap_search_base = dc=abc,dc=com
id_provider = ldap
auth_provider = ldap
chpass_provider = ldap
access_provider = ldap
ldap_tls_cacert = /etc/openldap/certs/cacert.pem
ldap_uri = ldaps://ldapserver.abc.com:636
ldap_id_use_start_tls = False
ldap_default_bind_dn = uid=nssproxy,ou=users,dc=abc,dc=com
ldap_chpass_uri = ldaps://ldapserver.abc.com:636

ldap_default_authtok_type = password
ldap_default_authtok = 12345
debug_level = 4

[pam]
debug_level = 4

[sudo]

[autofs]

[ssh]
debug_level = 9

[pac]

[ifp]
</code>```

/etc/pam.d/password-auth-ac:

```<code>#%PAM-1.0
# This file is auto-generated.
# User changes will be destroyed the next time authconfig is run.
auth        required      pam_env.so
auth        sufficient    pam_unix.so nullok try_first_pass
auth        requisite     pam_succeed_if.so uid >= 1000 quiet_success
auth        sufficient    pam_sss.so use_first_pass
auth        required      pam_deny.so

account     required      pam_unix.so
account     sufficient    pam_localuser.so
account     sufficient    pam_succeed_if.so uid < 1000 quiet
account     [default=bad success=ok user_unknown=ignore] pam_sss.so
account     required      pam_permit.so

password    requisite     pam_pwquality.so try_first_pass local_users_only retry=3 authtok_type=
password    sufficient    pam_unix.so sha512 shadow nullok try_first_pass use_authtok
password    sufficient    pam_sss.so use_authtok
password    required      pam_deny.so

session     optional      pam_keyinit.so revoke
session     required      pam_limits.so
-session     optional      pam_systemd.so
session     [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid
session     required      pam_unix.so
session     optional      pam_sss.so
</code>```

/etc/pam.d/system-auth-ac:

```<code>#%PAM-1.0
# This file is auto-generated.
# User changes will be destroyed the next time authconfig is run.
auth        required      pam_env.so
auth        sufficient    pam_fprintd.so
auth        sufficient    pam_unix.so nullok try_first_pass
auth        requisite     pam_succeed_if.so uid >= 1000 quiet_success
auth        sufficient    pam_sss.so use_first_pass
auth        required      pam_deny.so

account     required      pam_unix.so
account     sufficient    pam_localuser.so
account     sufficient    pam_succeed_if.so uid < 1000 quiet
account     [default=bad success=ok user_unknown=ignore] pam_sss.so
account     required      pam_permit.so

password    requisite     pam_pwquality.so try_first_pass local_users_only retry=3 authtok_type=
password    sufficient    pam_unix.so sha512 shadow nullok try_first_pass use_authtok
password    sufficient    pam_sss.so use_authtok
password    required      pam_deny.so

session     optional      pam_keyinit.so revoke
session     required      pam_limits.so
-session     optional      pam_systemd.so
session     [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid
session     required      pam_unix.so
session     optional      pam_sss.so
</code>```

/etc/nsswitch.conf:

```<code>passwd:     files sss
shadow:     files sss
group:      files sss
#initgroups: files

#hosts:     db files nisplus nis dns
hosts:      files dns

bootparams: nisplus [NOTFOUND=return] files

ethers:     files
netmasks:   files
networks:   files
protocols:  files
rpc:        files
services:   files sss

netgroup:   files sss

publickey:  nisplus

automount:  files sss
aliases:    files nisplus
</code>```

答:
sssd does not support authentication over an unencrypted channel

This line from man page should be posted as answer specifically.

Body:
I've setup an LDAP server running on Centos 7.  id, getent passwd, on users works.  But 'ssh' failed.  From /var/log/secure, it seems like authentication succeeded, but pam doesn't like something else.  I'm not sure how to narrow down where the problem is.

/var/log/secure:

May 11 16:33:40 localhost sshd[45055]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=ldapserver.abc.com  user=user1
May 11 16:33:40 localhost sshd[45055]: pam_sss(sshd:auth): authentication success; logname= uid=0 euid=0 tty=ssh ruser= rhost=ldapserver.abc.com user=user1
May 11 16:33:40 localhost sshd[45055]: pam_sss(sshd:account): Access denied for user user1: 6 (Permission denied)
May 11 16:33:40 localhost sshd[45055]: Failed password for user1 from ldapserver.abc.com port 55185 ssh2
May 11 16:33:40 localhost sshd[45055]: fatal: Access denied for user user1 by PAM account configuration [preauth]

/etc/sssd/sssd.conf:

[sssd]
services = nss, pam, autofs, ssh
config_file_version = 2
domains = default

[nss]
homedir_substring = /home
filter_users = root,ldap,named,avahi,haldaemon,dbus,radiusd,newsnsdc,nscd

[domain/default]
enumerate = False
ldap_tls_reqcert = never
autofs_provider = ldap
cache_credentials = True
krb5_realm = #
ldap_search_base = dc=abc,dc=com
id_provider = ldap
auth_provider = ldap
chpass_provider = ldap
access_provider = ldap
ldap_tls_cacert = /etc/openldap/certs/cacert.pem
ldap_uri = ldaps://ldapserver.abc.com:636
ldap_id_use_start_tls = False
ldap_default_bind_dn = uid=nssproxy,ou=users,dc=abc,dc=com
ldap_chpass_uri = ldaps://ldapserver.abc.com:636

ldap_default_authtok_type = password
ldap_default_authtok = 12345
debug_level = 4

[pam]
debug_level = 4

[sudo]

[autofs]

[ssh]
debug_level = 9

[pac]

[ifp]

/etc/pam.d/password-auth-ac:

#%PAM-1.0
# This file is auto-generated.
# User changes will be destroyed the next time authconfig is run.
auth        required      pam_env.so
auth        sufficient    pam_unix.so nullok try_first_pass
auth        requisite     pam_succeed_if.so uid >= 1000 quiet_success
auth        sufficient    pam_sss.so use_first_pass
auth        required      pam_deny.so

account     required      pam_unix.so
account     sufficient    pam_localuser.so
account     sufficient    pam_succeed_if.so uid < 1000 quiet
account     [default=bad success=ok user_unknown=ignore] pam_sss.so
account     required      pam_permit.so

password    requisite     pam_pwquality.so try_first_pass local_users_only retry=3 authtok_type=
password    sufficient    pam_unix.so sha512 shadow nullok try_first_pass use_authtok
password    sufficient    pam_sss.so use_authtok
password    required      pam_deny.so

session     optional      pam_keyinit.so revoke
session     required      pam_limits.so
-session     optional      pam_systemd.so
session     [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid
session     required      pam_unix.so
session     optional      pam_sss.so

/etc/pam.d/system-auth-ac:

#%PAM-1.0
# This file is auto-generated.
# User changes will be destroyed the next time authconfig is run.
auth        required      pam_env.so
auth        sufficient    pam_fprintd.so
auth        sufficient    pam_unix.so nullok try_first_pass
auth        requisite     pam_succeed_if.so uid >= 1000 quiet_success
auth        sufficient    pam_sss.so use_first_pass
auth        required      pam_deny.so

account     required      pam_unix.so
account     sufficient    pam_localuser.so
account     sufficient    pam_succeed_if.so uid < 1000 quiet
account     [default=bad success=ok user_unknown=ignore] pam_sss.so
account     required      pam_permit.so

password    requisite     pam_pwquality.so try_first_pass local_users_only retry=3 authtok_type=
password    sufficient    pam_unix.so sha512 shadow nullok try_first_pass use_authtok
password    sufficient    pam_sss.so use_authtok
password    required      pam_deny.so

session     optional      pam_keyinit.so revoke
session     required      pam_limits.so
-session     optional      pam_systemd.so
session     [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid
session     required      pam_unix.so
session     optional      pam_sss.so

/etc/nsswitch.conf:

passwd:     files sss
shadow:     files sss
group:      files sss
#initgroups: files

#hosts:     db files nisplus nis dns
hosts:      files dns

bootparams: nisplus [NOTFOUND=return] files

ethers:     files
netmasks:   files
networks:   files
protocols:  files
rpc:        files
services:   files sss

netgroup:   files sss

publickey:  nisplus

automount:  files sss
aliases:    files nisplus


问:
Any sublime plugin to make angular view template smarter
Working in sublime on angular(2/4) is great until I am in the view template file. The interpolation cannot provide auto-completion for class properties backing the view, which I have seen it working by using VS Code.

Is there any plugin to make this work in sublime 3?

答:
The VS Code extension that enables smart templates for Angular is Angular Language Service.

A google search for 'angular language service sublime' brought up this blog. It has a section for adding the plugin to Sublime as well.


问:
Jquery Live Validation
After having a search around I could not find exactly what I want, I am looking to validate a form client side using the Jquery library and some form of validation plugin.  I was hoping that some one could advise me on whether there are any validation plugins out there that do not use generic error messages, as my form is laid out with no room for these errors, and I also I want the validator to to for correct content as well.

Basically I want to be able to check the field on each key press and blur and if the fields validates for it to gain a green border, and if it does not validate for it to gain a red border, any one know of a plugin that can do this?

Thanks

sico87

答:
I use this Form Validation plugin: http://docs.jquery.com/Plugins/Validation. While I'm not sure about the "live" validation, you could hide the "generic" errors using CSS:

```<code>label.error{ display: none; }
</code>```

I know the plugin supports AJAX, so perhaps could be extended to do the live validation you want?

Title: Jquery Live Validation

Body:
I use this Form Validation plugin: http://docs.jquery.com/Plugins/Validation. While I'm not sure about the "live" validation, you could hide the "generic" errors using CSS:

label.error{ display: none; }

I know the plugin supports AJAX, so perhaps could be extended to do the live validation you want?

OwnerDisplayName: Chris


问:
How to generate hash(SHA1) using beanshell in JMeter?
How do I want to generate a hash using beanshell(SHA1) in JMeter to sign up to a application?

I'm not able to get a substantial answer yet from net

答:
There's a new JMeter function __digest, currently in nightly builds which can be used to encode strings

In your case to save in sha1Value variable the result of myVar variable use the following:

```<code>${__digest(SHA-1,${myVar},,,sha1Value)}
</code>```

4th parameter is uppercase, so you can send true to automatically uppercase it.

Body:
There's a new JMeter function __digest, currently in nightly builds which can be used to encode strings

In your case to save in sha1Value variable the result of myVar variable use the following:

${__digest(SHA-1,${myVar},,,sha1Value)}

4th parameter is uppercase, so you can send true to automatically uppercase it.


问:
When I click a button it should display the html page in angularjs(single page application)
I am going to design a website That should display the content of html  when I click a button.

HTML

```<code> <a ui-sref="about">about</a>
    <a href="" ng-click="home()" >home</a><div ng-include="templateURL"></div>
    <ui-view></ui-view>
</code>```

JS:

```<code> app.controller("home", hom); function hom($scope) {
  $scope.home = function(){
   $scope.templateURL = 'templates/hello.html';  }}
</code>```

答:
Answer to your problem is ngRoute / ui-route.
You can one of the above-mentioned solutions.

check demo here:
https://www.w3schools.com/angular/angular_routing.asp

Body:
I am going to design a website That should display the content of html  when I click a button.

HTML

 about
    home

    <ui-view></ui-view>

JS:

 app.controller("home", hom); function hom($scope) {
  $scope.home = function(){
   $scope.templateURL = 'templates/hello.html';  }}


问:
Indesign SDK - Model and UI Plugin
How to use a model plugin in UI plugin of Indesign SDK. And how to separate the model and UI plugin?

答:
You can find the InDesign plug-in programming guide by simple google search. There are PDF versions available. The one to explain this specific doubt is available here.
Chapter 5 has a detailed discussion on model and ui plug-ins and model and UI separation.</p>

Title: Indesign SDK - Model and UI Plugin


问:
Azure IoT Hub - How to use Table Storage in IoT Hub?
First of all, sorry for my english skill.

I'm a high school student from South Korea who's doing project with Azure IoT Hub.

I am working on a project where a raspberry pi device is sending values to an Azure IoT Hub. I would like to save this data in Azure Table Storage as this data will be used by some other services (Azure WebApp for example).

So I tried to save raspberry pi values in Azure Table Storage.
But when I add endpoints of IoT Hub, I just can use only blob storage container

of course i still don't understand about iot hub
please don't look so bad.

In a nutshell

I want to send raspberry pi values to Azure Table Storage and not Blob Storage however only option available to me is Blob Storage when I am setting endpoints for Azure IoT Hub.

How to send values to Table Storage via Azure IoT Hub.

by any chance, my logic for Azure is completely wrong?

答:
Simple way how to store D2C messages in the Azure Store Table is using an Azure EventHubTrigger Function.

More details about the function and its integration with Azure IoT Hub can be found here.


问:
Difference between x.toString() and x+""
Back in college one of my profs. taught us to just do x + "" as a quick conversion from basic types to strings.

I don't remember which class it was in I had him for some Java and C++ courses(I haven't used either for some time now), but I use it in C#/.Net now which is what I'm primarily developing in lately.

Is there an advantage to using .toString() over +"" for basic types such at int, decimal, float...?
What cases would .toString() be better?

Note:I was shown .toString() as well, that prof just recommended +"" because it was shorter and I have just done that since then without questioning it.

答: Because strings are immutable, x+"" invokes two functions: x.toString() and StringBuffer.append() (in Java, at least). I imagine most good JITs would simply turn that into a single function call, x.toString(), but I couldn't be sure without actually testing.


问:
how to call actionmailer in rails admin controller?
I want to send a email to user after create something via rails admin.

I know I can call it in model callback but it's not considered as a good pratices

the best way is to put the actionmailer action after model save in the controller but I don't know how to do it in rails_admin controller

```<code>class UsersController < ApplicationController
  # POST /users
  # POST /users.json
  def create
    @user = User.new(params[:user])

    respond_to do |format|
      if @user.save
        # Tell the UserMailer to send a welcome email after save
        UserMailer.welcome_email(@user).deliver_later

        format.html { redirect_to(@user, notice: 'User was successfully created.') }
        format.json { render json: @user, status: :created, location: @user }
      else
        format.html { render action: 'new' }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end
end
</code>```

答:
Have you tried to include your Mailer in admin_controller?

```<code>include UserMailer
</code>```

Then in your create action UserMailer.some_mailer_action.deliver_now

Body:
I want to send a email to user after create something via rails admin.

I know I can call it in model callback but it's not considered as a good pratices

the best way is to put the actionmailer action after model save in the controller but I don't know how to do it in rails_admin controller

class UsersController < ApplicationController
  # POST /users
  # POST /users.json
  def create
    @user = User.new(params[:user])

    respond_to do |format|
      if @user.save
        # Tell the UserMailer to send a welcome email after save
        UserMailer.welcome_email(@user).deliver_later

        format.html { redirect_to(@user, notice: 'User was successfully created.') }
        format.json { render json: @user, status: :created, location: @user }
      else
        format.html { render action: 'new' }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end
end

Body:
Have you tried to include your Mailer in admin_controller?

include UserMailer

Then in your create action UserMailer.some_mailer_action.deliver_now


问:
Cartesian product on multiple pandas DataFrames at once
I want to do in pandas an equivalent operation to MYSQL cartesian products.

For example table a and b have the same column name "Price", I want to change the name as "a.Price" and "b,Price" and prevent those two "Price" attributes from merging into one column.

However, pandas merge can only merge two DataFrames on their shared columns:

```<code>dfa = pd.DataFrame({'price': [30,40],
                   'discount': ['0.1', '0.2']})

dfb = pd.DataFrame({'price': [100,120],
                   'title': ['abc', 'xyz']})

df_result = pd.merge(dfa,dfb,how="outer")

  discount  price title
0      0.1     30   NaN
1      0.2     40   NaN
2      NaN    100   abc
3      NaN    120   xyz
</code>```

The result would be like this, but I want to rename these two "Price" attributes and separate them into two columns. I saw other answers recommending to add the same keys to each DataFrame manually, but I want to know how to solve this problem when I have several large DataFrames (more than 2).

答:
I'm not quite sure why you might want to do this, but you could add a prefix to every column:

```<code>In [11]: dfa.add_prefix("a_")
Out[11]:
  a_discount  a_price
0        0.1       30
1        0.2       40
</code>```

I would use concat rather than merge:

```<code>In [12]: pd.concat([dfa.add_prefix("a_"), dfb.add_prefix("b_")])
Out[12]:
  a_discount  a_price  b_price b_title
0        0.1     30.0      NaN     NaN
1        0.2     40.0      NaN     NaN
0        NaN      NaN    100.0     abc
1        NaN      NaN    120.0     xyz
</code>```

to do more than two, pass more into the list:

```<code>pd.concat([dfa.add_prefix("a_"), dfb.add_prefix("b_"), dfc.add_prefix("c_")])
</code>```

Body:
I want to do in pandas an equivalent operation to MYSQL cartesian products.

For example table a and b have the same column name "Price", I want to change the name as "a.Price" and "b,Price" and prevent those two "Price" attributes from merging into one column.

However, pandas merge can only merge two DataFrames on their shared columns:

dfa = pd.DataFrame({'price': [30,40],
                   'discount': ['0.1', '0.2']})

dfb = pd.DataFrame({'price': [100,120],
                   'title': ['abc', 'xyz']})

df_result = pd.merge(dfa,dfb,how="outer")

  discount  price title
0      0.1     30   NaN
1      0.2     40   NaN
2      NaN    100   abc
3      NaN    120   xyz

The result would be like this, but I want to rename these two "Price" attributes and separate them into two columns. I saw other answers recommending to add the same keys to each DataFrame manually, but I want to know how to solve this problem when I have several large DataFrames (more than 2).

Body:
I'm not quite sure why you might want to do this, but you could add a prefix to every column:

In [11]: dfa.add_prefix("a_")
Out[11]:
  a_discount  a_price
0        0.1       30
1        0.2       40

I would use concat rather than merge:

In [12]: pd.concat([dfa.add_prefix("a_"), dfb.add_prefix("b_")])
Out[12]:
  a_discount  a_price  b_price b_title
0        0.1     30.0      NaN     NaN
1        0.2     40.0      NaN     NaN
0        NaN      NaN    100.0     abc
1        NaN      NaN    120.0     xyz

to do more than two, pass more into the list:

pd.concat([dfa.add_prefix("a_"), dfb.add_prefix("b_"), dfc.add_prefix("c_")])


问:
Python Scikit Learn, LinearRegression, Dummy Variable lead to different in shape
I've worked around with Scikit Learn Library for Machine Learning purpose.
I got some problem related to Dummy variable while using Regression. I have 2 set of sample for Training set and Test set. Actually, program uses Training set to create "Prediction Model", then "Testing" to check the score. While running the program, If the shape is equal, it's fine. But dummy variable, will make change to the shape and lead to different in
shape.

Example

Training set: 130 Rows * 3 Column

Training set: 60 Rows * 3 Column

After making 1 and 2 column to be dummy, now shape is changing

Training set: 130 Rows * 15 Column

Training set: 60 Rows * 12 Column

Any solution to solve this problem?
If it's possible or not, to success in progress even data shape is different

Sample Program: https://www.dropbox.com/s/tcc1ianmljf5i8c/Dummy_Error.py?dl=0

答:
If I understand your code correctly, you are using pd.get_dummies to create the dummy variables and are passing your entire data frame to the function.

In this case, pandas will create a dummy variable for every value in every category it finds. In this case, it looks like more category values exist in training than in test. This is why you end up with more columns in training than in test.

A better approach is to combine everything in one dataframe, create categorical variables in the combined data set and then split your data into train and test.