问:
Cannot connect to the Docker daemon (port 2375)
I have installed Docker on Ubuntu 16.04 server, using the manual on this page: https://docs.docker.com/cs-engine/1.13/, so, using these steps:

```<code>curl -fsSL 'https://sks-keyservers.net/pks/lookup?op=get&search=0xee6d536cf7dc86e2d7d56f59a178ac6c6238f52e' | sudo apt-key add -
sudo add-apt-repository    "deb https://packages.docker.com/1.13/apt/repo/ \
ubuntu-$(lsb_release -cs) \
main"

sudo apt-get update
sudo apt-get -y install docker-engine
</code>```

I have installed it on two servers and I need them to see each other, I needed to let Docker daemon listen on port 2375 (probably doesn't matter, but using this manual: https://github.com/yeasy/cello/blob/master/docs/deployment.md)

So I created the conf file:

```<code>sudo mkdir -p /etc/systemd/system/docker.service.d
sudo vim /etc/systemd/system/docker.service.d/override.conf
</code>```

Added this to the override.conf:

```<code>[Service]
DOCKER_OPTS="$DOCKER_OPTS -H tcp://0.0.0.0:2375 -H unix:///var/run/docker.sock --api-cors-header='*' --default-ulimit=nofile=8192:16384 --default-ulimit=nproc=8192:16384"
EnvironmentFile=-/etc/default/docker
ExecStart=
ExecStart=/usr/bin/dockerd -H fd:// $DOCKER_OPTS
</code>```

Then:

```<code>$ sudo systemctl daemon-reload
$ sudo systemctl restart docker.service
</code>```

Tested the connection between servers like this:

```<code>$ docker -H 10.101.35.61:2375 version
</code>```

The response:

```<code>Client:
 Version:      1.13.1-cs4
 API version:  1.27
 Go version:   go1.7.5
 Git commit:   e46aec0
 Built:        Mon May 22 18:46:40 2017
 OS/Arch:      linux/amd64
Cannot connect to the Docker daemon at tcp://10.101.35.61:2375. Is the docker daemon running?
</code>```

Tried restarting the server, same problem. Tried to run with sudo. Tried adding the user to group docker:

```<code>sudo usermod -aG docker $USER
</code>```

Didn't help. I have disabled firewall on both servers. When I check the ports open on the server with sudo lsof -i, I can't see anything listening to port 2375 - I am guessing Docker should be listening to it?

答:
Try the config file in this location, create it if it does not exist:

```<code>/etc/docker/daemon.json
</code>```

Put this and restart the docker service:

```<code>{"hosts": ["tcp://0.0.0.0:2375", "unix:///var/run/docker.sock"]}
</code>```

You can add more configs, documented here.

Body:
I have installed Docker on Ubuntu 16.04 server, using the manual on this page: https://docs.docker.com/cs-engine/1.13/, so, using these steps:

curl -fsSL 'https://sks-keyservers.net/pks/lookup?op=get&search=0xee6d536cf7dc86e2d7d56f59a178ac6c6238f52e' | sudo apt-key add -
sudo add-apt-repository    "deb https://packages.docker.com/1.13/apt/repo/ \
ubuntu-$(lsb_release -cs) \
main"

sudo apt-get update
sudo apt-get -y install docker-engine

I have installed it on two servers and I need them to see each other, I needed to let Docker daemon listen on port 2375 (probably doesn't matter, but using this manual: https://github.com/yeasy/cello/blob/master/docs/deployment.md)

So I created the conf file:

sudo mkdir -p /etc/systemd/system/docker.service.d
sudo vim /etc/systemd/system/docker.service.d/override.conf

Added this to the override.conf:

[Service]
DOCKER_OPTS="$DOCKER_OPTS -H tcp://0.0.0.0:2375 -H unix:///var/run/docker.sock --api-cors-header='*' --default-ulimit=nofile=8192:16384 --default-ulimit=nproc=8192:16384"
EnvironmentFile=-/etc/default/docker
ExecStart=
ExecStart=/usr/bin/dockerd -H fd:// $DOCKER_OPTS

Then:

$ sudo systemctl daemon-reload
$ sudo systemctl restart docker.service

Tested the connection between servers like this:

$ docker -H 10.101.35.61:2375 version

The response:

Client:
 Version:      1.13.1-cs4
 API version:  1.27
 Go version:   go1.7.5
 Git commit:   e46aec0
 Built:        Mon May 22 18:46:40 2017
 OS/Arch:      linux/amd64
Cannot connect to the Docker daemon at tcp://10.101.35.61:2375. Is the docker daemon running?

Tried restarting the server, same problem. Tried to run with sudo. Tried adding the user to group docker:

sudo usermod -aG docker $USER

Didn't help. I have disabled firewall on both servers. When I check the ports open on the server with sudo lsof -i, I can't see anything listening to port 2375 - I am guessing Docker should be listening to it?

Body:
Try the config file in this location, create it if it does not exist:

/etc/docker/daemon.json

Put this and restart the docker service:

{"hosts": ["tcp://0.0.0.0:2375", "unix:///var/run/docker.sock"]}

You can add more configs, documented here.


来源: stackexchange

问:
Background: transparent does not work
I try to use background-color transparent for my task (can see in image) , but its not useful . Background-transparent do nothing , its show li's background-color .

I try many ways but its not working . What can i do ?

Thanks in advance .

HTML:

```<code><div>
   <ul>
      <li>...</li>
      <li>...</li>
      <li>...</li>
      <li>...</li>
      <li>...</li>
   </ul>

   <span class="left-arrow-winners"></span>
   <span class="right-arrow-winners" ></span>
<div>
</code>```

CSS:

```<code>li {
    display: inline-block;
    box-sizing: border-box;
    margin: 0 12px;
    padding: 4px 12px;
    background-color: rgba(230, 229, 220, 0.75);
    transition: all 250ms;
    border-radius: 4px;
}

.left-arrow-winners ,
.right-arrow-winners {
    cursor: pointer;
    font: 18px/32px icomoon;
    position: absolute;
    top: 4px;
}

.left-arrow-winners {
    left: 0
}

.right-arrow-winners {
    right: 0
}

.left-arrow-winners:before {
    content: "\e92a";
}

.right-arrow-winners:before {
    content: "\e92b";
}
</code>```

答:
This can be your best friend: http://www.colorzilla.com/gradient-editor/

Is this what you were looking for?

White - fade to transparent background?

li {
    display: inline-block;
    box-sizing: border-box;
    margin: 0 12px;
    padding: 4px 12px;
    background-color: rgba(230, 229, 220, 0.75);
    transition: all 250ms;
    border-radius: 4px;
}
li{
/* Permalink - use to edit and share this gradient: http://colorzilla.com/gradient-editor/#ffffff+51,7db9e8+100&0.9+51,0.01+100 */
background: -moz-linear-gradient(left, rgba(255,255,255,0.9) 51%, rgba(125,185,232,0.01) 100%);
/* FF3.6-15 */
background: -webkit-linear-gradient(left, rgba(255,255,255,0.9) 51%,rgba(125,185,232,0.01) 100%);
/* Chrome10-25,Safari5.1-6 */
background: linear-gradient(to right, rgba(255,255,255,0.9) 51%,rgba(125,185,232,0.01) 100%);
/* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#e6ffffff', endColorstr='#037db9e8',GradientType=1 );
/* IE6-9 */
}

.left-arrow-winners ,
.right-arrow-winners {
    cursor: pointer;
    font: 18px/32px icomoon;
    position: absolute;
    top: 4px;
}

.left-arrow-winners {
    left: 0
}

.right-arrow-winners {
    right: 0
}

.left-arrow-winners:before {
    content: "\e92a";
}

.right-arrow-winners:before {
    content: "\e92b";
}
div{
background-color:blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
   <ul>
      <li>...</li>
      <li>...</li>
      <li>...</li>
      <li>...</li>
      <li>...</li>
   </ul>

   <span class="left-arrow-winners"></span>
   <span class="right-arrow-winners" ></span>
<div></code>```

ContentLicense: CC BY-SA 3.0

Title: Background: transparent does not work

Body:
I try to use background-color transparent for my task (can see in image) , but its not useful . Background-transparent do nothing , its show li's background-color .

I try many ways but its not working . What can i do ?

Thanks in advance .

HTML:

...

...

...

...

...

CSS:

li {
    display: inline-block;
    box-sizing: border-box;
    margin: 0 12px;
    padding: 4px 12px;
    background-color: rgba(230, 229, 220, 0.75);
    transition: all 250ms;
    border-radius: 4px;
}

.left-arrow-winners ,
.right-arrow-winners {
    cursor: pointer;
    font: 18px/32px icomoon;
    position: absolute;
    top: 4px;
}

.left-arrow-winners {
    left: 0
}

.right-arrow-winners {
    right: 0
}

.left-arrow-winners:before {
    content: "\e92a";
}

.right-arrow-winners:before {
    content: "\e92b";
}

Body:
This can be your best friend: http://www.colorzilla.com/gradient-editor/

Is this what you were looking for?

White - fade to transparent background?

li {
    display: inline-block;
    box-sizing: border-box;
    margin: 0 12px;
    padding: 4px 12px;
    background-color: rgba(230, 229, 220, 0.75);
    transition: all 250ms;
    border-radius: 4px;
}
li{
/* Permalink - use to edit and share this gradient: http://colorzilla.com/gradient-editor/#ffffff+51,7db9e8+100&0.9+51,0.01+100 */
background: -moz-linear-gradient(left, rgba(255,255,255,0.9) 51%, rgba(125,185,232,0.01) 100%);
/* FF3.6-15 */
background: -webkit-linear-gradient(left, rgba(255,255,255,0.9) 51%,rgba(125,185,232,0.01) 100%);
/* Chrome10-25,Safari5.1-6 */
background: linear-gradient(to right, rgba(255,255,255,0.9) 51%,rgba(125,185,232,0.01) 100%);
/* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#e6ffffff', endColorstr='#037db9e8',GradientType=1 );
/* IE6-9 */
}

.left-arrow-winners ,
.right-arrow-winners {
    cursor: pointer;
    font: 18px/32px icomoon;
    position: absolute;
    top: 4px;
}

.left-arrow-winners {
    left: 0
}

.right-arrow-winners {
    right: 0
}

.left-arrow-winners:before {
    content: "\e92a";
}

.right-arrow-winners:before {
    content: "\e92b";
}
div{
background-color:blue;
}

<div>
   <ul>
      <li>...</li>
      <li>...</li>
      <li>...</li>
      <li>...</li>
      <li>...</li>
   </ul>

   <span class="left-arrow-winners"></span>
   <span class="right-arrow-winners" ></span>
<div>


问:
Not updating value in database instead Inserting new entry
I am using below code to update database and putting where clause for date

```<code> ContentValues values = new ContentValues();
    values.put(DBTransactions.USER_ID_KEY, userId);
    values.put(DBTransactions.DATE_KEY, date);
    values.put(DBTransactions.DAY_KEY, day);
    values.put(DBTransactions.GOAL_KEY, dailyGoal);
    values.put(DBTransactions.VOLUME_KEY, dailyVolume);
    values.put(DBTransactions.IS_GOAL_MET_KEY, goalMet);
    db.getWritableDatabase().update(DBTransactions.TRANSACTION_TABLE_NAME, values, DBTransactions.DATE_KEY + " = ?", new String[]{date});
    closeDB();
</code>```

am I wrong somewhere in putting where clause? Its not updating database, Its creating new entry in database.

Its not updating database.
Thanks in Advance

答:
What is data type of DBTransactions.DATE_KEY column in DBTransactions.TRANSACTION_TABLE_NAME table?

Insert data in local database and check the format in which date is inserting in DBTransactions.TRANSACTION_TABLE_NAME table.

While updating record based on DBTransactions.DATE_KEY condition, check DBTransactions.DATE_KEY matches value stored in DBTransactions.TRANSACTION_TABLE_NAME DBTransactions.DATE_KEY column.

Everything else in your code seems to be fine.

Body:
I am using below code to update database and putting where clause for date

 ContentValues values = new ContentValues();
    values.put(DBTransactions.USER_ID_KEY, userId);
    values.put(DBTransactions.DATE_KEY, date);
    values.put(DBTransactions.DAY_KEY, day);
    values.put(DBTransactions.GOAL_KEY, dailyGoal);
    values.put(DBTransactions.VOLUME_KEY, dailyVolume);
    values.put(DBTransactions.IS_GOAL_MET_KEY, goalMet);
    db.getWritableDatabase().update(DBTransactions.TRANSACTION_TABLE_NAME, values, DBTransactions.DATE_KEY + " = ?", new String[]{date});
    closeDB();

am I wrong somewhere in putting where clause? Its not updating database, Its creating new entry in database.

Its not updating database.
Thanks in Advance


问:
C# How to use Directory White Spaces into process.arguements?
The program created utilizes a 3rd party tool to generate a log file.

However the arguments provided for the the tool requires various files from Directory locations as part of generating the logs. Therefore the main argument of @"-r C:\test\ftk\ntuser.dat -d C:\System Volume Information\" + restoreFolder.Name + " -p runmru"; would be used to generate the logs.

May someone advise on how to make the arguments of "C:\System Volume Information\" be processed by the system with the white spaces in placed? Thanks!

The codes:

```<code>            Process process = new Process();
            process.StartInfo.FileName = @"C:\test\ftk\ripxp\ripxp.exe";
            process.StartInfo.Arguments = @"-r C:\test\ftk\ntuser.dat -d C:\System Volume Information\" + restoreFolder.Name + " -p runmru";
            process.StartInfo.CreateNoWindow = false;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardError = true;
            process.Start();
</code>```

答:
Wrap that path in double quotes:</p>

```<code>process.StartInfo.Arguments = @"-r C:\test\ftk\ntuser.dat -d ""C:\System Volume Information\" + restoreFolder.Name + @""" -p runmru";
</code>```

ContentLicense: CC BY-SA 2.5

Body:
The program created utilizes a 3rd party tool to generate a log file.

However the arguments provided for the the tool requires various files from Directory locations as part of generating the logs. Therefore the main argument of @"-r C:\test\ftk\ntuser.dat -d C:\System Volume Information\" + restoreFolder.Name + " -p runmru"; would be used to generate the logs.

May someone advise on how to make the arguments of "C:\System Volume Information\" be processed by the system with the white spaces in placed? Thanks!

The codes:

            Process process = new Process();
            process.StartInfo.FileName = @"C:\test\ftk\ripxp\ripxp.exe";
            process.StartInfo.Arguments = @"-r C:\test\ftk\ntuser.dat -d C:\System Volume Information\" + restoreFolder.Name + " -p runmru";
            process.StartInfo.CreateNoWindow = false;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardError = true;
            process.Start();

Body:
Wrap that path in double quotes:

process.StartInfo.Arguments = @"-r C:\test\ftk\ntuser.dat -d ""C:\System Volume Information\" + restoreFolder.Name + @""" -p runmru";


问:
How to calculate nearest restaurant, but my code is showing all nearby restaurants
My code is searching for nearby restaurants and working well by showing all nearest restaurants on Map,
But i want to get very near restaurant, i want to show only 1 restaurant in TextView, i don't know how i can calculate shortest path for that. Please help, Thanks:) </p>

```<code>import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import java.util.HashMap;
import java.util.List;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

    private GoogleMap mMap;
    double latitude;
    double longitude;
    private int PROXIMITY_RADIUS = 10000;
    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    Marker mCurrLocationMarker;
    LocationRequest mLocationRequest;

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

    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        checkLocationPermission();
    }

    //Check if Google Play Services Available or not
    if (!CheckGooglePlayServices()) {
        Log.d("onCreate", "Finishing test case since Google Play Services are not available");
        finish();
    }
    else {
        Log.d("onCreate","Google Play Services available.");
    }

    // 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);
}

private boolean CheckGooglePlayServices() {
    GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
    int result = googleAPI.isGooglePlayServicesAvailable(this);
    if(result != ConnectionResult.SUCCESS) {
        if(googleAPI.isUserResolvableError(result)) {
            googleAPI.getErrorDialog(this, result,
                    0).show();
        }
        return false;
    }
    return true;
}

/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

    //Initialize Google Play Services
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);
        }
    }
    else {
        buildGoogleApiClient();
        mMap.setMyLocationEnabled(true);
    }

    Button btnRestaurant = (Button) findViewById(R.id.btnRestaurant);
    btnRestaurant.setOnClickListener(new View.OnClickListener() {
        String Restaurant = "restaurant";
        @Override
        public void onClick(View v) {
            Log.d("onClick", "Button is Clicked");
            mMap.clear();
            String url = getUrl(latitude, longitude, Restaurant);
            Object[] DataTransfer = new Object[2];
            DataTransfer[0] = mMap;
            DataTransfer[1] = url;
            Log.d("onClick", url);
            GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
            getNearbyPlacesData.execute(DataTransfer);
            Toast.makeText(MapsActivity.this,"Nearby Restaurants", Toast.LENGTH_LONG).show();
        }
    });

}

protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();
}

@Override
public void onConnected(Bundle bundle) {
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(1000);
    mLocationRequest.setFastestInterval(1000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }
}

private String getUrl(double latitude, double longitude, String nearbyPlace) {

    StringBuilder googlePlacesUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
    googlePlacesUrl.append("location=" + latitude + "," + longitude);
    googlePlacesUrl.append("&radius=" + PROXIMITY_RADIUS);
    googlePlacesUrl.append("&type=" + nearbyPlace);
    googlePlacesUrl.append("&sensor=true");
    googlePlacesUrl.append("&key=" + "AIzaSyATuUiZUkEc_UgHuqsBJa1oqaODI-3mLs0");
    Log.d("getUrl", googlePlacesUrl.toString());
    return (googlePlacesUrl.toString());
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onLocationChanged(Location location) {
    Log.d("onLocationChanged", "entered");

    mLastLocation = location;
    if (mCurrLocationMarker != null) {
        mCurrLocationMarker.remove();
    }

    //Place current location marker
    latitude = location.getLatitude();
    longitude = location.getLongitude();
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    markerOptions.title("Current Position");
    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
    mCurrLocationMarker = mMap.addMarker(markerOptions);

    //move map camera
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
    Toast.makeText(MapsActivity.this,"Your Current Location", Toast.LENGTH_LONG).show();

    Log.d("onLocationChanged", String.format("latitude:%.3f longitude:%.3f",latitude,longitude));

    //stop location updates
    if (mGoogleApiClient != null) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        Log.d("onLocationChanged", "Removing Location Updates");
    }
    Log.d("onLocationChanged", "Exit");

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {

        // Asking user if explanation is needed
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {

            // Show an explanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.

            //Prompt the user once explanation has been shown
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION);

        } else {
            // No explanation needed, we can request the permission.
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION);
        }
        return false;
    } else {
        return true;
    }
}

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_LOCATION: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted. Do the
                // contacts-related task you need to do.
                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED) {

                    if (mGoogleApiClient == null) {
                        buildGoogleApiClient();
                    }
                    mMap.setMyLocationEnabled(true);
                }

            } else {

                // Permission denied, Disable the functionality that depends on this permission.
                Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
            }
            return;
        }

        // other 'case' lines to check for other permissions this app might request.
        // You can add here other case statements according to your requirement.
    }
}
</code>```

<p>}</p>

答:
Pseudocode for finding the item that is closest:</p>

```<code>closest = none;
for each item in items
{
  if(!closest || item.distance > closest.distance)
  {
    closest = item
  }
}
print "Closest Item is: " closest
</code>```

Body:
My code is searching for nearby restaurants and working well by showing all nearest restaurants on Map,
But i want to get very near restaurant, i want to show only 1 restaurant in TextView, i don't know how i can calculate shortest path for that. Please help, Thanks:)

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import java.util.HashMap;
import java.util.List;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

    private GoogleMap mMap;
    double latitude;
    double longitude;
    private int PROXIMITY_RADIUS = 10000;
    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    Marker mCurrLocationMarker;
    LocationRequest mLocationRequest;

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

    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        checkLocationPermission();
    }

    //Check if Google Play Services Available or not
    if (!CheckGooglePlayServices()) {
        Log.d("onCreate", "Finishing test case since Google Play Services are not available");
        finish();
    }
    else {
        Log.d("onCreate","Google Play Services available.");
    }

    // 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);
}

private boolean CheckGooglePlayServices() {
    GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
    int result = googleAPI.isGooglePlayServicesAvailable(this);
    if(result != ConnectionResult.SUCCESS) {
        if(googleAPI.isUserResolvableError(result)) {
            googleAPI.getErrorDialog(this, result,
                    0).show();
        }
        return false;
    }
    return true;
}

/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

    //Initialize Google Play Services
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);
        }
    }
    else {
        buildGoogleApiClient();
        mMap.setMyLocationEnabled(true);
    }

    Button btnRestaurant = (Button) findViewById(R.id.btnRestaurant);
    btnRestaurant.setOnClickListener(new View.OnClickListener() {
        String Restaurant = "restaurant";
        @Override
        public void onClick(View v) {
            Log.d("onClick", "Button is Clicked");
            mMap.clear();
            String url = getUrl(latitude, longitude, Restaurant);
            Object[] DataTransfer = new Object[2];
            DataTransfer[0] = mMap;
            DataTransfer[1] = url;
            Log.d("onClick", url);
            GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
            getNearbyPlacesData.execute(DataTransfer);
            Toast.makeText(MapsActivity.this,"Nearby Restaurants", Toast.LENGTH_LONG).show();
        }
    });

}

protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();
}

@Override
public void onConnected(Bundle bundle) {
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(1000);
    mLocationRequest.setFastestInterval(1000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }
}

private String getUrl(double latitude, double longitude, String nearbyPlace) {

    StringBuilder googlePlacesUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
    googlePlacesUrl.append("location=" + latitude + "," + longitude);
    googlePlacesUrl.append("&radius=" + PROXIMITY_RADIUS);
    googlePlacesUrl.append("&type=" + nearbyPlace);
    googlePlacesUrl.append("&sensor=true");
    googlePlacesUrl.append("&key=" + "AIzaSyATuUiZUkEc_UgHuqsBJa1oqaODI-3mLs0");
    Log.d("getUrl", googlePlacesUrl.toString());
    return (googlePlacesUrl.toString());
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onLocationChanged(Location location) {
    Log.d("onLocationChanged", "entered");

    mLastLocation = location;
    if (mCurrLocationMarker != null) {
        mCurrLocationMarker.remove();
    }

    //Place current location marker
    latitude = location.getLatitude();
    longitude = location.getLongitude();
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    markerOptions.title("Current Position");
    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
    mCurrLocationMarker = mMap.addMarker(markerOptions);

    //move map camera
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
    Toast.makeText(MapsActivity.this,"Your Current Location", Toast.LENGTH_LONG).show();

    Log.d("onLocationChanged", String.format("latitude:%.3f longitude:%.3f",latitude,longitude));

    //stop location updates
    if (mGoogleApiClient != null) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        Log.d("onLocationChanged", "Removing Location Updates");
    }
    Log.d("onLocationChanged", "Exit");

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {

        // Asking user if explanation is needed
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {

            // Show an explanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.

            //Prompt the user once explanation has been shown
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION);

        } else {
            // No explanation needed, we can request the permission.
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION);
        }
        return false;
    } else {
        return true;
    }
}

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_LOCATION: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted. Do the
                // contacts-related task you need to do.
                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED) {

                    if (mGoogleApiClient == null) {
                        buildGoogleApiClient();
                    }
                    mMap.setMyLocationEnabled(true);
                }

            } else {

                // Permission denied, Disable the functionality that depends on this permission.
                Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
            }
            return;
        }

        // other 'case' lines to check for other permissions this app might request.
        // You can add here other case statements according to your requirement.
    }
}

}

Body:
Pseudocode for finding the item that is closest:

closest = none;
for each item in items
{
  if(!closest || item.distance > closest.distance)
  {
    closest = item
  }
}
print "Closest Item is: " closest


问:
PHP - Session ID changing when using session.use_trans_sid
I have developed a PHP web application that used cookie-based sessions and it was all working fine - until I realised that it won't work in browsers that have third party cookies disabled (because the script is going to be loaded in an iframe on another website/domain).

So I decided to switch over to URL-based sessions (which I presume will be safe as, because the script is in an iframe, there will be no visible URL for the user to share or bookmark, etc.).

However, for some reason, since I switched to domain-based sessions, each page in my web application is using a different session ID.

Here's my code...

```<code>ini_set("session.use_cookies", 0);
ini_set("session.use_only_cookies", 0);
ini_set("session.use_trans_sid", 1);
ini_set("session.cache_limiter", "");
session_start();
echo "<p>Session ID: " . session_id() . "</p>"; // Test output
</code>```

...which is the very first thing to be called on each page (with no previous output that I'm aware of).

The first page in my web app contains a form and I see that the required hidden session ID input is automatically added to it by PHP:

<input type="hidden" name="PHPSESSID" value="m4jbeec47uplnf95ue2h244a02" />

But the session ID reported by the next page (that the form submits to) is

Session ID: iiovfkrf3hesj1um5orasv7it6

Also, when I load the first page using https:// (instead of http://), submitting the form results in the same page being reloaded (rather than the next page being loaded).

What I've already tried:

ini_set("session.cookie_secure", 0);

and

ini_set("session.cookie_secure", 1);

and

ini_set('session.gc_maxlifetime', 30 * 60); // expires in 30 minutes

and (at the end of the script)

session_write_close();

and removing

ini_set("session.cache_limiter", "");

From phpinfo():

```<code>session.auto_start  Off Off
session.cache_expire    180 180
session.cache_limiter   nocache nocache
session.cookie_domain   no value    no value
session.cookie_httponly Off Off
session.cookie_lifetime 0   0
session.cookie_path /   /
session.cookie_secure   Off Off
session.entropy_file    no value    no value
session.entropy_length  0   0
session.gc_divisor  1000    1000
session.gc_maxlifetime  1440    1440
session.gc_probability  1   1
session.hash_bits_per_character 5   5
session.hash_function   0   0
session.name    PHPSESSID   PHPSESSID
session.referer_check   no value    no value
session.save_handler    files   files
session.save_path   /tmp    /tmp
session.serialize_handler   php php
session.upload_progress.cleanup On  On
session.upload_progress.enabled On  On
session.upload_progress.freq    1%  1%
session.upload_progress.min_freq    1   1
session.upload_progress.name    PHP_SESSION_UPLOAD_PROGRESS PHP_SESSION_UPLOAD_PROGRESS
session.upload_progress.prefix  upload_progress_    upload_progress_
session.use_cookies On  On
session.use_only_cookies    On  On
session.use_strict_mode Off Off
session.use_trans_sid   0   0
</code>```

Any ideas?

答:
I think the problem must be due to a bug in my code somewhere. I've created the test script, below, and it works as expected (on the same server):

url-session-test.php

```<code><?php

