问:
Image stretched when I capture image and save to SD card in Android
```<code>BitmapFactory.Options opts = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opts);
bitmap = Bitmap.createScaledBitmap(bitmap, 150, 50, false);
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int newWidth = 150;
int newHeight = 50;

// calculate the scale - in this case = 0.4f
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;

// createa matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// rotate the Bitmap
matrix.postRotate(-90);
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
        width, height, matrix, true);
//      HomePage.image.setImageBitmap(resizedBitmap);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
resizedBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();

Intent in1 = new Intent(CameraView.this, ImageDisplay.class);
in1.putExtra("picture",byteArray);
startActivity(in1);
</code>```

This is my code. I am unable to set image because image becomes stretched. It's not coming clear image full screen. Where am I doing wrong?

My image come like this we have fix it it should not stretched.

答:
I have a written a code  to pick image from gallery or capture image from camera  you can use this to achieve what you want and you will get the file path of capture from camera  or picked from gallery  image file path  in onactivityforResult </p>

```<code>private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;

private static final int CROP_FROM_CAMERA = 2;
private static final int PICK_FROM_FILE = 3;

public static final int camPermissionRequestCode=6;
public static final int galleryPermissionRequestCode=4;

private Uri imageUri;

private File profilePicPicked;

@Override
public void onClick(View v) {

    int id=v.getId();

    switch (id){

        case R.id.camera:
            if (Build.VERSION.SDK_INT >= 23) {
                //do your check here

                isStoragePermissionGranted(camPermissionRequestCode);

            } else {

                captureImage();

            }

            break;
        case R.id.upload_image:

            if (Build.VERSION.SDK_INT >= 23) {
                //do your check here
                isStoragePermissionGranted(galleryPermissionRequestCode);

            } else {

                pickFromGallery();

            }

            break;

    }

}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub

    if (resultCode != Activity.RESULT_OK)
        return;

    switch (requestCode) {
        case CAMERA_CAPTURE_IMAGE_REQUEST_CODE:
            /**
             * After taking a picture, do the crop
             */

            File file2 = handleImageUri(imageUri,getContext());

            try {

                ExifInterface ei = new ExifInterface(file2.getAbsolutePath());
                int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                        ExifInterface.ORIENTATION_UNDEFINED);

                switch (orientation) {
                    case ExifInterface.ORIENTATION_ROTATE_90:
                        file2=rotateImage(file2, 90);
                       /* Toast.makeText(getActivity(),"90",Toast.LENGTH_SHORT).show();*/
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_180:
                        file2=rotateImage(file2, 180);
                       /* Toast.makeText(getActivity(),"180",Toast.LENGTH_SHORT).show();*/
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_270:
                        file2=rotateImage(file2, 270);
                       /* Toast.makeText(getActivity(),"270",Toast.LENGTH_SHORT).show();*/
                        break;
                    case ExifInterface.ORIENTATION_NORMAL:
                        /*Toast.makeText(getActivity(),"default",Toast.LENGTH_SHORT).show();*/
                    default:
                        break;

                }

            }catch (Exception e){

                e.printStackTrace();
            }

            profilePicPicked= file2;

            break;

        case PICK_FROM_FILE:
            /**
             * After selecting image from files, save the selected path
             */

            /*Toast.makeText(getContext(), "Image Taken", Toast.LENGTH_LONG).show();*/
            imageUri = data.getData();

            //iv_post.setImageURI(fileUri);
            File fileGAllr = getRealPathFromURIForGallery(getActivity(),imageUri);

            profilePicPicked=fileGAllr;

            // new Updata().execute("");
            // btn_gallery.setVisibility(View.GONE);

            break;

        case CROP_FROM_CAMERA:

            break;

    }

}

public static File getRealPathFromURIForGallery(Context context, Uri uri) {
    File file = null;
    try {

        String extension="";
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = context.getContentResolver().query(uri, filePathColumn, null, null, null);
        if (cursor.moveToFirst()) {
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String filePath = cursor.getString(columnIndex);
            extension= filePath.substring(filePath.lastIndexOf("."));
            System.out.print("");
        }
        cursor.close();

        InputStream input = null;
        input = context.getContentResolver().openInputStream(uri);

        if (input == null) {
            return null;
        }
        file = new File(context.getCacheDir(), System.currentTimeMillis()+"_Photo"+extension);
        OutputStream output = new FileOutputStream(file);
        try {
            byte[] buffer = new byte[4 * 1024];
            int read;
            while ((read = input.read(buffer)) != -1) {
                output.write(buffer, 0, read);
            }
            output.flush();
        } finally {
            output.close();
            input.close();
        }
    } catch (IOException e) {
        Log.d("Error", e.toString());
    }
    return file;
}

public File  rotateImage(File f, float angle) {

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
    Bitmap source = BitmapFactory.decodeFile(f.getAbsolutePath(), options);
    Matrix matrix = new Matrix();
    matrix.postRotate(angle);

    Bitmap finalBm= Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);

    File editedFile=getOutputMediaFile(MEDIA_TYPE_IMAGE);
    FileOutputStream out = null;
    try {
        out = new FileOutputStream(editedFile);
        finalBm.compress(Bitmap.CompressFormat.JPEG, 100, out); // bmp is your Bitmap instance
        // PNG is a lossless format, the compression factor (100) is ignored
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    f.delete();

    return editedFile;
}

public static File handleImageUri(Uri uri, Context context) {
    Pattern pattern = Pattern.compile("(content://media/.*\\d)");
    Matcher matcher = pattern.matcher(uri.getPath());
    if (matcher.find()) {
        return getRealPathFromURI(context, uri);
    } else {
        return new File(uri.getPath());
    }
}

public static File getRealPathFromURI(Context context, Uri uri) {
    File file = null;
    try {
        InputStream input = null;
        input = context.getContentResolver().openInputStream(uri);

        if (input == null) {
            return null;
        }
        file = new File(context.getCacheDir(), System.currentTimeMillis()+"Photo.png");
        OutputStream output = new FileOutputStream(file);
        try {
            byte[] buffer = new byte[4 * 1024];
            int read;
            while ((read = input.read(buffer)) != -1) {
                output.write(buffer, 0, read);
            }
            output.flush();
        } finally {
            output.close();
            input.close();
        }
    } catch (IOException e) {
        Log.d("Error", e.toString());
    }
    return file;
}

public  boolean isStoragePermissionGranted(int requsetCode) {
    if (Build.VERSION.SDK_INT >= 23) {
        if (ContextCompat.checkSelfPermission(getActivity(),android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {

            if(requsetCode==camPermissionRequestCode){

                captureImage();
            }else{

                pickFromGallery();
            }
            return true;
        } else {

            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requsetCode);
            return false;
        }
    }
    else { //permission is automatically granted on sdk<23 upon installation

        if(requsetCode==camPermissionRequestCode){

            captureImage();
        }else{

            pickFromGallery();
        }
        return true;
    }

}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(grantResults[0]== PackageManager.PERMISSION_GRANTED){

        if(requestCode==camPermissionRequestCode){

            captureImage();
        }else if(requestCode==galleryPermissionRequestCode){

            pickFromGallery();
        }
        //resume tasks needing this permission
    }
}

private void captureImage() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    imageUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

    // start the image capture Intent
    startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}

private void pickFromGallery(){

    Intent i = new Intent(
            Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(i, PICK_FROM_FILE);
}

public Uri getOutputMediaFileUri(int type) {
    return Uri.fromFile(getOutputMediaFile(type));
}

private File getOutputMediaFile(int type) {
    // TODO Auto-generated method stub
    // External sdcard location
    File mediaStorageDir = new File(
            Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            "marcopolo");

    // Create the storage directory if it does not exist
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {

            return null;
        }
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
            Locale.getDefault()).format(new Date());
    File mediaFile;
    if (type == MEDIA_TYPE_IMAGE) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_" + timeStamp + ".jpg");
    } else {
        return null;
    }

    return mediaFile;
}
</code>```

Body:
BitmapFactory.Options opts = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opts);
bitmap = Bitmap.createScaledBitmap(bitmap, 150, 50, false);
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int newWidth = 150;
int newHeight = 50;

// calculate the scale - in this case = 0.4f
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;

// createa matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// rotate the Bitmap
matrix.postRotate(-90);
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
        width, height, matrix, true);
//      HomePage.image.setImageBitmap(resizedBitmap);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
resizedBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();

Intent in1 = new Intent(CameraView.this, ImageDisplay.class);
in1.putExtra("picture",byteArray);
startActivity(in1);

This is my code. I am unable to set image because image becomes stretched. It's not coming clear image full screen. Where am I doing wrong?

My image come like this we have fix it it should not stretched.

Body:
I have a written a code  to pick image from gallery or capture image from camera  you can use this to achieve what you want and you will get the file path of capture from camera  or picked from gallery  image file path  in onactivityforResult

private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;

private static final int CROP_FROM_CAMERA = 2;
private static final int PICK_FROM_FILE = 3;

public static final int camPermissionRequestCode=6;
public static final int galleryPermissionRequestCode=4;

private Uri imageUri;

private File profilePicPicked;

@Override
public void onClick(View v) {

    int id=v.getId();

    switch (id){

        case R.id.camera:
            if (Build.VERSION.SDK_INT >= 23) {
                //do your check here

                isStoragePermissionGranted(camPermissionRequestCode);

            } else {

                captureImage();

            }

            break;
        case R.id.upload_image:

            if (Build.VERSION.SDK_INT >= 23) {
                //do your check here
                isStoragePermissionGranted(galleryPermissionRequestCode);

            } else {

                pickFromGallery();

            }

            break;

    }

}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub

    if (resultCode != Activity.RESULT_OK)
        return;

    switch (requestCode) {
        case CAMERA_CAPTURE_IMAGE_REQUEST_CODE:
            /**
             * After taking a picture, do the crop
             */

            File file2 = handleImageUri(imageUri,getContext());

            try {

                ExifInterface ei = new ExifInterface(file2.getAbsolutePath());
                int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                        ExifInterface.ORIENTATION_UNDEFINED);

                switch (orientation) {
                    case ExifInterface.ORIENTATION_ROTATE_90:
                        file2=rotateImage(file2, 90);
                       /* Toast.makeText(getActivity(),"90",Toast.LENGTH_SHORT).show();*/
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_180:
                        file2=rotateImage(file2, 180);
                       /* Toast.makeText(getActivity(),"180",Toast.LENGTH_SHORT).show();*/
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_270:
                        file2=rotateImage(file2, 270);
                       /* Toast.makeText(getActivity(),"270",Toast.LENGTH_SHORT).show();*/
                        break;
                    case ExifInterface.ORIENTATION_NORMAL:
                        /*Toast.makeText(getActivity(),"default",Toast.LENGTH_SHORT).show();*/
                    default:
                        break;

                }

            }catch (Exception e){

                e.printStackTrace();
            }

            profilePicPicked= file2;

            break;

        case PICK_FROM_FILE:
            /**
             * After selecting image from files, save the selected path
             */

            /*Toast.makeText(getContext(), "Image Taken", Toast.LENGTH_LONG).show();*/
            imageUri = data.getData();

            //iv_post.setImageURI(fileUri);
            File fileGAllr = getRealPathFromURIForGallery(getActivity(),imageUri);

            profilePicPicked=fileGAllr;

            // new Updata().execute("");
            // btn_gallery.setVisibility(View.GONE);

            break;

        case CROP_FROM_CAMERA:

            break;

    }

}