$page_title = "URL Session Test (v11)";

ini_set("session.use_cookies", 0);
ini_set("session.use_only_cookies", 0);
ini_set("session.use_trans_sid", 1);
//ini_set("session.cache_limiter", "");
ini_set('session.gc_maxlifetime', 30 * 60); // expires in 30 minutes
session_start();
$session_id = session_id();

$is_new_session = !isset($_SESSION["existing"]);
$_SESSION["existing"] = true;
if ($is_new_session) {
    $_SESSION["my_key"] = "MY PRIVATE KEY";
}
$my_session_key = $_SESSION["my_key"];

$timezone = $_SESSION["timezone"];
if ($timezone) {
    date_default_timezone_set($timezone);
}

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

?><!DOCTYPE html>
<html>
    <head>
        <title><?php echo $page_title; ?></title>
    </head>
    <body>
        <h1><?php echo $page_title; ?></h1>
        <p>Is new session: <?php echo $is_new_session; ?></p>
        <p>My session key: <?php echo $my_session_key; ?></p>
        <p>Received session ID: <?php echo $session_id_received; ?></p>
        <p>Actual session ID: <?php echo $session_id; ?></p>
        <form method="POST">
            <input type="submit" value="Click this form submit button to see how if the above session ID is received by the next page" />
        </form>
        <a href="url-session-test.php">Hover over this link to check the session ID parameter</a>
    </body>