public static File getRealPathFromURIForGallery(Context context, Uri uri) {
    File file = null;
    try {

        String extension="";
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = context.getContentResolver().query(uri, filePathColumn, null, null, null);
        if (cursor.moveToFirst()) {
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String filePath = cursor.getString(columnIndex);
            extension= filePath.substring(filePath.lastIndexOf("."));
            System.out.print("");
        }
        cursor.close();

        InputStream input = null;
        input = context.getContentResolver().openInputStream(uri);

        if (input == null) {
            return null;
        }
        file = new File(context.getCacheDir(), System.currentTimeMillis()+"_Photo"+extension);
        OutputStream output = new FileOutputStream(file);
        try {
            byte[] buffer = new byte[4 * 1024];
            int read;
            while ((read = input.read(buffer)) != -1) {
                output.write(buffer, 0, read);
            }
            output.flush();
        } finally {
            output.close();
            input.close();
        }
    } catch (IOException e) {
        Log.d("Error", e.toString());
    }
    return file;
}

public File  rotateImage(File f, float angle) {

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
    Bitmap source = BitmapFactory.decodeFile(f.getAbsolutePath(), options);
    Matrix matrix = new Matrix();
    matrix.postRotate(angle);

    Bitmap finalBm= Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);

    File editedFile=getOutputMediaFile(MEDIA_TYPE_IMAGE);
    FileOutputStream out = null;
    try {
        out = new FileOutputStream(editedFile);
        finalBm.compress(Bitmap.CompressFormat.JPEG, 100, out); // bmp is your Bitmap instance
        // PNG is a lossless format, the compression factor (100) is ignored
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    f.delete();

    return editedFile;
}

public static File handleImageUri(Uri uri, Context context) {
    Pattern pattern = Pattern.compile("(content://media/.*\\d)");
    Matcher matcher = pattern.matcher(uri.getPath());
    if (matcher.find()) {
        return getRealPathFromURI(context, uri);
    } else {
        return new File(uri.getPath());
    }
}

public static File getRealPathFromURI(Context context, Uri uri) {
    File file = null;
    try {
        InputStream input = null;
        input = context.getContentResolver().openInputStream(uri);

        if (input == null) {
            return null;
        }
        file = new File(context.getCacheDir(), System.currentTimeMillis()+"Photo.png");
        OutputStream output = new FileOutputStream(file);
        try {
            byte[] buffer = new byte[4 * 1024];
            int read;
            while ((read = input.read(buffer)) != -1) {
                output.write(buffer, 0, read);
            }
            output.flush();
        } finally {
            output.close();
            input.close();
        }
    } catch (IOException e) {
        Log.d("Error", e.toString());
    }
    return file;
}

public  boolean isStoragePermissionGranted(int requsetCode) {
    if (Build.VERSION.SDK_INT >= 23) {
        if (ContextCompat.checkSelfPermission(getActivity(),android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {

            if(requsetCode==camPermissionRequestCode){

                captureImage();
            }else{

                pickFromGallery();
            }
            return true;
        } else {

            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requsetCode);
            return false;
        }
    }
    else { //permission is automatically granted on sdk<23 upon installation

        if(requsetCode==camPermissionRequestCode){

            captureImage();
        }else{

            pickFromGallery();
        }
        return true;
    }

}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(grantResults[0]== PackageManager.PERMISSION_GRANTED){

        if(requestCode==camPermissionRequestCode){

            captureImage();
        }else if(requestCode==galleryPermissionRequestCode){

            pickFromGallery();
        }
        //resume tasks needing this permission
    }
}

private void captureImage() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    imageUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

    // start the image capture Intent
    startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}

private void pickFromGallery(){

    Intent i = new Intent(
            Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(i, PICK_FROM_FILE);
}

public Uri getOutputMediaFileUri(int type) {
    return Uri.fromFile(getOutputMediaFile(type));
}

private File getOutputMediaFile(int type) {
    // TODO Auto-generated method stub
    // External sdcard location
    File mediaStorageDir = new File(
            Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            "marcopolo");

    // Create the storage directory if it does not exist
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {

            return null;
        }
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
            Locale.getDefault()).format(new Date());
    File mediaFile;
    if (type == MEDIA_TYPE_IMAGE) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_" + timeStamp + ".jpg");
    } else {
        return null;
    }

    return mediaFile;
}


来源: stackexchange

问:
Regarding decimal in javascript
When i am writing 11.00 it is displaying 11.00.00 otherwise its working fine on rest</p>

```<code>if(pos == -1)
{
    document.getElementById("printCheckAmount").textContent = "$" + checkObj.checkAmount + ".00";
}
else
{
    var integer = enterCheckAmount.substring(0,pos);
    var decimals = enterCheckAmount.substring(pos+1);
    while(decimals.length<2) decimals=decimals+'0';
    enterCheckAmount = integer + '.' + decimals;
    document.getElementById("printCheckAmount").textContent = "$" + checkObj.checkAmount;
}
</code>```

答:
JavaScript doesn't have a variable type for decimal numbers. It has only Number. If you want to display an integer as a decimal number with two zeros after the decimal point you can use the method toFixed.

Here is an example:

```<code>var myNumber = 11;
var myDecimalNumber = myNumber.toFixed(2);
console.log(myDecimalNumber) // will output 11.00
</code>```

Thus there is no need to concatenate strings and add ".00" manually to your number.

Beyond this you can use the methods parseInt and parseFloat. Let's say you have a variable of type string with the value "11 pieces". You can get the integer with this line of code:

```<code>var myString = "11 pieces";
var myInteger = parseInt(myString, 10);
console.log(myInteger); // will output 11
</code>```

If you have something similar like this, you are better off with this methods instead of cuting substrings.

I wish you a lot of success in refactoring your code and a warm welcome to the StackOverflow community.

ContentLicense: CC BY-SA 3.0

Title: Regarding decimal in javascript

Body:
When i am writing 11.00 it is displaying 11.00.00 otherwise its working fine on rest

if(pos == -1)
{
    document.getElementById("printCheckAmount").textContent = "$" + checkObj.checkAmount + ".00";
}
else
{
    var integer = enterCheckAmount.substring(0,pos);
    var decimals = enterCheckAmount.substring(pos+1);
    while(decimals.length<2) decimals=decimals+'0';
    enterCheckAmount = integer + '.' + decimals;
    document.getElementById("printCheckAmount").textContent = "$" + checkObj.checkAmount;
}

Body:
JavaScript doesn't have a variable type for decimal numbers. It has only Number. If you want to display an integer as a decimal number with two zeros after the decimal point you can use the method toFixed.

Here is an example:

var myNumber = 11;
var myDecimalNumber = myNumber.toFixed(2);
console.log(myDecimalNumber) // will output 11.00

Thus there is no need to concatenate strings and add ".00" manually to your number.

Beyond this you can use the methods parseInt and parseFloat. Let's say you have a variable of type string with the value "11 pieces". You can get the integer with this line of code:

var myString = "11 pieces";
var myInteger = parseInt(myString, 10);
console.log(myInteger); // will output 11

If you have something similar like this, you are better off with this methods instead of cuting substrings.

I wish you a lot of success in refactoring your code and a warm welcome to the StackOverflow community.


问:
jQuery, converting from a .POST to .AJAX with a method?
I have the following:

```<code>    $.post(this.href, { _method: 'delete' }, null, "script");
</code>```

How can I convert that to a:

```<code>$.ajax({
    type: "POST",
    url: ,
    data: ,
    beforeSend: function() {
    },
    success: function() {
</code>```

I'm not use how to deal with URL or how to add the _method: 'delete' where does that go with .ajax?

thanks

答:
documentation of $.post</p>

```<code>$.ajax({
  type: 'POST',
  url: url,
  data: data,
  success: success
  dataType: dataType
});
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have the following:

    $.post(this.href, { _method: 'delete' }, null, "script");

How can I convert that to a:

$.ajax({
    type: "POST",
    url: ,
    data: ,
    beforeSend: function() {
    },
    success: function() {

I'm not use how to deal with URL or how to add the _method: 'delete' where does that go with .ajax?

thanks

Body:
documentation of $.post

$.ajax({
  type: 'POST',
  url: url,
  data: data,
  success: success
  dataType: dataType
});


答:
you may use foreach or array_map with this as follows :

```<code>$arrays = [
    ['change' => 'c876e544-eca5-4ce1-8563-ed48ac74ebc2'],
    ['change' => 'c876e544-eca5-4ce1-8563-ed48ac74ebc2'],
    ['change' => 'fa37e5a4-3b5a-4f7d-915e-4807caa5949e'],
    ['change' => 'fa37e5a4-3b5a-4f7d-915e-4807caa5949e'],
    ['change' => '9a356688-d08b-42ee-b26d-19d76bf6543b'],
    ['change' => '8a356688-d08b-42ee-b26d-19d76bf6543b'],
    ['change' => '701a896a-7d19-4cdd-80a4-f9ca7042945b'],
    ['change' => '601a896a-7d19-4cdd-80a4-f9ca7042945b'],
];

$list = [];
foreach ($arrays as $array) {
    $list[$array['change']][] = $array;
}

print_r(array_values($list));

// if you would like to use array_map instead

$list = [];
array_map(function ($array) use (&$list) {
    $list[$array['change']][] = $array;
}, $arrays);