</html>
</code>```

Will post the actual bug once I've found it...

UPDATE

The problem was that I was using a POST-Redirect-GET model and I was not appending the required PHPSESSID parameter to the GET url!

Body:
I have developed a PHP web application that used cookie-based sessions and it was all working fine - until I realised that it won't work in browsers that have third party cookies disabled (because the script is going to be loaded in an iframe on another website/domain).

So I decided to switch over to URL-based sessions (which I presume will be safe as, because the script is in an iframe, there will be no visible URL for the user to share or bookmark, etc.).

However, for some reason, since I switched to domain-based sessions, each page in my web application is using a different session ID.

Here's my code...

ini_set("session.use_cookies", 0);
ini_set("session.use_only_cookies", 0);
ini_set("session.use_trans_sid", 1);
ini_set("session.cache_limiter", "");
session_start();
echo "
Session ID: " . session_id() . "
"; // Test output

...which is the very first thing to be called on each page (with no previous output that I'm aware of).

The first page in my web app contains a form and I see that the required hidden session ID input is automatically added to it by PHP:

<input type="hidden" name="PHPSESSID" value="m4jbeec47uplnf95ue2h244a02" />

But the session ID reported by the next page (that the form submits to) is

Session ID: iiovfkrf3hesj1um5orasv7it6

Also, when I load the first page using https:// (instead of http://), submitting the form results in the same page being reloaded (rather than the next page being loaded).

What I've already tried:

ini_set("session.cookie_secure", 0);

and

ini_set("session.cookie_secure", 1);

and

ini_set('session.gc_maxlifetime', 30 * 60); // expires in 30 minutes

and (at the end of the script)

session_write_close();

and removing

ini_set("session.cache_limiter", "");

From phpinfo():

session.auto_start  Off Off
session.cache_expire    180 180
session.cache_limiter   nocache nocache
session.cookie_domain   no value    no value
session.cookie_httponly Off Off
session.cookie_lifetime 0   0
session.cookie_path /   /
session.cookie_secure   Off Off
session.entropy_file    no value    no value
session.entropy_length  0   0
session.gc_divisor  1000    1000
session.gc_maxlifetime  1440    1440
session.gc_probability  1   1
session.hash_bits_per_character 5   5
session.hash_function   0   0
session.name    PHPSESSID   PHPSESSID
session.referer_check   no value    no value
session.save_handler    files   files
session.save_path   /tmp    /tmp
session.serialize_handler   php php
session.upload_progress.cleanup On  On
session.upload_progress.enabled On  On
session.upload_progress.freq    1%  1%
session.upload_progress.min_freq    1   1
session.upload_progress.name    PHP_SESSION_UPLOAD_PROGRESS PHP_SESSION_UPLOAD_PROGRESS
session.upload_progress.prefix  upload_progress_    upload_progress_
session.use_cookies On  On
session.use_only_cookies    On  On
session.use_strict_mode Off Off
session.use_trans_sid   0   0

Any ideas?

Body:
I think the problem must be due to a bug in my code somewhere. I've created the test script, below, and it works as expected (on the same server):

url-session-test.php

<?php

$page_title = "URL Session Test (v11)";

ini_set("session.use_cookies", 0);
ini_set("session.use_only_cookies", 0);
ini_set("session.use_trans_sid", 1);
//ini_set("session.cache_limiter", "");
ini_set('session.gc_maxlifetime', 30 * 60); // expires in 30 minutes
session_start();
$session_id = session_id();

$is_new_session = !isset($_SESSION["existing"]);
$_SESSION["existing"] = true;
if ($is_new_session) {
    $_SESSION["my_key"] = "MY PRIVATE KEY";
}
$my_session_key = $_SESSION["my_key"];

$timezone = $_SESSION["timezone"];
if ($timezone) {
    date_default_timezone_set($timezone);
}

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

?><!DOCTYPE html>
<html>
    <head>
        <title><?php echo $page_title; ?></title>
    </head>
    <body>
        <h1><?php echo $page_title; ?></h1>
        <p>Is new session: <?php echo $is_new_session; ?></p>
        <p>My session key: <?php echo $my_session_key; ?></p>
        <p>Received session ID: <?php echo $session_id_received; ?></p>
        <p>Actual session ID: <?php echo $session_id; ?></p>
        <form method="POST">
            <input type="submit" value="Click this form submit button to see how if the above session ID is received by the next page" />
        </form>
        <a href="url-session-test.php">Hover over this link to check the session ID parameter</a>
    </body>
</html>

Will post the actual bug once I've found it...

UPDATE

The problem was that I was using a POST-Redirect-GET model and I was not appending the required PHPSESSID parameter to the GET url!


问:
Dojo how to extend a dijit class?
I need to add some custom function on  dijit/form/Select at the moment I use the following code but I get the following error:

Uncaught TypeError: SelectGroup is not a constructor

How to fix this issue ?

```<code>require([
  'dijit/form/Select',
  'dojo/_base/window',
  'dojo/domReady!'
], function(Select, win) {

  var SelectGroup = define([
    "dojo/_base/declare",
    "dijit/form/Select"
  ], function(declare, Select) {
    return declare(Select, {
      myCustom: function() {
        alert('hey custom');
      }
    });
  });

  var select = new SelectGroup({
    name: 'select',
    options: [{
      label: '<i>Colors I love</i>',
      value: 'G 1',
      disabled: true
    }, {
      label: 'Red',
      value: '1'
    }, {
      label: 'Green',
      value: '2',
      selected: true
    },
    ]
  }, 'select');

  select.on('change', function(value) {
    alert(value);
  });

});
</code>```

答:
I think It was just an error from you when writing the define() inside require , (AMD imbrication calls ) !

It's Simple , You have just to make all your import(requires) including the declare , and the call declare ( to make your widget direclty ) , it'll return the new widget in your var SelectGroup reference

Please find below a working snippet :

require([
    "dojo/_base/declare",
    "dijit/form/Select",
    'dojo/_base/window',
    'dojo/domReady!'
  ], function(declare, Select, win) {

    var SelectGroup = declare(Select, {
      myCustom: function() {
        alert('hey custom calue is = '+this.value);
      }
    });

    var select = new SelectGroup({
    name: 'select',
    options: [{
        label: 'Colors I love',
        value: 'G 1',
        disabled: true
      }, {
        label: 'Red',
        value: '1'
      }, {
        label: 'Green',
        value: '2',
        selected: true
      },
    ]
  }, 'select');

    select.on('change', function(value) {
      select.myCustom();
    });

  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/dojo/1.12.1/dijit/themes/claro/claro.css" />

<script>
  window.dojoConfig = {
    parseOnLoad: false,
    async: true
  };
</script>

<script src="//ajax.googleapis.com/ajax/libs/dojo/1.12.1/dojo/dojo.js"></script>

<body class="claro">
  <div id="select"></div>
</body></code>```

Title: Dojo how to extend a dijit class?

Body:
I need to add some custom function on  dijit/form/Select at the moment I use the following code but I get the following error:

Uncaught TypeError: SelectGroup is not a constructor

How to fix this issue ?

require([
  'dijit/form/Select',
  'dojo/_base/window',
  'dojo/domReady!'
], function(Select, win) {

  var SelectGroup = define([
    "dojo/_base/declare",
    "dijit/form/Select"
  ], function(declare, Select) {
    return declare(Select, {
      myCustom: function() {
        alert('hey custom');
      }
    });
  });

  var select = new SelectGroup({
    name: 'select',
    options: [{
      label: 'Colors I love',
      value: 'G 1',
      disabled: true
    }, {
      label: 'Red',
      value: '1'
    }, {
      label: 'Green',
      value: '2',
      selected: true
    },
    ]
  }, 'select');

  select.on('change', function(value) {
    alert(value);
  });

});

Body:
I think It was just an error from you when writing the define() inside require , (AMD imbrication calls ) !

It's Simple , You have just to make all your import(requires) including the declare , and the call declare ( to make your widget direclty ) , it'll return the new widget in your var SelectGroup reference

Please find below a working snippet :

require([
    "dojo/_base/declare",
    "dijit/form/Select",
    'dojo/_base/window',
    'dojo/domReady!'
  ], function(declare, Select, win) {

    var SelectGroup = declare(Select, {
      myCustom: function() {
        alert('hey custom calue is = '+this.value);
      }
    });

    var select = new SelectGroup({
    name: 'select',
    options: [{
        label: '<i>Colors I love</i>',
        value: 'G 1',
        disabled: true
      }, {
        label: 'Red',
        value: '1'
      }, {
        label: 'Green',
        value: '2',
        selected: true
      },
    ]
  }, 'select');

    select.on('change', function(value) {
      select.myCustom();
    });

  });

<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/dojo/1.12.1/dijit/themes/claro/claro.css" />

<script>
  window.dojoConfig = {
    parseOnLoad: false,
    async: true
  };
</script>

<script src="//ajax.googleapis.com/ajax/libs/dojo/1.12.1/dojo/dojo.js"></script>

<body class="claro">
  <div id="select"></div>
</body>


问:
php is not adding data to mysql
```<code>$date = date('Y-m-d H:i:s');
        $qry = "INSERT INTO `guest` (`name`, `pincode`, `address`, `phone`, `date`) VALUES ('".$_SESSION['name']."', '".$_SESSION['pincode']."', '".$_SESSION['address']."', '".$_SESSION['phone']."', '".$date."');";
        $result = $conn->query($qry);
        //echo $qry;
        $qry = "select guest_id from guest where name = '".$_SESSION['name']."' and pincode = '".$_SESSION['pincode']."' and address= '".$_SESSION['address']."' and phone= '".$_SESSION['phone']."' and date= '".$date."';";
        //echo $qry;
        $result = $conn->query($qry);
        $row = $result -> fetch_assoc();
        //echo $row['guest_id'];
        $guest_id = $row['guest_id'];
        $date = date('Y-m-d H:i:s');
        //$qry1 = "INSERT INTO order (`order_date`, `payment_type`, `payment_status`, `order_status`, `order_type`, `amount`, `cust_id`) VALUES ('".$date."', 'cod', 'yes', 'Pending', 'yes', ".$_SESSION['total'].", '".$guest_id."');";
        $qry1 = "INSERT INTO `grocery`.`order` (`order_date`, `payment_type`, `payment_status`, `order_status`, `delivery_slot`, `order_type`, `amount`, `deliver_date`, `cust_id`) VALUES ('sd', 'asd', 'sdf', 'sd', '4', 'sf', '23', '2017-04-19', 'sdfs');";

        $result1 = $conn->query($qry1);
        echo $qry1;
</code>```

The first 2 queries are getting executed and data is added to db.. But the last statement is not adding the data to db. Please help me out

答:
Leaving the issue of SQL injection to one side, for just a moment, it seems to me that everything after line 3 could be replaced with this:</p>

```<code>        INSERT INTO `order`
        (order_date
        ,payment_type
        ,payment_status
        ,order_status
        ,order_type
        ,amount
        ,cust_id)
        SELECT CURDATE()
             , 'cod'
             , 'yes'
             , 'Pending'
             , 'yes'
             , {$_SESSION['total']}
             , guest_id
          FROM guest
         WHERE name    = '{$_SESSION['name']}'
           AND pincode = '{$_SESSION['pincode']}'
           AND address = '{$_SESSION['address']}'
           AND phone   = '{$_SESSION['phone']}'
           AND date    = CURDATE();
</code>```

Title: php is not adding data to mysql

Body:
$date = date('Y-m-d H:i:s');
        $qry = "INSERT INTO `guest` (`name`, `pincode`, `address`, `phone`, `date`) VALUES ('".$_SESSION['name']."', '".$_SESSION['pincode']."', '".$_SESSION['address']."', '".$_SESSION['phone']."', '".$date."');";
        $result = $conn->query($qry);
        //echo $qry;
        $qry = "select guest_id from guest where name = '".$_SESSION['name']."' and pincode = '".$_SESSION['pincode']."' and address= '".$_SESSION['address']."' and phone= '".$_SESSION['phone']."' and date= '".$date."';";
        //echo $qry;
        $result = $conn->query($qry);
        $row = $result -> fetch_assoc();
        //echo $row['guest_id'];
        $guest_id = $row['guest_id'];
        $date = date('Y-m-d H:i:s');
        //$qry1 = "INSERT INTO order (`order_date`, `payment_type`, `payment_status`, `order_status`, `order_type`, `amount`, `cust_id`) VALUES ('".$date."', 'cod', 'yes', 'Pending', 'yes', ".$_SESSION['total'].", '".$guest_id."');";
        $qry1 = "INSERT INTO `grocery`.`order` (`order_date`, `payment_type`, `payment_status`, `order_status`, `delivery_slot`, `order_type`, `amount`, `deliver_date`, `cust_id`) VALUES ('sd', 'asd', 'sdf', 'sd', '4', 'sf', '23', '2017-04-19', 'sdfs');";

        $result1 = $conn->query($qry1);
        echo $qry1;

The first 2 queries are getting executed and data is added to db.. But the last statement is not adding the data to db. Please help me out

Body:
Leaving the issue of SQL injection to one side, for just a moment, it seems to me that everything after line 3 could be replaced with this:

        INSERT INTO `order`
        (order_date
        ,payment_type
        ,payment_status
        ,order_status
        ,order_type
        ,amount
        ,cust_id)
        SELECT CURDATE()
             , 'cod'
             , 'yes'
             , 'Pending'
             , 'yes'
             , {$_SESSION['total']}
             , guest_id
          FROM guest
         WHERE name    = '{$_SESSION['name']}'
           AND pincode = '{$_SESSION['pincode']}'
           AND address = '{$_SESSION['address']}'
           AND phone   = '{$_SESSION['phone']}'
           AND date    = CURDATE();


问:
comparison condition in case statement
I want to have a comparison in case statement in sql statement

```<code>  SUM(CASE
    WHEN bt.idBillingStatus = 2  and o.idOperator = 5 and cs.idClub=1
    THEN (price * revenueShareAmountLocal * o.mfactor *0.08)
</code>```

and  second one is

```<code>SUM(CASE
    WHEN bt.idBillingStatus = 2  and o.idOperator = 5 and cs.idClub=2
    THEN (price * revenueShareAmountLocal * o.mfactor *0.04)
</code>```

I want make a comparison that if bt.idBillingStatus = 2  and o.idOperator = 5 and cs.idClub=2 > bt.idBillingStatus = 2  and o.idOperator = 5 and cs.idClub=1
then (price * revenueShareAmountLocal * o.mfactor *0.01)

Else
if bt.idBillingStatus = 2  and o.idOperator = 5 and cs.idClub=2 < bt.idBillingStatus = 2  and o.idOperator = 5 and cs.idClub=1
then (price * revenueShareAmountLocal * o.mfactor *0.08)

In simple words, I need to put a comparison in the case statement that if one is greater than another then sum this else sum something else.

答:
As you have not included your data or table structures the help we can provide here is limited, though it sounds like you need one of the following:

```<code>SUM(CASE
      WHEN bt.idBillingStatus = 2  and o.idOperator = 5 and cs.idClub=1
        THEN (price * revenueShareAmountLocal * o.mfactor *0.08)

      WHEN bt.idBillingStatus = 2  and o.idOperator = 5 and cs.idClub=2
        THEN (price * revenueShareAmountLocal * o.mfactor *0.04)

      ELSE 0
    END
   )
</code>```

or the sightly more verbose option, which would suggest bad query design on your part that should be looked into:

```<code>CASE
  WHEN SUM(CASE
             WHEN bt.idBillingStatus = 2  and o.idOperator = 5 and cs.idClub=2
               THEN (price * revenueShareAmountLocal * o.mfactor *0.04)

             ELSE 0
           END
          )
       > SUM(CASE
             WHEN bt.idBillingStatus = 2  and o.idOperator = 5 and cs.idClub=1
               THEN (price * revenueShareAmountLocal * o.mfactor *0.08)

             ELSE 0
           END
          )
  THEN SUM(CASE
             WHEN bt.idBillingStatus = 2  and o.idOperator = 5 and cs.idClub=2
               THEN (price * revenueShareAmountLocal * o.mfactor *0.04)

             ELSE 0
           END
          )

   ELSE SUM(CASE
             WHEN bt.idBillingStatus = 2  and o.idOperator = 5 and cs.idClub=1
               THEN (price * revenueShareAmountLocal * o.mfactor *0.08)

             ELSE 0
           END
          )
END
</code>```

Title: comparison condition in case statement