print_r(array_values($list));
</code>```

live demo : https://3v4l.org/1JO58

Title: PHP compare element values and push to array

Body:
I need to compare elements in array which have same elment value ex. $array[0]['change'] == $array[1]['change'] and if it true than make array push.

I have array like this

[
    (int) 0 => [
        'id' => (int) 2,
        'uuid' => 'c876e544-eca5-4ce1-8563-ed48ac74ebc2',
        'change' => 'c876e544-eca5-4ce1-8563-ed48ac74ebc2',
        'company_id' => (int) 18
    ],
    (int) 1 => [
        'id' => (int) 3,
        'uuid' => 'c3f388bc-9efb-4c72-b50e-3b6a9075d919',
        'change' => 'c876e544-eca5-4ce1-8563-ed48ac74ebc2',
        'company_id' => (int) 11
    ],
    (int) 2 => [
        'id' => (int) 4,
        'uuid' => 'fa37e5a4-3b5a-4f7d-915e-4807caa5949e',
        'change' => 'fa37e5a4-3b5a-4f7d-915e-4807caa5949e',
        'company_id' => (int) 17
    ],
    (int) 3 => [
        'id' => (int) 5,
        'uuid' => '52732822-11a9-4c00-8685-2493b88983f8',
        'change' => 'fa37e5a4-3b5a-4f7d-915e-4807caa5949e',
        'company_id' => (int) 19
    ],
    (int) 4 => [
        'id' => (int) 6,
        'uuid' => '9a356688-d08b-42ee-b26d-19d76bf6543b',
        'change' => '9a356688-d08b-42ee-b26d-19d76bf6543b',
        'company_id' => (int) 10
    ],
    (int) 5 => [
        'id' => (int) 7,
        'uuid' => '8dbe1a81-d722-4261-9b13-ef0b68cbb759',
        'change' => '8a356688-d08b-42ee-b26d-19d76bf6543b',
        'company_id' => (int) 18
    ],
    (int) 6 => [
        'id' => (int) 8,
        'uuid' => '701a896a-7d19-4cdd-80a4-f9ca7042945b',
        'change' => '701a896a-7d19-4cdd-80a4-f9ca7042945b',
        'company_id' => (int) 19
    ],
    (int) 7 => [
        'id' => (int) 9,
        'uuid' => '64e146bf-5d76-483f-992c-274cde1202ce',
        'change' => '601a896a-7d19-4cdd-80a4-f9ca7042945b',
        'company_id' => (int) 20
    ]
]

I need to get result like this

[
    (int) 0 => [
        (int) 0 => [
            'id' => (int) 2,
            'uuid' => 'c876e544-eca5-4ce1-8563-ed48ac74ebc2',
            'change' => 'c876e544-eca5-4ce1-8563-ed48ac74ebc2',
            'company_id' => (int) 18
        ],
        (int) 1 => [
            'id' => (int) 3,
            'uuid' => 'c3f388bc-9efb-4c72-b50e-3b6a9075d919',
            'change' => 'c876e544-eca5-4ce1-8563-ed48ac74ebc2',
            'company_id' => (int) 18
        ],
    ],
    (int) 1 => [
        (int) 0 => [
            'id' => (int) 4,
            'uuid' => 'fa37e5a4-3b5a-4f7d-915e-4807caa5949e',
            'change' => 'fa37e5a4-3b5a-4f7d-915e-4807caa5949e',
            'company_id' => (int) 18
        ],
        (int) 1 => [
            'id' => (int) 5,
            'uuid' => '52732822-11a9-4c00-8685-2493b88983f8',
            'change' => 'fa37e5a4-3b5a-4f7d-915e-4807caa5949e',
            'company_id' => (int) 18
        ],
    ],
    (int) 2 => [
        'id' => (int) 6,
        'uuid' => '9a356688-d08b-42ee-b26d-19d76bf6543b',
        'change' => '9a356688-d08b-42ee-b26d-19d76bf6543b',
        'company_id' => (int) 18
    ],
    (int) 3 => [
        'id' => (int) 7,
        'uuid' => '8dbe1a81-d722-4261-9b13-ef0b68cbb759',
        'change' => '8a356688-d08b-42ee-b26d-19d76bf6543b',
        'company_id' => (int) 18
    ],
    .
    .
    .
]

I have tried to make 2 arrays one with same values and another with different values, than make merge but the result is not as I want... and I hope so that there is "nicer" solution (maybe more readable logic).

    $exchange_array = [];
    $item_array = [];
    foreach ($order->items as $item) {
      foreach ($order->items as $exchange) {
        if (
          isset($item->change) && isset($exchange->change) &&
          $item->change == $exchange->change &&
          $item->id != $exchange->id
        ) {
          $exchange_array[] = $exchange;
        }
        if (
          !isset($item->change) && !isset($exchange->change) &&
          $item->id != $exchange->id
        ) {
          $item_array[] = $exchange;
        }

      }
    }

    $item = array_merge($exchange_array,$item_array);

Thank you!

Body:
you may use foreach or array_map with this as follows :

$arrays = [
    ['change' => 'c876e544-eca5-4ce1-8563-ed48ac74ebc2'],
    ['change' => 'c876e544-eca5-4ce1-8563-ed48ac74ebc2'],
    ['change' => 'fa37e5a4-3b5a-4f7d-915e-4807caa5949e'],
    ['change' => 'fa37e5a4-3b5a-4f7d-915e-4807caa5949e'],
    ['change' => '9a356688-d08b-42ee-b26d-19d76bf6543b'],
    ['change' => '8a356688-d08b-42ee-b26d-19d76bf6543b'],
    ['change' => '701a896a-7d19-4cdd-80a4-f9ca7042945b'],
    ['change' => '601a896a-7d19-4cdd-80a4-f9ca7042945b'],
];

$list = [];
foreach ($arrays as $array) {
    $list[$array['change']][] = $array;
}

print_r(array_values($list));

// if you would like to use array_map instead

$list = [];
array_map(function ($array) use (&$list) {
    $list[$array['change']][] = $array;
}, $arrays);

print_r(array_values($list));

live demo : https://3v4l.org/1JO58


问:
l have NaN which are not NaN in my CSV file due to comma in a column considered as delimiter which is not
l have a strange scenario where non NaN values are represented by #####  but when l click on the cell of #### l get the value. However when l manipulate my data l got the following error :

```<code>  img_charac=img[int(coords[2]):int(coords[3]),int(coords[0]):int(coords[1])]
ValueError: cannot convert float NaN to integer
</code>```

Because it reads some cell as NaN

how can l avoid that ?
Here is my csv file

in the following picture look at te line 139 cell C when l click on that cell l get the real value on the top right corner

l increased the width of the column l don't have any #### in my csv file.
However when l read my csv file as follow :

```<code>npa=np.genfromtxt(path_csv+"char.csv", delimiter=',',skip_header=1,usecols=(2,3,4,5))

npa[:280]
array([[   38.,   104.,  2456.,  2492.],
       [   40.,   102.,  2442.,  2448.],
       [   40.,   100.,  2402.,  2410.],
       ...,
       [ 1473.,  1482.,   153.,   177.],
       [   nan,  1491.,  1494.,   172.],
       [ 1508.,  1517.,   159.,   177.]])
</code>```

l get strangely one NaN value (npa[278])

```<code>[   nan,  1491.,  1494.,   172.]
</code>```

l noticed  in this value it is not reading the correct column.
the entire line is as follow  :

```<code>',' 1491    1494    172 181
</code>```

rather writing :
 [ 1491.,  1494.,   172., 181.]
it writes :

```<code>[   nan,  1491.,  1494.,   172.]
</code>```

which means it reads the first column which is a char (',') and left the last column.
l noticed that for each row with a char ',' for the rest it's ok

here how l read my csv :

```<code>npa=np.genfromtxt(path_csv+"char.csv", delimiter=',',skip_header=1,usecols=(2,3,4,5))
</code>```

l have  delimiter=',' and in the first column l have some char which are ','
the question is updated to

```<code>http://stackoverflow.com/questions/43093100/considering-comma-in-a-cell-column-as-delimiter-but-its-not-how-to-differentia
</code>```

thank you

答: This is an Excel question, and your problem happens because Excel has no space to display the value. Increase the column width of C and you'll be fine.</p>

Body:
l have a strange scenario where non NaN values are represented by #####  but when l click on the cell of #### l get the value. However when l manipulate my data l got the following error :

  img_charac=img[int(coords[2]):int(coords[3]),int(coords[0]):int(coords[1])]
ValueError: cannot convert float NaN to integer

Because it reads some cell as NaN

how can l avoid that ?
Here is my csv file

in the following picture look at te line 139 cell C when l click on that cell l get the real value on the top right corner

l increased the width of the column l don't have any #### in my csv file.
However when l read my csv file as follow :

npa=np.genfromtxt(path_csv+"char.csv", delimiter=',',skip_header=1,usecols=(2,3,4,5))

npa[:280]
array([[   38.,   104.,  2456.,  2492.],
       [   40.,   102.,  2442.,  2448.],
       [   40.,   100.,  2402.,  2410.],
       ...,
       [ 1473.,  1482.,   153.,   177.],
       [   nan,  1491.,  1494.,   172.],
       [ 1508.,  1517.,   159.,   177.]])

l get strangely one NaN value (npa[278])

[   nan,  1491.,  1494.,   172.]

l noticed  in this value it is not reading the correct column.
the entire line is as follow  :

',' 1491    1494    172 181

rather writing :
 [ 1491.,  1494.,   172., 181.]
it writes :

[   nan,  1491.,  1494.,   172.]

which means it reads the first column which is a char (',') and left the last column.
l noticed that for each row with a char ',' for the rest it's ok

here how l read my csv :

npa=np.genfromtxt(path_csv+"char.csv", delimiter=',',skip_header=1,usecols=(2,3,4,5))

l have  delimiter=',' and in the first column l have some char which are ','
the question is updated to

http://stackoverflow.com/questions/43093100/considering-comma-in-a-cell-column-as-delimiter-but-its-not-how-to-differentia

thank you


问:
Redirects in PHP website not working properly
I have written htaccess file. I want to redirect https://example.com/index.php?route=product/category&path=1 to https://example.com/fashion.

My htaccess is

```<code>RewriteEngine On
RewriteRule ^([^?]*) index.php?_route_=$1 [L,QSA]
</code>```

But it is not redirecting to the link I have shown

答:
You may use something like this. I hope this will help you a lot. And if not work visit https://github.com/aice09/htaccess/blob/master/redirects/.htaccess</p>

```<code>RewriteEngine On
RewriteRule ^/?category/([^/d]+)/?$ index.php?route=$1 [L,QSA]
</code>```

Body:
I have written htaccess file. I want to redirect https://example.com/index.php?route=product/category&path=1 to https://example.com/fashion.

My htaccess is

RewriteEngine On
RewriteRule ^([^?]*) index.php?_route_=$1 [L,QSA]

But it is not redirecting to the link I have shown

Body:
You may use something like this. I hope this will help you a lot. And if not work visit https://github.com/aice09/htaccess/blob/master/redirects/.htaccess

RewriteEngine On
RewriteRule ^/?category/([^/d]+)/?$ index.php?route=$1 [L,QSA]


问:
Android activity and fragment life cycle - do I need to use all methods in my code?
Android activity and fragment lifecycles have many stages (onCreate(), onStart(), onResume(), onPause(), onStop(), onDestroy(), etc). I have been coding in Android Studio for a few months now and there're many times where I haven't used all of lifecycle methods. </p>

<p>My question is that do you need to use all of the lifecycle methods of a fragment or an activity to write a good code? Will it cause crashes otherwise? </p>

答: Not all, only methods you thing is essential for your task. see docs on Activity's lifecycle: https://developer.android.com/reference/android/app/Activity.html</p>

Body:
Android activity and fragment lifecycles have many stages (onCreate(), onStart(), onResume(), onPause(), onStop(), onDestroy(), etc). I have been coding in Android Studio for a few months now and there're many times where I haven't used all of lifecycle methods.

My question is that do you need to use all of the lifecycle methods of a fragment or an activity to write a good code? Will it cause crashes otherwise?


问:
Calculating the difference between dates not working and giving an huge error
Hi I'm making an online coupon system for mobile devices. The coupons are for a limited time active and I have to do a check on the coupons. I use date(d/m/Y  H:i:s) for just showing the date and time, and I also have a expire date which is a just a string that I later convert into a date.

This is how I do the check if the coupon is expired:

```<code>if ($date1B > $date2B) {
   echo "<script>alert('Expired coupon!!');</script>";
}
</code>```

Now what I want is to calculate the days when the coupon will be expired.

This is what I found on W3Schools, but the example below uses date_create(), so you make an custom date and time. I already have 2 dates and times.

```<code>$date1 = date("d-m-Y  H:i:s");
$date2 = date_format($date2A, 'd-m-Y H:i:s');
$diff = date_diff($date1,$date2);
echo $diff->format("%a days %h Hours %i Minute %s Seconds ");
</code>```

When I replace variables with the existing variables I get these errors:

date_diff() expects parameter 1 to be DateTimeInterface, string given in

and

Call to a member function format() on boolean in

The full .PHP page:

```<code><?php
   date_default_timezone_set("America/Curacao");

   $date1A = date("d/m/Y  H:i:s");
   $date1B = date("dmYHis");
   $date2B = "27032017042100";
   $date2A = date_create_from_format('dmYHis', $date2B);

   echo "Datum 1: " . $date1A . "<br>" ;
   echo "Datum 1: " . $date1B . "<br><br>";
   echo "Datum 2: " . date_format($date2A, 'd/m/Y H:i:s') . "<br>";
   echo "Datum 2: " . $date2B . "<br>";

   if ($date1B > $date2B) {
      echo "<script>alert('Klaar!!');</script>";
   }

   $date1 = date("d/m/Y  H:i:s");
   $date2 = date_format($date2A, 'd/m/Y H:i:s');
   $diff = date_diff($date1,$date2);
   echo $diff->format("%a days %h Hours %i Minute %s Seconds ");