Body:
I want to have a comparison in case statement in sql statement

  SUM(CASE
    WHEN bt.idBillingStatus = 2  and o.idOperator = 5 and cs.idClub=1
    THEN (price * revenueShareAmountLocal * o.mfactor *0.08)

and  second one is

SUM(CASE
    WHEN bt.idBillingStatus = 2  and o.idOperator = 5 and cs.idClub=2
    THEN (price * revenueShareAmountLocal * o.mfactor *0.04)

I want make a comparison that if bt.idBillingStatus = 2  and o.idOperator = 5 and cs.idClub=2 > bt.idBillingStatus = 2  and o.idOperator = 5 and cs.idClub=1
then (price * revenueShareAmountLocal * o.mfactor *0.01)

Else
if bt.idBillingStatus = 2  and o.idOperator = 5 and cs.idClub=2 < bt.idBillingStatus = 2  and o.idOperator = 5 and cs.idClub=1
then (price * revenueShareAmountLocal * o.mfactor *0.08)

In simple words, I need to put a comparison in the case statement that if one is greater than another then sum this else sum something else.

Body:
As you have not included your data or table structures the help we can provide here is limited, though it sounds like you need one of the following:

SUM(CASE
      WHEN bt.idBillingStatus = 2  and o.idOperator = 5 and cs.idClub=1
        THEN (price * revenueShareAmountLocal * o.mfactor *0.08)

      WHEN bt.idBillingStatus = 2  and o.idOperator = 5 and cs.idClub=2
        THEN (price * revenueShareAmountLocal * o.mfactor *0.04)

      ELSE 0
    END
   )

or the sightly more verbose option, which would suggest bad query design on your part that should be looked into:

CASE
  WHEN SUM(CASE
             WHEN bt.idBillingStatus = 2  and o.idOperator = 5 and cs.idClub=2
               THEN (price * revenueShareAmountLocal * o.mfactor *0.04)

             ELSE 0
           END
          )
       > SUM(CASE
             WHEN bt.idBillingStatus = 2  and o.idOperator = 5 and cs.idClub=1
               THEN (price * revenueShareAmountLocal * o.mfactor *0.08)

             ELSE 0
           END
          )
  THEN SUM(CASE
             WHEN bt.idBillingStatus = 2  and o.idOperator = 5 and cs.idClub=2
               THEN (price * revenueShareAmountLocal * o.mfactor *0.04)

             ELSE 0
           END
          )

   ELSE SUM(CASE
             WHEN bt.idBillingStatus = 2  and o.idOperator = 5 and cs.idClub=1
               THEN (price * revenueShareAmountLocal * o.mfactor *0.08)

             ELSE 0
           END
          )
END


问:
Retrieving the File Name of a .mp3 file without the path
Reasoning:

I've seen this question duplicated a few times on this website, and each one seems to bring people to same conclusion.

Okay, so I have a music player located within a window. When the window opens, an OpenFileDialog method is ran, to where the user must pick a .mp3 file. Once done, they can play the file whilst navigating other windows in the program.

I'm trying to:

Enter the file name of the selected file into a label. With this, I want to show the file name as it is being played. I want to only show the file name, not the path to it as well.

What I've seen on duplicate questions:

Repeating fixes whereby I can use the following code to pick up the file name with or without the file extension:

```<code>label1.Content = Path.GetFileName(media.Source.ToString());

label1.Content = Path.GetFileNameWithoutExtension(media.Source.ToString());
</code>```

Issue:

I've tried to enter this on my program, but I don't have the "Path" section (I'm not too sure of the actual name of this part of code).

The closest I can get to this is: class System.Windows.Shapes.Path | Draws a series of connected lines and curves.

I don't seem to have another "path" in my VS, so I'm not too sure what to do.

Code (Sorry about the code here, it was a little awkward to copy into the question box)

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Microsoft.Win32;
using System.Windows.Threading;

namespace WolfAlbumCatalogue
{
    /// <summary>
    /// Interaction logic for MusicPlayer.xaml
    /// </summary>
    public partial class MusicPlayer : Window
    {
        private MediaPlayer mediaPlayer = new MediaPlayer();

        AlbumCatalogue albumCatalogue;

        public MusicPlayer(AlbumCatalogue parent)
        {
            InitializeComponent();
            albumCatalogue = parent;

            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "MP3 files (*.mp3)|*.mp3|All files(*.*)|*.*";
            if (openFileDialog.ShowDialog() == true)
                mediaPlayer.Open(new Uri(openFileDialog.FileName));

            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Tick += timer_Tick;
            timer.Tick += miniTimer_Tick;
            timer.Start();

            albumCatalogue.img_musicPlayerWindow.IsEnabled = false;

            lbl_songName.Content = Path
        }

        private void rec_closeHover_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            this.Close();
            albumCatalogue.img_musicPlayerWindow.IsEnabled = true;
        }

        void timer_Tick(object sender, EventArgs e)
        {
            if (mediaPlayer.Source != null)
            {
                lbl_timer.Content = String.Format("{0} / {1}", mediaPlayer.Position.ToString(@"mm\:ss"), mediaPlayer.NaturalDuration.TimeSpan.ToString(@"mm\:ss"));
            }
            else
            {
                lbl_timer.Content = "No file selected...";
            }
        }

        void miniTimer_Tick(object sender, EventArgs e)
        {
            if (mediaPlayer.Source != null)
            {
                lbl_miniTimer.Content = String.Format("{0} / {1}", mediaPlayer.Position.ToString(@"mm\:ss"), mediaPlayer.NaturalDuration.TimeSpan.ToString(@"mm\:ss"));
            }
            else
            {
                lbl_miniTimer.Content = "No file selected...";
            }
        }

        private void btn_play_Click(object sender, RoutedEventArgs e)
        {
            mediaPlayer.Play();
            lbl_play_pause.Content = "Playing...";
            lbl_play_pause.Visibility = Visibility.Visible;
        }

        private void btn_pause_Click(object sender, RoutedEventArgs e)
        {
            mediaPlayer.Pause();
            lbl_play_pause.Content = "Paused.";
            lbl_play_pause.Visibility = Visibility.Visible;
        }

        private void btn_stop_Click(object sender, RoutedEventArgs e)
        {
            mediaPlayer.Stop();
            lbl_play_pause.Visibility = Visibility.Hidden;
        }

        private void rec_titleBar_MouseDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }

        private void rec_windowBkg_MouseDown(object sender, MouseButtonEventArgs e)
        {
        this.DragMove();
        }

        private void rec_btnOpenAudioFile_MouseDown(object sender, MouseButtonEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "MP3 files (*.mp3)|*.mp3|All files(*.*)|*.*";
            if (openFileDialog.ShowDialog() == true)
                mediaPlayer.Open(new Uri(openFileDialog.FileName));

            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Tick += timer_Tick;
            timer.Start();
        }
    }
}
</code>```

I would copy in the XAML too but I use blend animations and it's way too long for this question. If you need it, please let me know :)

That said, I think that's everything!

Thank you

答:
Include the header System.IO in your application.
(using System.IO;) .If it is not found you need to add the reference System dll.</p>

Body:
Reasoning:

I've seen this question duplicated a few times on this website, and each one seems to bring people to same conclusion.

Okay, so I have a music player located within a window. When the window opens, an OpenFileDialog method is ran, to where the user must pick a .mp3 file. Once done, they can play the file whilst navigating other windows in the program.

I'm trying to:

Enter the file name of the selected file into a label. With this, I want to show the file name as it is being played. I want to only show the file name, not the path to it as well.

What I've seen on duplicate questions:

Repeating fixes whereby I can use the following code to pick up the file name with or without the file extension:

label1.Content = Path.GetFileName(media.Source.ToString());

label1.Content = Path.GetFileNameWithoutExtension(media.Source.ToString());

Issue:

I've tried to enter this on my program, but I don't have the "Path" section (I'm not too sure of the actual name of this part of code).

The closest I can get to this is: class System.Windows.Shapes.Path | Draws a series of connected lines and curves.

I don't seem to have another "path" in my VS, so I'm not too sure what to do.

Code (Sorry about the code here, it was a little awkward to copy into the question box)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Microsoft.Win32;
using System.Windows.Threading;

namespace WolfAlbumCatalogue
{
    ///
    /// Interaction logic for MusicPlayer.xaml
    ///
    public partial class MusicPlayer : Window
    {
        private MediaPlayer mediaPlayer = new MediaPlayer();

        AlbumCatalogue albumCatalogue;

        public MusicPlayer(AlbumCatalogue parent)
        {
            InitializeComponent();
            albumCatalogue = parent;

            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "MP3 files (*.mp3)|*.mp3|All files(*.*)|*.*";
            if (openFileDialog.ShowDialog() == true)
                mediaPlayer.Open(new Uri(openFileDialog.FileName));

            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Tick += timer_Tick;
            timer.Tick += miniTimer_Tick;
            timer.Start();

            albumCatalogue.img_musicPlayerWindow.IsEnabled = false;

            lbl_songName.Content = Path
        }

        private void rec_closeHover_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            this.Close();
            albumCatalogue.img_musicPlayerWindow.IsEnabled = true;
        }

        void timer_Tick(object sender, EventArgs e)
        {
            if (mediaPlayer.Source != null)
            {
                lbl_timer.Content = String.Format("{0} / {1}", mediaPlayer.Position.ToString(@"mm\:ss"), mediaPlayer.NaturalDuration.TimeSpan.ToString(@"mm\:ss"));
            }
            else
            {
                lbl_timer.Content = "No file selected...";
            }
        }

        void miniTimer_Tick(object sender, EventArgs e)
        {
            if (mediaPlayer.Source != null)
            {
                lbl_miniTimer.Content = String.Format("{0} / {1}", mediaPlayer.Position.ToString(@"mm\:ss"), mediaPlayer.NaturalDuration.TimeSpan.ToString(@"mm\:ss"));
            }
            else
            {
                lbl_miniTimer.Content = "No file selected...";
            }
        }

        private void btn_play_Click(object sender, RoutedEventArgs e)
        {
            mediaPlayer.Play();
            lbl_play_pause.Content = "Playing...";
            lbl_play_pause.Visibility = Visibility.Visible;
        }

        private void btn_pause_Click(object sender, RoutedEventArgs e)
        {
            mediaPlayer.Pause();
            lbl_play_pause.Content = "Paused.";
            lbl_play_pause.Visibility = Visibility.Visible;
        }

        private void btn_stop_Click(object sender, RoutedEventArgs e)
        {
            mediaPlayer.Stop();
            lbl_play_pause.Visibility = Visibility.Hidden;
        }

        private void rec_titleBar_MouseDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }

        private void rec_windowBkg_MouseDown(object sender, MouseButtonEventArgs e)
        {
        this.DragMove();
        }

        private void rec_btnOpenAudioFile_MouseDown(object sender, MouseButtonEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "MP3 files (*.mp3)|*.mp3|All files(*.*)|*.*";
            if (openFileDialog.ShowDialog() == true)
                mediaPlayer.Open(new Uri(openFileDialog.FileName));

            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Tick += timer_Tick;
            timer.Start();
        }
    }
}

I would copy in the XAML too but I use blend animations and it's way too long for this question. If you need it, please let me know :)

That said, I think that's everything!

Thank you


问:
When to use an object or an array in javascript?
I just found out that Arrays inherit directly from Object in javascript.  I'm finding the difference between an array and an object is fairly minuscule.

How do i know when to use one over the other?

答:
Objects are a good candidate if you have a unique key.

Example Array vs. Object:

```<code>var item = { id: '123', prop1: 456 };

var obj = {}, arr = [];

// add to object
obj[item.id] = item;

// add to array
arr.push(item);

// get from object
var got = obj[item.id];

// get from array
var got;
for(var i = 0; i < arr.length; i++)
    if(arr[i].id == item.id){
        got = arr[i];
        break;
    }
</code>```

As you can see finding an object is much more expensive with an array (loop). Using an object you will not have access to all the array helper methods (sort/push/etc) but you can still iterate an objects' properties using a for...in loop.

Body:
Objects are a good candidate if you have a unique key.

Example Array vs. Object:

var item = { id: '123', prop1: 456 };

var obj = {}, arr = [];

// add to object
obj[item.id] = item;

// add to array
arr.push(item);

// get from object
var got = obj[item.id];

// get from array
var got;
for(var i = 0; i < arr.length; i++)
    if(arr[i].id == item.id){
        got = arr[i];
        break;
    }

As you can see finding an object is much more expensive with an array (loop). Using an object you will not have access to all the array helper methods (sort/push/etc) but you can still iterate an objects' properties using a for...in loop.


问:
How do I loop an if, elif else statement?
I am writing code for a project and I would like some help.

When the user enters something other than male or female, it prints the message "Error! Please enter a valid gender!", but it doesn't rerun the input statement, so it doesn't let them pick a gender. I would like to know how to have the input line rerun again after the user receives the error message. Please let me know how I can do this using Python 3.0!

This is my code:

```<code>Gender = input("Your Gender (Male / Female):")
gender = Gender.lower()
if gender == "male":
  heorshe = "he"
  hisher = "his"
  himher = "him"
  himselfherself = "himself"
  HeShe = "He"
elif gender == "female":
  heorshe = "she"
  hisher = "her"
  himher = "her"
  himselfherself = "herself"
  HeShe = "He"
else:
  print("Error Please enter a valid gender!")
  print('\n')
  gender = False
</code>```

I will appreciate any help given to me!

答:
Encapsulate in a while-loop, then break out of it when you find what you're looking for!</p>

```<code>while(True):
  gender = input("Your Gender (Male / Female):").lower()
  if gender == "male":
    heorshe = "he"
    hisher = "his"
    himher = "him"
    himselfherself = "himself"
    HeShe = "He"
    break
  elif gender == "female":
    heorshe = "she"
    hisher = "her"
    himher = "her"
    himselfherself = "herself"
    HeShe = "He"
    break
  else:
    print("Error Please enter a valid gender!")
    print('\n')
</code>```

Body:
I am writing code for a project and I would like some help.

When the user enters something other than male or female, it prints the message "Error! Please enter a valid gender!", but it doesn't rerun the input statement, so it doesn't let them pick a gender. I would like to know how to have the input line rerun again after the user receives the error message. Please let me know how I can do this using Python 3.0!

This is my code:

Gender = input("Your Gender (Male / Female):")
gender = Gender.lower()
if gender == "male":
  heorshe = "he"
  hisher = "his"
  himher = "him"
  himselfherself = "himself"
  HeShe = "He"
elif gender == "female":
  heorshe = "she"
  hisher = "her"
  himher = "her"
  himselfherself = "herself"
  HeShe = "He"
else:
  print("Error Please enter a valid gender!")
  print('\n')
  gender = False

I will appreciate any help given to me!

Body:
Encapsulate in a while-loop, then break out of it when you find what you're looking for!

while(True):
  gender = input("Your Gender (Male / Female):").lower()
  if gender == "male":
    heorshe = "he"
    hisher = "his"
    himher = "him"
    himselfherself = "himself"
    HeShe = "He"
    break
  elif gender == "female":
    heorshe = "she"
    hisher = "her"
    himher = "her"
    himselfherself = "herself"
    HeShe = "He"
    break
  else:
    print("Error Please enter a valid gender!")
    print('\n')


问:
Azure B2C SignIn Policy Custom Page URI is not called from OWIN
I have set sign-in policy custom page URI in blob storage, but it always go to Microsoft login page. I am using owin and code as follow :

```<code> public void ConfigureAuth(IAppBuilder app)
 {                 app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

 app.UseCookieAuthentication(new CookieAuthenticationOptions());

        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                Authority = authority,
                PostLogoutRedirectUri = postLogoutRedirectUri,
                RedirectUri = postLogoutRedirectUri,
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = context =>
                    {
                        context.HandleResponse();
                        context.Response.Redirect("/Error?message=" + context.Exception.Message);
                        return Task.FromResult(0);
                    }
                }
            });
    }
</code>```

Page is configured and it is working.

Following URL I am using

```<code> <add key="ida:AADInstance" value="https://login.microsoftonline.com/te/{0}/{1}/v2.0/.well-known/openid-configuration" />
</code>```

I using following sample :
     https://github.com/Azure-Samples/active-directory-b2c-dotnet-webapp-and-webapi

Getting following error:

```<code> Response status code does not indicate success: 404 (Not Found).

 Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

 Exception Details: System.Net.Http.HttpRequestException: Response status code does not indicate success: 404 (Not Found).
</code>```

Following is the Microsoft default login screen :

答:
Never mind guys the problem was resolved by updating Microsoft.IdentityModel.Protocol.Extensions to version 1.0.4.4 or later.

Hope this helps anyone who is still struggling with this.

Body:
I have set sign-in policy custom page URI in blob storage, but it always go to Microsoft login page. I am using owin and code as follow :

 public void ConfigureAuth(IAppBuilder app)
 {                 app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

 app.UseCookieAuthentication(new CookieAuthenticationOptions());

        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                Authority = authority,
                PostLogoutRedirectUri = postLogoutRedirectUri,
                RedirectUri = postLogoutRedirectUri,
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = context =>
                    {
                        context.HandleResponse();
                        context.Response.Redirect("/Error?message=" + context.Exception.Message);
                        return Task.FromResult(0);
                    }
                }
            });
    }

Page is configured and it is working.

Following URL I am using

 <add key="ida:AADInstance" value="https://login.microsoftonline.com/te/{0}/{1}/v2.0/.well-known/openid-configuration" />

I using following sample :
     https://github.com/Azure-Samples/active-directory-b2c-dotnet-webapp-and-webapi

Getting following error:

 Response status code does not indicate success: 404 (Not Found).

 Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

 Exception Details: System.Net.Http.HttpRequestException: Response status code does not indicate success: 404 (Not Found).

Following is the Microsoft default login screen :


问:
Append Incremental Number to a Field
I have a field in my Database that stores a product-page.html name for each product in my product table.

The issue I have is the CMS i'm using allows for duplicate products, and when uploading I'm getting duplicate page names for products highlighted. This is caused due to a setting issue in the CMS.

To resolve it...

Is there away to append an incremental value to each record containing the page name of a product to make them all unique?

i.e.

product-page-1.html

product-page-2.html

Etc.

Whereby the value 1, 2 is being created via SQL statement to make all the page names unique

答:
Add a column to your table called page-id or similar.

Modify your INSERT statement as follows:

```<code>DECLARE @NewPageName VARCHAR(MAX) = 'your page name'
DECLARE @NewProductName VARCHAR(MAX) = 'your product name'

DECLARE @NewPageId = CONVERT(VARCHAR(MAX), SELECT ISNULL(MAX(page-id), 0) + 1 FROM your-table WHERE page-name = @NewPageName)

INSERT INTO
    your-table
    (
        product-name
        , page-name
        , page-id
        , ...
    )
    VALUES
    (
        @NewProductName
        , @NewPageName
        , @NewPageId
        , ...
    )
</code>```

Now, you can concatenate page-name and page-id in your code to retrieve the full page name.

```<code>SELECT
    page-name + '-' + CONVERT(VARCHAR(MAX), page-id) + '.html' AS full-page-name
FROM
    your-table
WHERE
    product-name = 'your product name'
</code>```

Note: I am currently guessing what your table and columns are named.

I have requested more information so that I may revisit this answer and supply you with actual code in the future.

Title: Append Incremental Number to a Field

Body:
Add a column to your table called page-id or similar.

Modify your INSERT statement as follows:

DECLARE @NewPageName VARCHAR(MAX) = 'your page name'
DECLARE @NewProductName VARCHAR(MAX) = 'your product name'

DECLARE @NewPageId = CONVERT(VARCHAR(MAX), SELECT ISNULL(MAX(page-id), 0) + 1 FROM your-table WHERE page-name = @NewPageName)

INSERT INTO
    your-table
    (
        product-name
        , page-name
        , page-id
        , ...
    )
    VALUES
    (
        @NewProductName
        , @NewPageName
        , @NewPageId
        , ...
    )

Now, you can concatenate page-name and page-id in your code to retrieve the full page name.

SELECT
    page-name + '-' + CONVERT(VARCHAR(MAX), page-id) + '.html' AS full-page-name
FROM
    your-table
WHERE
    product-name = 'your product name'

Note: I am currently guessing what your table and columns are named.

I have requested more information so that I may revisit this answer and supply you with actual code in the future.


问:
Response Data via URLSessionUploadTask
I am writing simple handler for communication with REST API on server (currently local). Everything goes well so far with downloading and uploading data from/to server.

What I am trying to achieve now is to be able to handle JSON response returned by server after uploading data. This message is something like this:

```<code>{"message":"Record successfully added.","recordID":30}
</code>```

Important is for me the recordID, because I need to assign it to relevant NSManagedObject. I use delegation attitude instead of completionHandler so I would be able to manage progress of the upload. Appropriate delegate class implements these protocols with all methods:

```<code>class ConstructoHTTPHelper:NSObject, URLSessionDelegate, URLSessionDataDelegate, URLSessionTaskDelegate, URLSessionDownloadDelegate, URLSessionStreamDelegate { ... }
</code>```

Here comes the issue because as far as I create upload task with something like this:

```<code>let config = URLSessionConfiguration.default
self.session = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue.main) //URLSession(configuration: config)
var request:URLRequest = URLRequest(url:address)
request.httpMethod = "POST"
let data = // creation of data ...
let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("uploadData")
do {
   try data.write(to: fileURL)
}   catch {
   // handling error
}
self.sessionUploadTask = self.session?.uploadTask(with: request, fromFile: fileURL)
self.sessionUploadTask!.resume()
</code>```

The delegate func for handling data:

```<code>func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {}
</code>```

returned by server is never called.
What is strange to me is that when I use completion Handler like the one below, It prints the JSON well:

```<code>self.sessionUploadTask = self.session?.uploadTask(with: request, from: data, completionHandler: { (data, response, error) in
   print(NSString(data: data!, encoding: String.Encoding.utf8.rawValue)!)
})
</code>```

So it looks to me that uploadTask is limited in this way. Any suggestions?

Thanks

答:
I probably found the answer, just add this to URLSession:dataTask:didReceiveResponse:completionHandler: delegate method.

```<code>completionHandler(URLSession.ResponseDisposition.allow)
</code>```

I found solution in this thread.

Title: Response Data via URLSessionUploadTask

Body:
I am writing simple handler for communication with REST API on server (currently local). Everything goes well so far with downloading and uploading data from/to server.

What I am trying to achieve now is to be able to handle JSON response returned by server after uploading data. This message is something like this:

{"message":"Record successfully added.","recordID":30}

Important is for me the recordID, because I need to assign it to relevant NSManagedObject. I use delegation attitude instead of completionHandler so I would be able to manage progress of the upload. Appropriate delegate class implements these protocols with all methods:

class ConstructoHTTPHelper:NSObject, URLSessionDelegate, URLSessionDataDelegate, URLSessionTaskDelegate, URLSessionDownloadDelegate, URLSessionStreamDelegate { ... }

Here comes the issue because as far as I create upload task with something like this:

let config = URLSessionConfiguration.default
self.session = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue.main) //URLSession(configuration: config)
var request:URLRequest = URLRequest(url:address)
request.httpMethod = "POST"
let data = // creation of data ...
let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("uploadData")
do {
   try data.write(to: fileURL)
}   catch {
   // handling error
}
self.sessionUploadTask = self.session?.uploadTask(with: request, fromFile: fileURL)
self.sessionUploadTask!.resume()

The delegate func for handling data:

func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {}

returned by server is never called.
What is strange to me is that when I use completion Handler like the one below, It prints the JSON well:

self.sessionUploadTask = self.session?.uploadTask(with: request, from: data, completionHandler: { (data, response, error) in
   print(NSString(data: data!, encoding: String.Encoding.utf8.rawValue)!)
})

So it looks to me that uploadTask is limited in this way. Any suggestions?

Thanks

Body:
I probably found the answer, just add this to URLSession:dataTask:didReceiveResponse:completionHandler: delegate method.

completionHandler(URLSession.ResponseDisposition.allow)

I found solution in this thread.


问:
Angular ui-view load slowly
Is there a fadeIn effect for loading your ui-view?

Because sometimes the images are loading a bit slowly.

答:
I just add a simple css class to the global css and apply it to the component. This doesn't require ngAnimate.

```<code>.myapp-fade-in {
  /* make things invisible upon start */
  opacity: 0;
  /* call our keyframe named fadeIn, use animation ease-in and repeat it only 1 time */
  -webkit-animation: fadeIn ease-in 1;
  -moz-animation: fadeIn ease-in 1;
  animation: fadeIn ease-in 1;

  /* this makes sure that after animation is done we remain at the last keyframe value (opacity: 1)*/
  -webkit-animation-fill-mode:forwards;
  -moz-animation-fill-mode:forwards;
  animation-fill-mode:forwards;

  -webkit-animation-duration: 0.2s;
  -moz-animation-duration: 0.2s;
  animation-duration: 0.2s;
}
</code>```

Title: Angular ui-view load slowly

Body:
I just add a simple css class to the global css and apply it to the component. This doesn't require ngAnimate.

.myapp-fade-in {
  /* make things invisible upon start */
  opacity: 0;
  /* call our keyframe named fadeIn, use animation ease-in and repeat it only 1 time */
  -webkit-animation: fadeIn ease-in 1;
  -moz-animation: fadeIn ease-in 1;
  animation: fadeIn ease-in 1;

  /* this makes sure that after animation is done we remain at the last keyframe value (opacity: 1)*/
  -webkit-animation-fill-mode:forwards;
  -moz-animation-fill-mode:forwards;
  animation-fill-mode:forwards;

  -webkit-animation-duration: 0.2s;
  -moz-animation-duration: 0.2s;
  animation-duration: 0.2s;
}


问:
IllegalArgumentException: Jetty ALPN/NPN has not been properly configured
I'm trying to use google vision in google api, however I have the following problem:

jun 07, 2017 8:50:00 AM io.grpc.internal.ChannelExecutor drain
  ADVERTÊNCIA: Runnable threw exception in ChannelExecutor
  java.lang.IllegalArgumentException: Jetty ALPN/NPN has not been
  properly configured.  at
  io.grpc.netty.GrpcSslContexts.selectApplicationProtocolConfig(GrpcSslContexts.java:174)
    at io.grpc.netty.GrpcSslContexts.configure(GrpcSslContexts.java:151)
    at io.grpc.netty.GrpcSslContexts.configure(GrpcSslContexts.java:139)
    at io.grpc.netty.GrpcSslContexts.forClient(GrpcSslContexts.java:109)
    at
  io.grpc.netty.NettyChannelBuilder.createProtocolNegotiatorByType(NettyChannelBuilder.java:335)
    at
  io.grpc.netty.NettyChannelBuilder.createProtocolNegotiator(NettyChannelBuilder.java:308)
    at
  io.grpc.netty.NettyChannelBuilder$NettyTransportFactory$DynamicNettyTransportParams.getProtocolNegotiator(NettyChannelBuilder.java:499)
    at
  io.grpc.netty.NettyChannelBuilder$NettyTransportFactory.newClientTransport(NettyChannelBuilder.java:448)
    at
  io.grpc.internal.CallCredentialsApplyingTransportFactory.newClientTransport(CallCredentialsApplyingTransportFactory.java:61)
    at
  io.grpc.internal.InternalSubchannel.startNewTransport(InternalSubchannel.java:209)
    at
  io.grpc.internal.InternalSubchannel.obtainActiveTransport(InternalSubchannel.java:186)
    at
  io.grpc.internal.ManagedChannelImpl$SubchannelImplImpl.obtainActiveTransport(ManagedChannelImpl.java:806)
    at
  io.grpc.internal.GrpcUtil.getTransportFromPickResult(GrpcUtil.java:568)
    at
  io.grpc.internal.DelayedClientTransport.reprocess(DelayedClientTransport.java:296)
    at
  io.grpc.internal.ManagedChannelImpl$LbHelperImpl$5.run(ManagedChannelImpl.java:724)
    at io.grpc.internal.ChannelExecutor.drain(ChannelExecutor.java:87)
    at
  io.grpc.internal.ManagedChannelImpl$LbHelperImpl.runSerialized(ManagedChannelImpl.java:715)
    at
  io.grpc.internal.ManagedChannelImpl$NameResolverListenerImpl.onUpdate(ManagedChannelImpl.java:752)
    at io.grpc.internal.DnsNameResolver$1.run(DnsNameResolver.java:174)
    at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

I'm trying to run the api's own sample code, below:

```<code>public class QuickstartSample {
    public static void main(String... args) throws Exception {
        // Instantiates a client
        ImageAnnotatorClient vision = ImageAnnotatorClient.create();

        // The path to the image file to annotate
        String fileName = "./resources/wakeupcat.jpg";

        // Reads the image file into memory
        Path path = Paths.get(fileName);
        byte[] data = Files.readAllBytes(path);
        ByteString imgBytes = ByteString.copyFrom(data);

        // Builds the image annotation request
        List<AnnotateImageRequest> requests = new ArrayList<>();
        Image img = Image.newBuilder().setContent(imgBytes).build();
        Feature feat = Feature.newBuilder().setType(Type.LABEL_DETECTION).build();
        AnnotateImageRequest request = AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build();
        requests.add(request);

        // Performs label detection on the image file
        BatchAnnotateImagesResponse response = vision.batchAnnotateImages(requests);
        List<AnnotateImageResponse> responses = response.getResponsesList();

        for (AnnotateImageResponse res : responses) {
            if (res.hasError()) {
                System.out.printf("Error: %s\n", res.getError().getMessage());
                return;
            }

            for (EntityAnnotation annotation : res.getLabelAnnotationsList()) {
                annotation.getAllFields().forEach((k, v) -> System.out.printf("%s : %s\n", k, v.toString()));
            }
        }
    }
}
</code>```

I'm using the following dependencies:

```<code>    <dependency>
        <groupId>com.google.apis</groupId>
        <artifactId>google-api-services-vision</artifactId>
        <version>v1-rev357-1.22.0</version>
    </dependency>
    <dependency>
        <groupId>com.google.cloud</groupId>
        <artifactId>google-cloud-vision</artifactId>
        <version>0.17.2-beta</version>
    </dependency>