?>
</code>```

答:
The simplest way to calculate the difference between two dates is date_diff() function which gives error on invalid dates.

Before passing on the values to date_diff function you should use the date_create() function.

Usage:

```<code><?php
$startDate = date_create('2014-06-13');
$endDate = date_create('2017-08-10');
$diff = date_diff($startDate, $endDate);
var_export($diff);
</code>```

Which gives you output like:

```<code>DateInterval::__set_state(array( 'y' => 3, 'm' => 1, 'd' => 28, 'h' => 0, 'i' => 0, 's' => 0, 'weekday' => 0, 'weekday_behavior' => 0, 'first_last_day_of' => 0, 'invert' => 0, 'days' => 1154, 'special_type' => 0, 'special_amount' => 0, 'have_weekday_relative' => 0, 'have_special_relative' => 0, ))
</code>```

UPDATE

You can use or modify the following function to get the difference:

```<code>function dateDifference($startDate, $endDate)
{
    try {
        $startDate = date_create($startDate);
        $endDate = date_create($endDate);
        $diff = date_diff($startDate, $endDate);
        $d = "";
        if ($diff->y != 0) {
            if ($diff->y > 1) {
                $d .= $diff->y . " Years ";
            } else {
                $d .= $diff->y . " Year ";
            }
        }
        if ($diff->m != 0) {
            if ($diff->m > 1) {
                $d .= $diff->m . " Months ";
            } else {
                $d .= $diff->m . " Month ";
            }
        }
        if ($diff->d != 0) {
            if ($diff->d > 1) {
                $d .= $diff->d . " Days ";
            } else {
                $d .= $diff->d . " Day ";
            }
        }
        if ($diff->h != 0) {
            if ($diff->h > 1) {
                $d .= $diff->h . " Hours ";
            } else {
                $d .= $diff->h . " Hour ";
            }
        }
        if ($diff->i != 0) {
            if ($diff->i > 1) {
                $d .= $diff->i . " Minutes ";
            } else {
                $d .= $diff->i . " Minute ";
            }
        }
        if ($diff->s != 0) {
            if ($diff->s > 1) {
                $d .= $diff->s . " Seconds ";
            } else {
                $d .= $diff->s . " Second ";
            }
        }
        return $d;
    }
    catch(Exception $e)
    {
        die("ERROR");
    }
}
</code>```

Running it like so:

```<code>echo dateDifference('2014-10-16', '2017-06-08');
</code>```

shall output:

```<code>2 Years 7 Months 23 Days
</code>```

Body:
Hi I'm making an online coupon system for mobile devices. The coupons are for a limited time active and I have to do a check on the coupons. I use date(d/m/Y  H:i:s) for just showing the date and time, and I also have a expire date which is a just a string that I later convert into a date.

This is how I do the check if the coupon is expired:

if ($date1B > $date2B) {
   echo "";
}

Now what I want is to calculate the days when the coupon will be expired.

This is what I found on W3Schools, but the example below uses date_create(), so you make an custom date and time. I already have 2 dates and times.

$date1 = date("d-m-Y  H:i:s");
$date2 = date_format($date2A, 'd-m-Y H:i:s');
$diff = date_diff($date1,$date2);
echo $diff->format("%a days %h Hours %i Minute %s Seconds ");

When I replace variables with the existing variables I get these errors:

date_diff() expects parameter 1 to be DateTimeInterface, string given in

and

Call to a member function format() on boolean in

The full .PHP page:

<?php
   date_default_timezone_set("America/Curacao");

   $date1A = date("d/m/Y  H:i:s");
   $date1B = date("dmYHis");
   $date2B = "27032017042100";
   $date2A = date_create_from_format('dmYHis', $date2B);

   echo "Datum 1: " . $date1A . "
" ;
   echo "Datum 1: " . $date1B . "

";
   echo "Datum 2: " . date_format($date2A, 'd/m/Y H:i:s') . "
";
   echo "Datum 2: " . $date2B . "
";

   if ($date1B > $date2B) {
      echo "";
   }

   $date1 = date("d/m/Y  H:i:s");
   $date2 = date_format($date2A, 'd/m/Y H:i:s');
   $diff = date_diff($date1,$date2);
   echo $diff->format("%a days %h Hours %i Minute %s Seconds ");
?>

Body:
The simplest way to calculate the difference between two dates is date_diff() function which gives error on invalid dates.

Before passing on the values to date_diff function you should use the date_create() function.

Usage:

<?php
$startDate = date_create('2014-06-13');
$endDate = date_create('2017-08-10');
$diff = date_diff($startDate, $endDate);
var_export($diff);

Which gives you output like:

DateInterval::__set_state(array( 'y' => 3, 'm' => 1, 'd' => 28, 'h' => 0, 'i' => 0, 's' => 0, 'weekday' => 0, 'weekday_behavior' => 0, 'first_last_day_of' => 0, 'invert' => 0, 'days' => 1154, 'special_type' => 0, 'special_amount' => 0, 'have_weekday_relative' => 0, 'have_special_relative' => 0, ))

UPDATE

You can use or modify the following function to get the difference:

function dateDifference($startDate, $endDate)
{
    try {
        $startDate = date_create($startDate);
        $endDate = date_create($endDate);
        $diff = date_diff($startDate, $endDate);
        $d = "";
        if ($diff->y != 0) {
            if ($diff->y > 1) {
                $d .= $diff->y . " Years ";
            } else {
                $d .= $diff->y . " Year ";
            }
        }
        if ($diff->m != 0) {
            if ($diff->m > 1) {
                $d .= $diff->m . " Months ";
            } else {
                $d .= $diff->m . " Month ";
            }
        }
        if ($diff->d != 0) {
            if ($diff->d > 1) {
                $d .= $diff->d . " Days ";
            } else {
                $d .= $diff->d . " Day ";
            }
        }
        if ($diff->h != 0) {
            if ($diff->h > 1) {
                $d .= $diff->h . " Hours ";
            } else {
                $d .= $diff->h . " Hour ";
            }
        }
        if ($diff->i != 0) {
            if ($diff->i > 1) {
                $d .= $diff->i . " Minutes ";
            } else {
                $d .= $diff->i . " Minute ";
            }
        }
        if ($diff->s != 0) {
            if ($diff->s > 1) {
                $d .= $diff->s . " Seconds ";
            } else {
                $d .= $diff->s . " Second ";
            }
        }
        return $d;
    }
    catch(Exception $e)
    {
        die("ERROR");
    }
}

Running it like so:

echo dateDifference('2014-10-16', '2017-06-08');

shall output:

2 Years 7 Months 23 Days


问:
Python: Set permissions for pip or conda in /opt directory
I installed python via Anaconda to my /opt directory (I heard that's the proper way when all users should be able to use it).

Everything is working fine so far, up to the point when I try to install packages via pip or conda. Than I get permission issues for both ways.
When I try to do:

```<code>sudo pip install pandas-datareader
</code>```

I get:

```<code>sudo: pip: command not found
</code>```

and the same error results if I try to use conda as well.

Does anyone have an idea how to fix that?

答: You don't need to run conda or pip with sudo. Just run pip install pandas-datareader.

Body:
I installed python via Anaconda to my /opt directory (I heard that's the proper way when all users should be able to use it).

Everything is working fine so far, up to the point when I try to install packages via pip or conda. Than I get permission issues for both ways.
When I try to do:

sudo pip install pandas-datareader

I get:

sudo: pip: command not found

and the same error results if I try to use conda as well.

Does anyone have an idea how to fix that?


问:
Using MSBuild Import to modularize a project
I have developed a large MSBuild project to build a portion of our solution.  There's a lot of things going on-- XML parsing/replacing, Windows services, remote copy, etc. As a result, the file has grown really difficult to manage, despite my best efforts to add decorations in comments.

As a goof, I broke out the main chunks of functionality out into separate files, like "XML.targets", "Services.targets", etc and imported them into the main "Build.proj." The build still worked and I immediately found it to be much more manageable.

However, all the info I have read on the Import feature of MSBuild is that it should be used to import reusable targets, ie those than can be consumed by -any- MSBuild project without any modifications.  The separate projects I'm creating here are the opposite-- specific to one project and will break by default if use with anything else unless modified.

So I guess what I'm asking is, even though I can... should I?  Is there an inherent danger in using Import strictly for the purpose of organizing a large project?  Is there a better way to do this?

Thanks

答:
No, there is no inherent danger. I think it's a good decision to split large project into several .targets files specific to certain operation since it reduces overall complexity. The idea of creating reusable targets means that they should have as little dependencies on the other parts as possible. By analogy you can think of separate .targets files as classes. The less coupled they are - the better. Because modification in one targets file will less likely break the whole process. You can take a peace of paper, draw your targets files as points with your main project in the center and draw all the connections between them. Say if one targets file overrides target from another or expects some properties from it or somehow else depends on it then there is a connection. In the perfect scenario you'll get something like a star.

In short: you should if it reduces complexity.


问:
python split by "\t" is not showing all elements in it
I am trying to split by "\t" but it is not printing all the elements in it

```<code>import sys
reload(sys)
sys.setdefaultencoding('utf8')