</code>```

Has anyone ever had this problem?

答: I've actually discovered that to run the api, you must necessarily be in a web context and also be running the application on a Jetty server</p>

Body:
I'm trying to use google vision in google api, however I have the following problem:

jun 07, 2017 8:50:00 AM io.grpc.internal.ChannelExecutor drain
  ADVERTÊNCIA: Runnable threw exception in ChannelExecutor
  java.lang.IllegalArgumentException: Jetty ALPN/NPN has not been
  properly configured.  at
  io.grpc.netty.GrpcSslContexts.selectApplicationProtocolConfig(GrpcSslContexts.java:174)
    at io.grpc.netty.GrpcSslContexts.configure(GrpcSslContexts.java:151)
    at io.grpc.netty.GrpcSslContexts.configure(GrpcSslContexts.java:139)
    at io.grpc.netty.GrpcSslContexts.forClient(GrpcSslContexts.java:109)
    at
  io.grpc.netty.NettyChannelBuilder.createProtocolNegotiatorByType(NettyChannelBuilder.java:335)
    at
  io.grpc.netty.NettyChannelBuilder.createProtocolNegotiator(NettyChannelBuilder.java:308)
    at
  io.grpc.netty.NettyChannelBuilder$NettyTransportFactory$DynamicNettyTransportParams.getProtocolNegotiator(NettyChannelBuilder.java:499)
    at
  io.grpc.netty.NettyChannelBuilder$NettyTransportFactory.newClientTransport(NettyChannelBuilder.java:448)
    at
  io.grpc.internal.CallCredentialsApplyingTransportFactory.newClientTransport(CallCredentialsApplyingTransportFactory.java:61)
    at
  io.grpc.internal.InternalSubchannel.startNewTransport(InternalSubchannel.java:209)
    at
  io.grpc.internal.InternalSubchannel.obtainActiveTransport(InternalSubchannel.java:186)
    at
  io.grpc.internal.ManagedChannelImpl$SubchannelImplImpl.obtainActiveTransport(ManagedChannelImpl.java:806)
    at
  io.grpc.internal.GrpcUtil.getTransportFromPickResult(GrpcUtil.java:568)
    at
  io.grpc.internal.DelayedClientTransport.reprocess(DelayedClientTransport.java:296)
    at
  io.grpc.internal.ManagedChannelImpl$LbHelperImpl$5.run(ManagedChannelImpl.java:724)
    at io.grpc.internal.ChannelExecutor.drain(ChannelExecutor.java:87)
    at
  io.grpc.internal.ManagedChannelImpl$LbHelperImpl.runSerialized(ManagedChannelImpl.java:715)
    at
  io.grpc.internal.ManagedChannelImpl$NameResolverListenerImpl.onUpdate(ManagedChannelImpl.java:752)
    at io.grpc.internal.DnsNameResolver$1.run(DnsNameResolver.java:174)
    at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

I'm trying to run the api's own sample code, below:

public class QuickstartSample {
    public static void main(String... args) throws Exception {
        // Instantiates a client
        ImageAnnotatorClient vision = ImageAnnotatorClient.create();

        // The path to the image file to annotate
        String fileName = "./resources/wakeupcat.jpg";

        // Reads the image file into memory
        Path path = Paths.get(fileName);
        byte[] data = Files.readAllBytes(path);
        ByteString imgBytes = ByteString.copyFrom(data);

        // Builds the image annotation request
        List<AnnotateImageRequest> requests = new ArrayList<>();
        Image img = Image.newBuilder().setContent(imgBytes).build();
        Feature feat = Feature.newBuilder().setType(Type.LABEL_DETECTION).build();
        AnnotateImageRequest request = AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build();
        requests.add(request);

        // Performs label detection on the image file
        BatchAnnotateImagesResponse response = vision.batchAnnotateImages(requests);
        List<AnnotateImageResponse> responses = response.getResponsesList();

        for (AnnotateImageResponse res : responses) {
            if (res.hasError()) {
                System.out.printf("Error: %s\n", res.getError().getMessage());
                return;
            }

            for (EntityAnnotation annotation : res.getLabelAnnotationsList()) {
                annotation.getAllFields().forEach((k, v) -> System.out.printf("%s : %s\n", k, v.toString()));
            }
        }
    }
}

I'm using the following dependencies:

    <dependency>
        <groupId>com.google.apis</groupId>
        <artifactId>google-api-services-vision</artifactId>
        <version>v1-rev357-1.22.0</version>
    </dependency>
    <dependency>
        <groupId>com.google.cloud</groupId>
        <artifactId>google-cloud-vision</artifactId>
        <version>0.17.2-beta</version>
    </dependency>

Has anyone ever had this problem?


问:
Different count of documents in elastic search for the same query
I have incomprehensible behavior with elasticsearch (I use elasticsearch 5.2). I have index with ~5m documents. I try to search something. For example, I use this query:

```<code>{
    "query": {
        "match_all": {}
    }
}
</code>```

If I execute query several times, I get the different count of documents in hits.total. The different is 1 document (first time I have 5032511 docs, another time: 5032510)

The same situation, if I execute count query (first time I have 5032511 docs, another time: 5032510)

Does anybody know why this happens? And what I need to do to get the same count each time, when I execute query?

P.S. I use number_of_shards: 5, number_of_replicas: 1 for this index. Maybe this important to solve the problem.

答: If this is active index and there's some clients writing to it, most probable rootcase is long index refresh (which is kinda often-used optimisation for large indices). Try executing refresh query before counting. But beware, it can be sort of expensive for high-loaded indices.</p>

Body:
I have incomprehensible behavior with elasticsearch (I use elasticsearch 5.2). I have index with ~5m documents. I try to search something. For example, I use this query:

{
    "query": {
        "match_all": {}
    }
}

If I execute query several times, I get the different count of documents in hits.total. The different is 1 document (first time I have 5032511 docs, another time: 5032510)

The same situation, if I execute count query (first time I have 5032511 docs, another time: 5032510)

Does anybody know why this happens? And what I need to do to get the same count each time, when I execute query?

P.S. I use number_of_shards: 5, number_of_replicas: 1 for this index. Maybe this important to solve the problem.