s = ['A\t"Ravi"\t"Tirupur"\t"India"\t"641652"\t"arunachalamravi@gmail.com"\t"17379602"\t"+ 2"\t"Government Higher Secondary School', ' Tiruppur"\t\t"1989"\t"Maths',' Science"\t"No"\t"Encotec Energy 2 X 600 MW ITPCL"\t"Associate Vice President- Head Maintenance"\t"2015"\t"2016"\t"No"\t"27-Mar-2017"\t"9937297878"\t\t"2874875"\t"Submitted"\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t']
print s[0].split("\t")
</code>```

Results

```<code>['A', '"Ravi"', '"Tirupur"', '"India"', '"641652"', '"arunachalamravi@gmail.com"', '"17379602"', '"+ 2"', '"Government Higher Secondary School']
</code>```

But i want results upto this

```<code>2874875, Submitted
</code>```

How to fix the code and where is the change?

答:
Easy, you have more than one item in your list so when you do s[0] you just get the first one, fix your list or fix your code like this:

```<code>joined_string = ''.join(s)
print joined_string.split("\t")
</code>```

It should work

Body:
I am trying to split by "\t" but it is not printing all the elements in it

import sys
reload(sys)
sys.setdefaultencoding('utf8')

s = ['A\t"Ravi"\t"Tirupur"\t"India"\t"641652"\t"arunachalamravi@gmail.com"\t"17379602"\t"+ 2"\t"Government Higher Secondary School', ' Tiruppur"\t\t"1989"\t"Maths',' Science"\t"No"\t"Encotec Energy 2 X 600 MW ITPCL"\t"Associate Vice President- Head Maintenance"\t"2015"\t"2016"\t"No"\t"27-Mar-2017"\t"9937297878"\t\t"2874875"\t"Submitted"\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t']
print s[0].split("\t")

Results

['A', '"Ravi"', '"Tirupur"', '"India"', '"641652"', '"arunachalamravi@gmail.com"', '"17379602"', '"+ 2"', '"Government Higher Secondary School']

But i want results upto this

2874875, Submitted

How to fix the code and where is the change?

Body:
Easy, you have more than one item in your list so when you do s[0] you just get the first one, fix your list or fix your code like this:

joined_string = ''.join(s)
print joined_string.split("\t")

It should work


问:
POSTMAN returns fail for schema validation test
I have a sample response:

```<code>{
  "tags": [
    {
      "id": 1,
      "name": "[String]",
      "user_id": 1,
      "created_at": "2016-12-20T15:50:37.000Z",
      "updated_at": "2016-12-20T15:50:37.000Z",
      "deleted_at": null
    }
  ]
}
</code>```

I've written a test for the response:

```<code>var schema = {
    "type": "object",
    "properties": {
        "tags": {
            "type": "object",
            "properties": {
                "id": { "type": "integer" },
                "name": { "type": "string" },
                "user_id": { "type": "number" },
                "created_at": { "type": "string" },
                "updated_at": { "type": "string" },
                "deleted_at": { "type": ["string", "null"] }
            }
        }
    }
};
var data = JSON.parse(responseBody);

tests["Valid schema"] = tv4.validate(data, schema);
</code>```

This test returns [FAIL]. What wrongs in the test?

Thank you for a respond!

答:
There is a problem on the definition of tags, since it's an array instead of an object. You should nest its properties into its items properties.

This code is passing the test:

```<code>test_data = {
  "tags": [
    {
      "id": 1,
      "name": "[String]",
      "user_id": 1,
      "created_at": "2016-12-20T15:50:37.000Z",
      "updated_at": "2016-12-20T15:50:37.000Z",
      "deleted_at": null
    }
  ]
}

test_schema = {
    "type": "object",
    "properties": {
        "tags": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "id": { "type": "integer" },
                    "name": { "type": "string" },
                    "user_id": { "type": "number" },
                    "created_at": { "type": "string" },
                    "updated_at": { "type": "string" },
                    "deleted_at": { "type": ["string", "null"] }
                }
            }
        }
    }
};
tests["Testing schema"] = tv4.validate(test_data, test_schema);
console.log("Validation errors: ", tv4.error);
</code>```

Body:
I have a sample response:

{
  "tags": [
    {
      "id": 1,
      "name": "[String]",
      "user_id": 1,
      "created_at": "2016-12-20T15:50:37.000Z",
      "updated_at": "2016-12-20T15:50:37.000Z",
      "deleted_at": null
    }
  ]
}

I've written a test for the response:

var schema = {
    "type": "object",
    "properties": {
        "tags": {
            "type": "object",
            "properties": {
                "id": { "type": "integer" },
                "name": { "type": "string" },
                "user_id": { "type": "number" },
                "created_at": { "type": "string" },
                "updated_at": { "type": "string" },
                "deleted_at": { "type": ["string", "null"] }
            }
        }
    }
};
var data = JSON.parse(responseBody);

tests["Valid schema"] = tv4.validate(data, schema);

This test returns [FAIL]. What wrongs in the test?

Thank you for a respond!

Body:
There is a problem on the definition of tags, since it's an array instead of an object. You should nest its properties into its items properties.

This code is passing the test:

test_data = {
  "tags": [
    {
      "id": 1,
      "name": "[String]",
      "user_id": 1,
      "created_at": "2016-12-20T15:50:37.000Z",
      "updated_at": "2016-12-20T15:50:37.000Z",
      "deleted_at": null
    }
  ]
}

test_schema = {
    "type": "object",
    "properties": {
        "tags": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "id": { "type": "integer" },
                    "name": { "type": "string" },
                    "user_id": { "type": "number" },
                    "created_at": { "type": "string" },
                    "updated_at": { "type": "string" },
                    "deleted_at": { "type": ["string", "null"] }
                }
            }
        }
    }
};
tests["Testing schema"] = tv4.validate(test_data, test_schema);
console.log("Validation errors: ", tv4.error);


问:
How safe is it to have references to union members in C++?
Imagine this situation:

```<code>union Reg16
{
    uint16_t word;

    struct
    {
        uint8_t bottom;
        uint8_t top;
    };
};
</code>```

Let's say I had something like this somewhere that uses this union:

```<code>Reg16 reg_AF;
uint8_t& reg_A = reg_AF.top;
uint8_t& reg_F = reg_AF.bottom;
</code>```

Is it safe to keep a reference to the respective halves of the union even though the union does not technically always refer to a u8? I am not sure if this is a violation of strict aliasing rules, but it is worth noting that there is no reference anywhere to the word, only to top and bottom. Especially in this particular situation, the references are supposed to point to the top and and bottom halves of the entire u16, so there isn't any UB because I won't be getting any value I don't expect to get by reading them versus if I had a union of a float and an int and made a reference to each of those.

Thanks in advance.

答:
The first thing to say is that there is explicit language in the strict aliasing rule (section 3.10 of the C++03 standard)† which permits access to a value via unsigned char.  If uint8_t is a typedef for unsigned char then this usage will be unequivocally legal.

However, uint8_t can be typedef for an implementation defined type which is not unsigned char (although careful reading of the standard shows that if uint8_t exists, it must be the same size as unsigned char).  Further, this question can still be of interest for other types (eg uint32_t and uint16_t).

There is definitely no harm in the reference existing - the only danger could arise if the reference is used when the union contains word rather than top + bottom.  On the other hand, if that happens (and top/bottom are not unsigned char) then the strict aliasing rule has been violated.

Given that the C standard explicitly permits type punning via unions (unlike C++), there is a significant chance that your C++ compiler will allow it too.

Aside: strictly speaking the sample is not legal; anonymous structs are an extension supported by GCC, Clang, and MSVC (so the question is, which compilers don't support them).

† The wording has changed slightly in later versions, and the section number may have changed - but the principle stays the same.

Body:
Imagine this situation:

union Reg16
{
    uint16_t word;

    struct
    {
        uint8_t bottom;
        uint8_t top;
    };
};

Let's say I had something like this somewhere that uses this union:

Reg16 reg_AF;
uint8_t& reg_A = reg_AF.top;
uint8_t& reg_F = reg_AF.bottom;

Is it safe to keep a reference to the respective halves of the union even though the union does not technically always refer to a u8? I am not sure if this is a violation of strict aliasing rules, but it is worth noting that there is no reference anywhere to the word, only to top and bottom. Especially in this particular situation, the references are supposed to point to the top and and bottom halves of the entire u16, so there isn't any UB because I won't be getting any value I don't expect to get by reading them versus if I had a union of a float and an int and made a reference to each of those.

Thanks in advance.


问:
SQL MAX of multiple columns?
How do you return 1 value per row of the max of several columns:

TableName

```<code>[Number, Date1, Date2, Date3, Cost]
</code>```

I need to return something like this:

```<code>[Number, Most_Recent_Date, Cost]
</code>```

Query?

答:
```<code>DECLARE @TableName TABLE (Number INT, Date1 DATETIME, Date2 DATETIME, Date3 DATETIME, Cost MONEY)

INSERT INTO @TableName
SELECT 1, '20000101', '20010101','20020101',100 UNION ALL
SELECT 2, '20000101', '19900101','19980101',99

SELECT Number,
       Cost  ,
       (SELECT MAX([Date])
       FROM    (SELECT Date1 AS [Date]
               UNION ALL
               SELECT Date2
               UNION ALL
               SELECT Date3
               )
               D
       )
       [Most Recent Date]
FROM   @TableName
</code>```

OwnerDisplayName: BenBruscella

Title: SQL MAX of multiple columns?

Body:
How do you return 1 value per row of the max of several columns:

TableName

[Number, Date1, Date2, Date3, Cost]

I need to return something like this:

[Number, Most_Recent_Date, Cost]

Query?

LastEditorDisplayName: Nigel Campbell


问:
Python regex to find phrases contain exact words
I have a list of strings and wish to find exact phases.

So far my code finds the month and year only, but the whole phase including “- Recorded” is needed, like “March 2016 - Recorded”.

How can it add on the “- Recorded” to the regex?

```<code>import re

texts = [

"Shawn Dookhit took annual leave in March 2016 - Recorded The report",
"Soondren Armon took medical leave in February 2017 - Recorded It was in",
"David Padachi took annual leave in May 2016 - Recorded It says",
"Jack Jagoo",
"Devendradutt Ramgolam took medical leave in August 2016 - Recorded Day back",
"Kate Dudhee",
"Vinaye Ramjuttun took annual leave in  - Recorded Answering"

]

regex = re.compile('(?P<month>[a-zA-Z]+)\s+(?P<year>\d{4})\s')

for t in texts:
    try:
        m = regex.search(t)
        print m.group()
    except:
        print "keyword's not found"
</code>```

答:
Use a list comprehension with the corrected regex:</p>

```<code>regex = re.compile('(?P<month>[a-zA-Z]+)\s+(?P<year>\d{4})\s* - Recorded')

matches = [match.groups() for text in texts for match in [regex.search(text)] if match]
print(matches)
# [('March', '2016'), ('February', '2017'), ('May', '2016'), ('August', '2016')]
</code>```

Body:
I have a list of strings and wish to find exact phases.

So far my code finds the month and year only, but the whole phase including “- Recorded” is needed, like “March 2016 - Recorded”.

How can it add on the “- Recorded” to the regex?

import re

texts = [

"Shawn Dookhit took annual leave in March 2016 - Recorded The report",
"Soondren Armon took medical leave in February 2017 - Recorded It was in",
"David Padachi took annual leave in May 2016 - Recorded It says",
"Jack Jagoo",
"Devendradutt Ramgolam took medical leave in August 2016 - Recorded Day back",
"Kate Dudhee",
"Vinaye Ramjuttun took annual leave in  - Recorded Answering"

]

regex = re.compile('(?P<month>[a-zA-Z]+)\s+(?P<year>\d{4})\s')

for t in texts:
    try:
        m = regex.search(t)
        print m.group()
    except:
        print "keyword's not found"

Body:
Use a list comprehension with the corrected regex:

regex = re.compile('(?P<month>[a-zA-Z]+)\s+(?P<year>\d{4})\s* - Recorded')

matches = [match.groups() for text in texts for match in [regex.search(text)] if match]
print(matches)
# [('March', '2016'), ('February', '2017'), ('May', '2016'), ('August', '2016')]


问:
How to extract Google Analytics historical data using APIs. Pros and cons?
I'm doing a quick proof of concept to understand the procedure to extract historical data from Google Analytics to be further used for offline data stitching to generate a holistic view of data and its analysis. I have not found any detailed online documentation available to understand pros and cons.

Would like to know any limitations on:

The time period for which data can be extracted or any limitation for max. calendar days?

Whether all dimensions/metrics can be extracted or any specific ones?

Will the data be real-time or sampled?

Can all data be pulled into a single table or separate ones?

Will it be available for both freeware and premium version?

答:
The time period for which data can be extracted or any limitation for max. calendar days?

Start date can not be before the launch of Google analytics on '2005-01-01'. Due to processing time lag extracting data that is newer then 2 days old can result in incomplete data.  Recommend checking the isDataGolden flag on the response.

Requesting large date ranges can result in sampling which can not be prevented. Its best to request the data in small chunks.

Whether all dimensions/metrics can be extracted or any specific ones?

A list of the dimensions and metrics you can extract can be found here. Each request can contain a maximum of 7 dimensions and 10 metrics.

Will the data be real-time or sampled?

Real-time API and Reporting API are two different APIs.  Real-time API is not to my knowledge sampled but as its only about five minutes of data I find it hard to think anyone but really big websites will hit this problem if it is.

Will it be available for both freeware and premium version?

Accessing Google Analytics APIs is free there is no charge.   There are however limits on how much data you can extract in a given day.

By default your application can run a maximum of 50k request a day. This can be extended.

Each view you are extracting from can make a maximum of 10k requests day.  This can not be extended.

See: limits and quotas for more info.

Note: I am a developer on a business intelligence application that extracts Google Analytics data.  I can tell you that its definitely doable.


答:
Nope. You can override those methods to add more functionality to your app but those methods already have their own function and will run whether you override it or not.

You could read more on the Android Activity Life Cycle: http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle

You could see this post as well: Android activity life cycle - what are all these methods for?

Title: Android activity and fragment life cycle - do I need to use all methods in my code?


问:
Calculating how many days between dates, diffrent months
So I'm playing around JavaScript's Date object, and I ran into something I think is a little strange.

I'm trying to figure out how many days there is between 2 given dates, and for that I use the formula below:

```<code>var oneDay = 24*60*60*1000;
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
</code>```

If you take 2017-05-28 & 2017-05-30 it returns 2 days - as it should

```<code>var oneDay = 24*60*60*1000;
var firstDate = new Date(2017, 05, 28);
var secondDate = new Date(2017, 05, 30);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
</code>```

If you take 2017-05-30 & 2017-06-01 it returns 1 days - supposed to be 2 days

```<code>var oneDay = 24*60*60*1000;
var firstDate = new Date(2017, 05, 28);
var secondDate = new Date(2017, 05, 30);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
</code>```

If you take 2017-05-30 & 2017-06-01 it returns 3 days - supposed to be 2 days

```<code>var oneDay = 24*60*60*1000;
var firstDate = new Date(2017, 11, 29);
var secondDate = new Date(2017, 12, 01);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
</code>```

答:
Please remember that Date constructor allows also values from outside the logical range.

Example: new Date(2017, -2, 30)

Source:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Where Date is called as a constructor with more than one argument, if
  values are greater than their logical range (e.g. 13 is provided as
  the month value or 70 for the minute value), the adjacent value will
  be adjusted. E.g. new Date(2013, 13, 1) is equivalent to new
  Date(2014, 1, 1), both create a date for 2014-02-01 (note that the
  month is 0-based). Similarly for other values: new Date(2013, 2, 1, 0,
  70) is equivalent to new Date(2013, 2, 1, 1, 10) which both create a
  date for 2013-03-01T01:10:00.

Body:
So I'm playing around JavaScript's Date object, and I ran into something I think is a little strange.

I'm trying to figure out how many days there is between 2 given dates, and for that I use the formula below:

var oneDay = 24*60*60*1000;
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));

If you take 2017-05-28 & 2017-05-30 it returns 2 days - as it should

var oneDay = 24*60*60*1000;
var firstDate = new Date(2017, 05, 28);
var secondDate = new Date(2017, 05, 30);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));

If you take 2017-05-30 & 2017-06-01 it returns 1 days - supposed to be 2 days

var oneDay = 24*60*60*1000;
var firstDate = new Date(2017, 05, 28);
var secondDate = new Date(2017, 05, 30);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));

If you take 2017-05-30 & 2017-06-01 it returns 3 days - supposed to be 2 days

var oneDay = 24*60*60*1000;
var firstDate = new Date(2017, 11, 29);
var secondDate = new Date(2017, 12, 01);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));


问:
Unknown column 'User.first_name' in 'where clause' cakePHP
I have tutor_students and users table. tutor_studentscontains id, tutor_id, student_id and created. users contain id, user_id, role_id, email, first_name, last_name. tutor_students table is connected table between tutor and student. so tutor can see their student list and can add new student too.

I succeeded to display student list and add new student to tutor student list. but when i want to search student, there will be an error:

Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column
  'User.email' in 'where clause'

SQL Query: SELECT TutorStudent.id, TutorStudent.tutor_id,
  TutorStudent.student_id, TutorStudent.created FROM
  virlen.tutor_students AS TutorStudent WHERE
  TutorStudent.tutor_id IS NULL AND User.email LIKE
  '%ka@mailinator.com%'

My controller:

```<code>public function admin_tutor_add_student($tutor_id = null)
{
    $user_list = '';
    $this->loadModel('TutorStudent');
    $this->set('title_for_layout','User');
    $this->User->bindModel(array(
                    'belongsTo'=>array(
                        'Standard'=>array(
                            'className'=>'Standard'
                        ),
                    )
    ),false);

    $this->User->id     =   $tutor_id;
    /*form post and check conditions*/
    // if ($this->request->is('post') || $this->request->is('put'))
    if(!empty($this->request->data) && isset($this->request->data['User']['status1']))
    {
        // pr($this->request->data);die;
        $action = $this->request->data['User']['pageAction'];
        foreach ($this->request->data['User'] AS $value) {
            if ($value != 0) {
                $ids[] = $value;
            }
        }

        // pr($ids);die;
        if (!empty($this->request->data))
        {
            if (!isset($this->request->params['_Token']['key']) || ($this->request->params['_Token']['key'] != $this->request->params['_Token']['key']))
            {
                $blackHoleCallback = $this->Security->blackHoleCallback;
                $this->$blackHoleCallback();
            }
            foreach($ids as $id)
            {
                if(!empty($id))
                {
                    if($id != 1)
                    {
                        $shift = array();
                        $shift['TutorStudent']['tutor_id'] = $tutor_id;
                        $shift['TutorStudent']['student_id'] = $id;
                        $this->TutorStudent->save($shift);
                        $this->TutorStudent->id = false;
                    }
                }
            }

            $this->Session->setFlash("Tutor has been added successfully", 'admin_flash_good');
            $this->redirect(array('controller'=>'users', 'action'=>'subadmin_tutor',$tutor_id));

        }
    }

    if (!isset($this->params['named']['page']))
    {
        $this->Session->delete('AdminSearch');
    }
    $email = '';
    $first_name = '';
    $role_id = '';
    $status = '';
    if (!empty($this->request->data))
    {
        $this->Session->delete('AdminSearch');
        if (isset($this->request->data['User']['first_name']) && $this->request->data['User']['first_name'] != '')
        {
            $first_name = trim($this->request->data['User']['first_name']);
            $this->Session->write('AdminSearch.first_name', $first_name);
        }
        if (isset($this->request->data['User']['email']) && $this->request->data['User']['email'] != '')
        {
            $email = trim($this->request->data['User']['email']);
            $this->Session->write('AdminSearch.email', $email);
        }

    }

    $filters    =   array('TutorStudent.tutor_id'=>$tutor_id);
    if ($this->Session->check('AdminSearch'))
    {
        $keywords   =   $this->Session->read('AdminSearch');
        foreach($keywords as $key=>$values)
        {
            if($key == 'email')
            {
                $email = $values;
                $filters[] = array('User.'.$key.' LIKE'=>"%".$values."%");
            }
            if($key == 'first_name')
            {
                $first_name = $values;
                $filters[] = array('User.'.$key.' LIKE'=>"%".$values."%");
            }
        }
    }

    $my_tutor_list = $this->TutorStudent->find('all',array('conditions'=>$filters));
    if(!empty($my_tutor_list))
    {
        foreach($my_tutor_list as $key=>$value)
        {
            $user_list[] = $value['TutorStudent']['student_id'];
        }
    }

    $this->paginate = array('User' => array(
        'limit' =>Configure::read('App.PageLimit'),
        'order' => array('User.id' => 'DESC'),
        'conditions'=>array('User.id !='=>$user_list,'User.role_id'=>2),
        )); //role_id 2 means student user

    $student_list = $this->paginate('User');

    // pr($student_list);die;
    $this->loadModel('Standard');
    $standards  =   $this->Standard->getStandardList();
    $this->set(compact('standards'));
    $this->set(compact('student_list','tutor_id','standard_id', 'User', 'email', 'first_name'));
    $this->set('title_for_layout', __('User', true));
}
</code>```

this is my view file:

```<code><?php echo($this->Form->create('User', array('url'=>array('controller' => 'users', 'action' => 'tutor_add_student'))));?>
            <div class="box-body table-responsive">
                <div class="box box-danger">
                    <div class="full box-header">
                        <h3 class="box-title">Search</h3>
                    </div>
                    <div class="box-body">
                        <div class="row">
                            <div class="col-xs-2">
                                <label for="exampleInputPassword1">User Email</label>
                                <?php echo($this->Form->input('User.email', array('placeholder'=>"Tutor Email",'label' => false,'value'=>$email, 'div'=>false,'class'=>'form-control'))); ?>
                            </div>
                            <div class="col-xs-2">
                                <label for="exampleInputPassword1">First Name </label>
                                <?php echo($this->Form->input('User.first_name', array('placeholder'=>"First Name",'label' => false,'value'=>$first_name, 'div'=>false,'class'=>'form-control'))); ?>
                            </div>
                            <div class="col-xs-2" style="margin-top: 5px;">
                                <br /><?php echo($this->Form->submit('Search', array('div'=>false, 'class'=>'btn btn-primary pull-left')));?>
                            </div>

                        </div>
                    </div><!-- /.box-body -->
                </div>

            </div>
         <?php echo($this->Form->end());?>
</code>```

This is my app model for user:

```<code>    <?php
/**
 * Country
 *
 * PHP version 5
 *
 * @category Model
 *
 */
// App::uses('AuthComponent', 'Controller/Component');
// App::uses('SessionComponent', 'Controller/Component');
App::uses('AppModel', 'Model');
class User extends AppModel{

    //public $primaryKey = '_id';

    /**
     * Model name
     * @var string
     * @access public
     */
    var $name = 'User';
    /**
     * Behaviors used by the Model
     *
     * @var array
     * @access public
     */

    var $actsAs = array(
       'Multivalidatable'
    );

    var $validationSets = array(
        'login'=>   array(
            'email'=>array(
                'notEmpty' => array(
                    'rule'      => 'notEmpty',
                    'message'   =>  'Email address is required'
                ),
                'R2'=>array(
                    'rule'=>array('maxLength', 50),
                    'message'=>'Email can be maximum 50 characters long.'
                ),
                'email' =>  array(
                    'rule'  =>  'email',
                    'message'   =>  'Please provide a valid email address.'
                ),
            ),
            'password'=>array(
                'R1'=>array(
                    'rule'=>'notEmpty',
                    'message' => 'Password is required.'
                ),
                'R3'=>array(
                    'rule'=>array('minLength', 6),
                    'message'=>'Password must be at least 6 characters long.'
                ),
                'R4'=>array(
                    'rule'=>array('maxLength', 20),
                    'message'=>'Password must be at least 20 characters long.'
                ),
            ),
        ),
        'add'=> array(
            'first_name'=>array(
                'R1'=>array(
                    'rule'=>'notEmpty',
                    'message' => 'First name is required.'
                ),
                'R2'=>array(
                    'rule'=>array('maxLength', 255),
                    'message'=>'First Name can be maximum 255 characters long.'
                ),
                'characters' => array(
                    'rule'     => array('custom', '/^[a-z]*$/i'),
                    'message'  => 'Alphabet characters only'
                )
            ),
            'last_name'=>array(
                'R1'=>array(
                    'rule'=>'notEmpty',
                    'message' => 'Last name is required.'
                ),
                'R2'=>array(
                    'rule'=>array('maxLength',255),
                    'message'=>'Last name can be maximum 255 characters long.'
                ),
                'characters' => array(
                    'rule'     => array('custom', '/^[a-z]*$/i'),
                    'message'  => 'Alphabet characters only'
                )
            ),
            'standard_id'=>array(
                'R1'=>array(
                    'rule'=>'notEmpty',
                    'message' => 'Standard is required.'
                )
            ),
            'role_id'=>array(
                'R1'=>array(
                    'rule'=>'notEmpty',
                    'message' => 'Role is required.'
                )
            ),
            'specilization'=>array(
                'R1' => array(
                    'rule'      => 'notEmpty',
                    'message'   =>  'Specilization is required.'
                ),
                'R2'=>array(
                    'rule'=>array('maxLength', 255),
                    'message'=>'Specilization can be 255 characters long.'
                ),
            ),
            'phone'=>array(
                'R1' => array(
                    'rule'      => 'notEmpty',
                    'message'   =>  'Phone number is required.'
                ),
                'notEmpty' => array(
                    'rule'      => 'numeric',
                    'message'   =>  'Phone number should be numeric'
                ),
                'R2'=>array(
                    'rule'=>array('minLength', 8),
                    'message'=>'Phone number shuold be minimum 8 numbers long'
                ),
                'R3'=>array(
                    'rule'=>array('maxLength', 12),
                    'message'=>'Phone number should be maximum 12 numbers long'
                ),
                /* 'R4'=>array(
                    'rule'=>array('CheckPhoneVailidation'),
                    'message'=>'Phone no should be start with 82 to 87.'
                ),   */
            ),
            'email'=>array(
                'notEmpty' => array(
                    'rule'      => 'notEmpty',
                    'message'   =>  'Email address is required'
                ),
                'R2'=>array(
                    'rule'=>array('maxLength', 50),
                    'message'=>'Email can be maximum 50 characters long.'
                ),
                'isUnique'  =>  array(
                    'rule'  =>  'isUnique',
                    'message'   =>  'Email already exists.'
                ),
                'email' =>  array(
                    'rule'  =>  'email',
                    'message'   =>  'Please provide a valid email address.'
                ),
            ),
            'new_password'=>array(
                'R1'=>array(
                    'rule'=>'notEmpty',
                    'message' => 'Password is required.'
                ),
                'R3'=>array(
                    'rule'=>array('minLength', 6),
                    'message'=>'Password must be at least 6 characters long.'
                ),
                'R4'=>array(
                    'rule'=>array('maxLength', 20),
                    'message'=>'Password must be at least 20 characters long.'
                ),
            ),
            'confirm_password'=>array(
                'identicalFieldValues' => array(
                    'rule' => array('identicalFieldValues', 'new_password'),
                    'message' => 'Password and confirm password mismatch'
                ),
                'R1' => array(
                    'rule' => 'notEmpty',
                    'message' => 'Confirm password is required.'
                )

            ),
            'image' => array(
                'R1' => array(
                    'rule' => array('checkextension'),
                    'message' => 'Please upload only image files'
                )
            ),
        )

    );
}
</code>```

答:
the from clause should be

```<code>virlen.tutor_students AS TutorStudent,virlen.users AS User
</code>```

Then your query should be

```<code>SELECT TutorStudent.id, TutorStudent.tutor_id, TutorStudent.student_id, TutorStudent.created FROM virlen.tutor_students AS TutorStudent,virlen.users AS User WHERE TutorStudent.tutor_id IS NULL AND User.email LIKE '%ka@mailinator.com%'
</code>```

Your code should be

```<code>$my_tutor_list = $this->TutorStudent->find('all',array('conditions'=>$filters,'contain' => array('User')));
if(!empty($my_tutor_list))
{
    foreach($my_tutor_list as $key=>$value)
    {
        $user_list[] = $value['TutorStudent']['student_id'];
    }
}
</code>```

Body:
I have tutor_students and users table. tutor_studentscontains id, tutor_id, student_id and created. users contain id, user_id, role_id, email, first_name, last_name. tutor_students table is connected table between tutor and student. so tutor can see their student list and can add new student too.

I succeeded to display student list and add new student to tutor student list. but when i want to search student, there will be an error:

Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column
  'User.email' in 'where clause'

SQL Query: SELECT TutorStudent.id, TutorStudent.tutor_id,
  TutorStudent.student_id, TutorStudent.created FROM
  virlen.tutor_students AS TutorStudent WHERE
  TutorStudent.tutor_id IS NULL AND User.email LIKE
  '%ka@mailinator.com%'

My controller:

public function admin_tutor_add_student($tutor_id = null)
{
    $user_list = '';
    $this->loadModel('TutorStudent');
    $this->set('title_for_layout','User');
    $this->User->bindModel(array(
                    'belongsTo'=>array(
                        'Standard'=>array(
                            'className'=>'Standard'
                        ),
                    )
    ),false);

    $this->User->id     =   $tutor_id;
    /*form post and check conditions*/
    // if ($this->request->is('post') || $this->request->is('put'))
    if(!empty($this->request->data) && isset($this->request->data['User']['status1']))
    {
        // pr($this->request->data);die;
        $action = $this->request->data['User']['pageAction'];
        foreach ($this->request->data['User'] AS $value) {
            if ($value != 0) {
                $ids[] = $value;
            }
        }

        // pr($ids);die;
        if (!empty($this->request->data))
        {
            if (!isset($this->request->params['_Token']['key']) || ($this->request->params['_Token']['key'] != $this->request->params['_Token']['key']))
            {
                $blackHoleCallback = $this->Security->blackHoleCallback;
                $this->$blackHoleCallback();
            }
            foreach($ids as $id)
            {
                if(!empty($id))
                {
                    if($id != 1)
                    {
                        $shift = array();
                        $shift['TutorStudent']['tutor_id'] = $tutor_id;
                        $shift['TutorStudent']['student_id'] = $id;
                        $this->TutorStudent->save($shift);
                        $this->TutorStudent->id = false;
                    }
                }
            }

            $this->Session->setFlash("Tutor has been added successfully", 'admin_flash_good');
            $this->redirect(array('controller'=>'users', 'action'=>'subadmin_tutor',$tutor_id));

        }
    }

    if (!isset($this->params['named']['page']))
    {
        $this->Session->delete('AdminSearch');
    }
    $email = '';
    $first_name = '';
    $role_id = '';
    $status = '';
    if (!empty($this->request->data))
    {
        $this->Session->delete('AdminSearch');
        if (isset($this->request->data['User']['first_name']) && $this->request->data['User']['first_name'] != '')
        {
            $first_name = trim($this->request->data['User']['first_name']);
            $this->Session->write('AdminSearch.first_name', $first_name);
        }
        if (isset($this->request->data['User']['email']) && $this->request->data['User']['email'] != '')
        {
            $email = trim($this->request->data['User']['email']);
            $this->Session->write('AdminSearch.email', $email);
        }

    }

    $filters    =   array('TutorStudent.tutor_id'=>$tutor_id);
    if ($this->Session->check('AdminSearch'))
    {
        $keywords   =   $this->Session->read('AdminSearch');
        foreach($keywords as $key=>$values)
        {
            if($key == 'email')
            {
                $email = $values;
                $filters[] = array('User.'.$key.' LIKE'=>"%".$values."%");
            }
            if($key == 'first_name')
            {
                $first_name = $values;
                $filters[] = array('User.'.$key.' LIKE'=>"%".$values."%");
            }
        }
    }

    $my_tutor_list = $this->TutorStudent->find('all',array('conditions'=>$filters));
    if(!empty($my_tutor_list))
    {
        foreach($my_tutor_list as $key=>$value)
        {
            $user_list[] = $value['TutorStudent']['student_id'];
        }
    }

    $this->paginate = array('User' => array(
        'limit' =>Configure::read('App.PageLimit'),
        'order' => array('User.id' => 'DESC'),
        'conditions'=>array('User.id !='=>$user_list,'User.role_id'=>2),
        )); //role_id 2 means student user

    $student_list = $this->paginate('User');

    // pr($student_list);die;
    $this->loadModel('Standard');
    $standards  =   $this->Standard->getStandardList();
    $this->set(compact('standards'));
    $this->set(compact('student_list','tutor_id','standard_id', 'User', 'email', 'first_name'));
    $this->set('title_for_layout', __('User', true));
}

this is my view file:

<?php echo($this->Form->create('User', array('url'=>array('controller' => 'users', 'action' => 'tutor_add_student'))));?>

Search

                                User Email
                                <?php echo($this->Form->input('User.email', array('placeholder'=>"Tutor Email",'label' => false,'value'=>$email, 'div'=>false,'class'=>'form-control'))); ?>

                                First Name
                                <?php echo($this->Form->input('User.first_name', array('placeholder'=>"First Name",'label' => false,'value'=>$first_name, 'div'=>false,'class'=>'form-control'))); ?>

<?php echo($this->Form->submit('Search', array('div'=>false, 'class'=>'btn btn-primary pull-left')));?>

         <?php echo($this->Form->end());?>

This is my app model for user:

    <?php
/**
 * Country
 *
 * PHP version 5
 *
 * @category Model
 *
 */
// App::uses('AuthComponent', 'Controller/Component');
// App::uses('SessionComponent', 'Controller/Component');
App::uses('AppModel', 'Model');
class User extends AppModel{

    //public $primaryKey = '_id';

    /**
     * Model name
     * @var string
     * @access public
     */
    var $name = 'User';
    /**
     * Behaviors used by the Model
     *
     * @var array
     * @access public
     */

    var $actsAs = array(
       'Multivalidatable'
    );

    var $validationSets = array(
        'login'=>   array(
            'email'=>array(
                'notEmpty' => array(
                    'rule'      => 'notEmpty',
                    'message'   =>  'Email address is required'
                ),
                'R2'=>array(
                    'rule'=>array('maxLength', 50),
                    'message'=>'Email can be maximum 50 characters long.'
                ),
                'email' =>  array(
                    'rule'  =>  'email',
                    'message'   =>  'Please provide a valid email address.'
                ),
            ),
            'password'=>array(
                'R1'=>array(
                    'rule'=>'notEmpty',
                    'message' => 'Password is required.'
                ),
                'R3'=>array(
                    'rule'=>array('minLength', 6),
                    'message'=>'Password must be at least 6 characters long.'
                ),
                'R4'=>array(
                    'rule'=>array('maxLength', 20),
                    'message'=>'Password must be at least 20 characters long.'
                ),
            ),
        ),
        'add'=> array(
            'first_name'=>array(
                'R1'=>array(
                    'rule'=>'notEmpty',
                    'message' => 'First name is required.'
                ),
                'R2'=>array(
                    'rule'=>array('maxLength', 255),
                    'message'=>'First Name can be maximum 255 characters long.'
                ),
                'characters' => array(
                    'rule'     => array('custom', '/^[a-z]*$/i'),
                    'message'  => 'Alphabet characters only'
                )
            ),
            'last_name'=>array(
                'R1'=>array(
                    'rule'=>'notEmpty',
                    'message' => 'Last name is required.'
                ),
                'R2'=>array(
                    'rule'=>array('maxLength',255),
                    'message'=>'Last name can be maximum 255 characters long.'
                ),
                'characters' => array(
                    'rule'     => array('custom', '/^[a-z]*$/i'),
                    'message'  => 'Alphabet characters only'
                )
            ),
            'standard_id'=>array(
                'R1'=>array(
                    'rule'=>'notEmpty',
                    'message' => 'Standard is required.'
                )
            ),
            'role_id'=>array(
                'R1'=>array(
                    'rule'=>'notEmpty',
                    'message' => 'Role is required.'
                )
            ),
            'specilization'=>array(
                'R1' => array(
                    'rule'      => 'notEmpty',
                    'message'   =>  'Specilization is required.'
                ),
                'R2'=>array(
                    'rule'=>array('maxLength', 255),
                    'message'=>'Specilization can be 255 characters long.'
                ),
            ),
            'phone'=>array(
                'R1' => array(
                    'rule'      => 'notEmpty',
                    'message'   =>  'Phone number is required.'
                ),
                'notEmpty' => array(
                    'rule'      => 'numeric',
                    'message'   =>  'Phone number should be numeric'
                ),
                'R2'=>array(
                    'rule'=>array('minLength', 8),
                    'message'=>'Phone number shuold be minimum 8 numbers long'
                ),
                'R3'=>array(
                    'rule'=>array('maxLength', 12),
                    'message'=>'Phone number should be maximum 12 numbers long'
                ),
                /* 'R4'=>array(
                    'rule'=>array('CheckPhoneVailidation'),
                    'message'=>'Phone no should be start with 82 to 87.'
                ),   */
            ),
            'email'=>array(
                'notEmpty' => array(
                    'rule'      => 'notEmpty',
                    'message'   =>  'Email address is required'
                ),
                'R2'=>array(
                    'rule'=>array('maxLength', 50),
                    'message'=>'Email can be maximum 50 characters long.'
                ),
                'isUnique'  =>  array(
                    'rule'  =>  'isUnique',
                    'message'   =>  'Email already exists.'
                ),
                'email' =>  array(
                    'rule'  =>  'email',
                    'message'   =>  'Please provide a valid email address.'
                ),
            ),
            'new_password'=>array(
                'R1'=>array(
                    'rule'=>'notEmpty',
                    'message' => 'Password is required.'
                ),
                'R3'=>array(
                    'rule'=>array('minLength', 6),
                    'message'=>'Password must be at least 6 characters long.'
                ),
                'R4'=>array(
                    'rule'=>array('maxLength', 20),
                    'message'=>'Password must be at least 20 characters long.'
                ),
            ),
            'confirm_password'=>array(
                'identicalFieldValues' => array(
                    'rule' => array('identicalFieldValues', 'new_password'),
                    'message' => 'Password and confirm password mismatch'
                ),
                'R1' => array(
                    'rule' => 'notEmpty',
                    'message' => 'Confirm password is required.'
                )

            ),
            'image' => array(
                'R1' => array(
                    'rule' => array('checkextension'),
                    'message' => 'Please upload only image files'
                )
            ),
        )

    );
}

Body:
the from clause should be

virlen.tutor_students AS TutorStudent,virlen.users AS User

Then your query should be

SELECT TutorStudent.id, TutorStudent.tutor_id, TutorStudent.student_id, TutorStudent.created FROM virlen.tutor_students AS TutorStudent,virlen.users AS User WHERE TutorStudent.tutor_id IS NULL AND User.email LIKE '%ka@mailinator.com%'

Your code should be

$my_tutor_list = $this->TutorStudent->find('all',array('conditions'=>$filters,'contain' => array('User')));
if(!empty($my_tutor_list))
{
    foreach($my_tutor_list as $key=>$value)
    {
        $user_list[] = $value['TutorStudent']['student_id'];
    }
}


问:
Same foreign key in multiple tables
I've seen posts on SO and through google stating that with Mysql you cannot have multiple foreign keys of the same name. My issue is how do I reference the same column from one table in multiple other tables. In my case I have a FAMILY table that contains FAM_ID. I want this to be a foreign key in my DOCUMENTS and CONTACT tables because rows in those have a relationship with FAM_ID. So if I understand what I've read correctly I need to name the column in DOCUMENTS and CONTACT different names (than FAM_ID) in order to have them map as a foreign key to FAM_ID in the FAMILY table. Am I just not understanding something or is this my only option? It seems like this would be a fairly common requirement of a data model.</p>

答: I'm having this same issue, havn't really noticed any good solutions. I originally wanted to keep my foreign key names the same as the primary key they referenced, to make natural joins possible. So I'll be renaming my foreign keys to something like {reference_primary_key}_1, {reference_primary_key}_2, etc..</p>

Title: Same foreign key in multiple tables


问:
Disable button until checkbox ticked
Apologies if this has already been asked, i have found it difficult to use the answers I have found to use in my code.

Basically, I have a "receive" button, that when the user clicks, will receive an email. But, I want a tick box checked in order for the button to become clickable. I have a code that kind of works, but when the page first loads, the "Receive" button is already clickable. However, when I click the tick box then unclick it, it disables the button.

```<code><td>
    <input type="checkbox"  id="tick" onchange="document.getElementById('terms').disabled = !this.checked;" />
    <td>
    <p> I agree to the <a href="terms.html" target="_blank">Terms & Conditions</a></p>
    </td>
</td>
</tr>
<td class="label1"></td>
<td align="right">
    <button type="submit" class="btn btn1" name="terms" id="terms">Receive</i></button>
</td>
</code>```

答:
Just add disabled attribute on button

```<code><button type="submit" class="btn btn1" name="terms" disabled id="terms">Receive</i></button>
</code>```

Title: Disable button until checkbox ticked

Body:
Apologies if this has already been asked, i have found it difficult to use the answers I have found to use in my code.

Basically, I have a "receive" button, that when the user clicks, will receive an email. But, I want a tick box checked in order for the button to become clickable. I have a code that kind of works, but when the page first loads, the "Receive" button is already clickable. However, when I click the tick box then unclick it, it disables the button.

    <input type="checkbox"  id="tick" onchange="document.getElementById('terms').disabled = !this.checked;" />

 I agree to the Terms & Conditions

    <button type="submit" class="btn btn1" name="terms" id="terms">Receive</button>

Body:
Just add disabled attribute on button

<button type="submit" class="btn btn1" name="terms" disabled id="terms">Receive</i></button>