问:
Opening PDF from android App
I am using custom class for opening PDF from my android application. It checks whether PDF is already downloaded and then open PDF using existing PDF Viewer application. If there is no pdf viewer application then it tries to open pdf using google docs.

The class was working fine till the upgrade of Android Studio 2.2.3 to 2.3.2 and Build Tool Version from 24 to 25. The target SDK is still API 24. Unable to figure out exact root cause of the issue.

PDF Class :

```<code>public class PDFTools {
private static final String GOOGLE_DRIVE_PDF_READER_PREFIX = "http://docs.google.com/viewer?url=";
private static final String PDF_MIME_TYPE = "application/pdf";
private static final String HTML_MIME_TYPE = "text/html";

/**
 * If a PDF reader is installed, download the PDF file and open it in a reader.
 * Otherwise ask the user if he/she wants to view it in the Google Drive online PDF reader.<br />
 * <br />
 * <b>BEWARE:</b> This method
 * @param context
 * @param pdfUrl
 * @return
 */
public static void showPDFUrl( final Context context, final String pdfUrl ) {
    if ( isPDFSupported( context ) ) {
        downloadAndOpenPDF(context, pdfUrl);
    } else {
        askToOpenPDFThroughGoogleDrive( context, pdfUrl );
    }
}

/**
 * Downloads a PDF with the Android DownloadManager and opens it with an installed PDF reader app.
 * @param context
 * @param pdfUrl
 */

public static void downloadAndOpenPDF(final Context context, final String pdfUrl) {
    // Get filename
    final String filename = pdfUrl.substring( pdfUrl.lastIndexOf( "/" ) + 1 );
    // The place where the downloaded PDF file will be put
    final File tempFile = new File( context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), filename );
    if ( tempFile.exists() ) {
        // If we have downloaded the file before, just go ahead and show it.
        Uri uri = null;
        File docPath = new File(context.getExternalFilesDir(null), "Download");
        File newFile = new File(docPath, filename);

        uri = FileProvider.getUriForFile( context, BuildConfig.APPLICATION_ID + ".provider", newFile );

        openPDF( context, uri);
        return;
    }

    // Show progress dialog while downloading
    final ProgressDialog progress = ProgressDialog.show( context, context.getString( R.string.pdf_show_local_progress_title ),
            context.getString( R.string.message_please_wait ), true );

    // Create the download request
    DownloadManager.Request r = new DownloadManager.Request( Uri.parse( pdfUrl ) );
    r.setDestinationInExternalFilesDir( context, Environment.DIRECTORY_DOWNLOADS, filename );
    final DownloadManager dm = (DownloadManager) context.getSystemService( Context.DOWNLOAD_SERVICE );
    BroadcastReceiver onComplete = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if ( !progress.isShowing() ) {
                return;
            }
            context.unregisterReceiver( this );

            progress.dismiss();
            long downloadId = intent.getLongExtra( DownloadManager.EXTRA_DOWNLOAD_ID, -1 );
            Cursor c = dm.query( new DownloadManager.Query().setFilterById( downloadId ) );

            if ( c.moveToFirst() ) {
                int status = c.getInt( c.getColumnIndex( DownloadManager.COLUMN_STATUS ) );
                if ( status == DownloadManager.STATUS_SUCCESSFUL ) {
                    Uri uri = null;
                    try {
                        uri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", tempFile );

                    }catch (IllegalArgumentException iae) {
                        iae.printStackTrace();
                    }
                    if (uri !=null) {
                        openPDF(context, uri);
                    }
                }
            }
            c.close();
        }
    };
    context.registerReceiver( onComplete, new IntentFilter( DownloadManager.ACTION_DOWNLOAD_COMPLETE ) );

    // Enqueue the request
    dm.enqueue( r );
}

/**
 * Show a dialog asking the user if he wants to open the PDF through Google Drive
 * @param context
 * @param pdfUrl
 */
public static void askToOpenPDFThroughGoogleDrive( final Context context, final String pdfUrl ) {
    new AlertDialog.Builder( context )
            .setTitle( R.string.pdf_show_online_dialog_title )
            .setMessage( R.string.pdf_show_online_dialog_question )
            .setNegativeButton( R.string.pdf_show_online_dialog_button_no, null )
            .setPositiveButton( R.string.pdf_show_online_dialog_button_yes, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    openPDFThroughGoogleDrive(context, pdfUrl);
                }
            })
            .show();
}

/**
 * Launches a browser to view the PDF through Google Drive
 * @param context
 * @param pdfUrl
 */
public static void openPDFThroughGoogleDrive(final Context context, final String pdfUrl) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    i.setDataAndType(Uri.parse(GOOGLE_DRIVE_PDF_READER_PREFIX + pdfUrl ), HTML_MIME_TYPE );
    context.startActivity( i );
}
/**
 * Open a local PDF file with an installed reader
 * @param context
 * @param localUri
 */
public static final void openPDF(Context context, Uri localUri ) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    i.setDataAndType( localUri, PDF_MIME_TYPE );
    context.startActivity( i );
}
/**
 * Checks if any apps are installed that supports reading of PDF files.
 * @param context
 * @return
 */
public static boolean isPDFSupported( Context context ) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    final File tempFile = new File( context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "test.pdf" );
    i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    i.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    try {
        i.setDataAndType( FileProvider.getUriForFile( context, BuildConfig.APPLICATION_ID + ".provider" ,tempFile ), PDF_MIME_TYPE );
    }catch (IllegalArgumentException iae ) {
    }
    return context.getPackageManager().queryIntentActivities( i, PackageManager.MATCH_DEFAULT_ONLY ).size() > 0;
}
</code>```

}

It throws an error as

```<code>java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/emulated/0/Android/data/<PACKAGE>/files/Download/javascript_pdf_version.pdf
</code>```

I have taken this sample from stack overflow itself. Appreciate your help on this.

答:
Try something like this to download:

WebService using RestTemplate:

```<code>public PdfByteArrayObject getPrintjob(String empId) {
    PdfByteArrayObject pdfByteArrayObject = null;
    try {
        getUrl();
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

        pdfByteArrayObject = restTemplate.getForObject("pdfURL" + empId, PdfByteArrayObject.class);

    } catch (Exception e) {
      e.printStackTrace();
      Log.e("webser======", e.toString());
    }
    return pdfByteArrayObject;
}
</code>```

The getUrl method(for File conversion & storage):

```<code>public void getUrl() {
    StringBuffer stringBuffer = new StringBuffer();
    String aDataRow = "";
    String aBuffer = "";
    try {
        File serverPath = new File(Environment.getExternalStorageDirectory(), "ServerUrl");

        if (serverPath.exists()) {
            FileInputStream fIn = new FileInputStream(serverPath);
            BufferedReader myReader = new BufferedReader(
                    new InputStreamReader(fIn));

            while ((aDataRow = myReader.readLine()) != null) {
                aBuffer += aDataRow;
            }
            RestUrl = aBuffer;
            Log.e("RestUrl", RestUrl + "--");
            myReader.close();
        } else {
            Log.e("RestUrl", "File not found");
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
    // Toast.makeText(getApplicationContext(),aBuffer,Toast.LENGTH_LONG).show();
}
</code>```

And the object:

```<code>public class PdfByteArrayObject {

private byte[] pdffile;

public byte[] getPdffile() {
    return pdffile;
}

public void setPdffile(byte[] pdffile) {
    this.pdffile = pdffile;
}
}
</code>```

Hope this helps!

Title: Opening PDF from android App

Body:
I am using custom class for opening PDF from my android application. It checks whether PDF is already downloaded and then open PDF using existing PDF Viewer application. If there is no pdf viewer application then it tries to open pdf using google docs.

The class was working fine till the upgrade of Android Studio 2.2.3 to 2.3.2 and Build Tool Version from 24 to 25. The target SDK is still API 24. Unable to figure out exact root cause of the issue.

PDF Class :

public class PDFTools {
private static final String GOOGLE_DRIVE_PDF_READER_PREFIX = "http://docs.google.com/viewer?url=";
private static final String PDF_MIME_TYPE = "application/pdf";
private static final String HTML_MIME_TYPE = "text/html";

/**
 * If a PDF reader is installed, download the PDF file and open it in a reader.
 * Otherwise ask the user if he/she wants to view it in the Google Drive online PDF reader.

 *

 * BEWARE: This method
 * @param context
 * @param pdfUrl
 * @return
 */
public static void showPDFUrl( final Context context, final String pdfUrl ) {
    if ( isPDFSupported( context ) ) {
        downloadAndOpenPDF(context, pdfUrl);
    } else {
        askToOpenPDFThroughGoogleDrive( context, pdfUrl );
    }
}

/**
 * Downloads a PDF with the Android DownloadManager and opens it with an installed PDF reader app.
 * @param context
 * @param pdfUrl
 */

public static void downloadAndOpenPDF(final Context context, final String pdfUrl) {
    // Get filename
    final String filename = pdfUrl.substring( pdfUrl.lastIndexOf( "/" ) + 1 );
    // The place where the downloaded PDF file will be put
    final File tempFile = new File( context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), filename );
    if ( tempFile.exists() ) {
        // If we have downloaded the file before, just go ahead and show it.
        Uri uri = null;
        File docPath = new File(context.getExternalFilesDir(null), "Download");
        File newFile = new File(docPath, filename);

        uri = FileProvider.getUriForFile( context, BuildConfig.APPLICATION_ID + ".provider", newFile );

        openPDF( context, uri);
        return;
    }

    // Show progress dialog while downloading
    final ProgressDialog progress = ProgressDialog.show( context, context.getString( R.string.pdf_show_local_progress_title ),
            context.getString( R.string.message_please_wait ), true );

    // Create the download request
    DownloadManager.Request r = new DownloadManager.Request( Uri.parse( pdfUrl ) );
    r.setDestinationInExternalFilesDir( context, Environment.DIRECTORY_DOWNLOADS, filename );
    final DownloadManager dm = (DownloadManager) context.getSystemService( Context.DOWNLOAD_SERVICE );
    BroadcastReceiver onComplete = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if ( !progress.isShowing() ) {
                return;
            }
            context.unregisterReceiver( this );

            progress.dismiss();
            long downloadId = intent.getLongExtra( DownloadManager.EXTRA_DOWNLOAD_ID, -1 );
            Cursor c = dm.query( new DownloadManager.Query().setFilterById( downloadId ) );

            if ( c.moveToFirst() ) {
                int status = c.getInt( c.getColumnIndex( DownloadManager.COLUMN_STATUS ) );
                if ( status == DownloadManager.STATUS_SUCCESSFUL ) {
                    Uri uri = null;
                    try {
                        uri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", tempFile );

                    }catch (IllegalArgumentException iae) {
                        iae.printStackTrace();
                    }
                    if (uri !=null) {
                        openPDF(context, uri);
                    }
                }
            }
            c.close();
        }
    };
    context.registerReceiver( onComplete, new IntentFilter( DownloadManager.ACTION_DOWNLOAD_COMPLETE ) );

    // Enqueue the request
    dm.enqueue( r );
}

/**
 * Show a dialog asking the user if he wants to open the PDF through Google Drive
 * @param context
 * @param pdfUrl
 */
public static void askToOpenPDFThroughGoogleDrive( final Context context, final String pdfUrl ) {
    new AlertDialog.Builder( context )
            .setTitle( R.string.pdf_show_online_dialog_title )
            .setMessage( R.string.pdf_show_online_dialog_question )
            .setNegativeButton( R.string.pdf_show_online_dialog_button_no, null )
            .setPositiveButton( R.string.pdf_show_online_dialog_button_yes, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    openPDFThroughGoogleDrive(context, pdfUrl);
                }
            })
            .show();
}

/**
 * Launches a browser to view the PDF through Google Drive
 * @param context
 * @param pdfUrl
 */
public static void openPDFThroughGoogleDrive(final Context context, final String pdfUrl) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    i.setDataAndType(Uri.parse(GOOGLE_DRIVE_PDF_READER_PREFIX + pdfUrl ), HTML_MIME_TYPE );
    context.startActivity( i );
}
/**
 * Open a local PDF file with an installed reader
 * @param context
 * @param localUri
 */
public static final void openPDF(Context context, Uri localUri ) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    i.setDataAndType( localUri, PDF_MIME_TYPE );
    context.startActivity( i );
}
/**
 * Checks if any apps are installed that supports reading of PDF files.
 * @param context
 * @return
 */
public static boolean isPDFSupported( Context context ) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    final File tempFile = new File( context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "test.pdf" );
    i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    i.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    try {
        i.setDataAndType( FileProvider.getUriForFile( context, BuildConfig.APPLICATION_ID + ".provider" ,tempFile ), PDF_MIME_TYPE );
    }catch (IllegalArgumentException iae ) {
    }
    return context.getPackageManager().queryIntentActivities( i, PackageManager.MATCH_DEFAULT_ONLY ).size() > 0;
}

}

It throws an error as

java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/emulated/0/Android/data/<PACKAGE>/files/Download/javascript_pdf_version.pdf

I have taken this sample from stack overflow itself. Appreciate your help on this.

Body:
Try something like this to download:

WebService using RestTemplate:

public PdfByteArrayObject getPrintjob(String empId) {
    PdfByteArrayObject pdfByteArrayObject = null;
    try {
        getUrl();
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

        pdfByteArrayObject = restTemplate.getForObject("pdfURL" + empId, PdfByteArrayObject.class);

    } catch (Exception e) {
      e.printStackTrace();
      Log.e("webser======", e.toString());
    }
    return pdfByteArrayObject;
}

The getUrl method(for File conversion & storage):

public void getUrl() {
    StringBuffer stringBuffer = new StringBuffer();
    String aDataRow = "";
    String aBuffer = "";
    try {
        File serverPath = new File(Environment.getExternalStorageDirectory(), "ServerUrl");

        if (serverPath.exists()) {
            FileInputStream fIn = new FileInputStream(serverPath);
            BufferedReader myReader = new BufferedReader(
                    new InputStreamReader(fIn));

            while ((aDataRow = myReader.readLine()) != null) {
                aBuffer += aDataRow;
            }
            RestUrl = aBuffer;
            Log.e("RestUrl", RestUrl + "--");
            myReader.close();
        } else {
            Log.e("RestUrl", "File not found");
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
    // Toast.makeText(getApplicationContext(),aBuffer,Toast.LENGTH_LONG).show();
}

And the object:

public class PdfByteArrayObject {

private byte[] pdffile;

public byte[] getPdffile() {
    return pdffile;
}

public void setPdffile(byte[] pdffile) {
    this.pdffile = pdffile;
}
}

Hope this helps!


来源: stackexchange

问:
How to add watermark image in laravel 5.2 in intervention package?
I am using laravel 5.2 framework and i am using intervention package of laravel that runs fine for me. Now here i face one problem i don't know what i amd doing wrong. Please help:-

```<code>$myimage = Image::make(storage_path('app/images/test1.jpg'));
//Suppose $imyimage width is 3024 and height is 2016
$actualwidth = 3024;
$actualheight = 2016;
</code>```

Now, when i tried these sizes 3024 * 2016 pixel then watermark is not visible while when i zoom the image then it is visible
Now suppose i have width and height 1600*1027 pixel it shows me right in  center without zooming
I want want watermark in center in 3024*2016 pixel or any pixel with zooming the image.

```<code>$watermarkHeight =  Image::make(storage_path('watermark.png'))->height();
$watermarkWidth =  Image::make(storage_path('watermark.png'))->width();
$x = ($actualwidth - $watermarkWidth) / 2;
$y = ($actualheight - $watermarkHeight) / 2;
$img = Image::make(storage_path('app/images/test1.jpg'));
$img->insert(storage_path('watermark.png'), 'center',round($x),round($y));
$img->resize($actualwidth,$actualheight)->save(storage_path('app/images/watermark-test.jpg'));
</code>```

Please Help me what i am doing wrong . Thanks in advance :)

答:
If I understood right your question, here is solution (not tested)</p>

```<code>$watermark =  Image::make(storage_path('watermark.png'));
$img = Image::make(storage_path('app/images/test1.jpg'));
//#1
$watermarkSize = $img->width() - 20; //size of the image minus 20 margins
//#2
$watermarkSize = $img->width() / 2; //half of the image size
//#3
$resizePercentage = 70;//70% less then an actual image (play with this value)
$watermarkSize = round($img->width() * ((100 - $resizePercentage) / 100), 2); //watermark will be $resizePercentage less then the actual width of the image

// resize watermark width keep height auto
$watermark->resize($watermarkSize, null, function ($constraint) {
    $constraint->aspectRatio();
});
//insert resized watermark to image center aligned
$img->insert($watermark, 'center');
//save new image
$img->save(storage_path('app/images/watermark-test.jpg'));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using laravel 5.2 framework and i am using intervention package of laravel that runs fine for me. Now here i face one problem i don't know what i amd doing wrong. Please help:-

$myimage = Image::make(storage_path('app/images/test1.jpg'));
//Suppose $imyimage width is 3024 and height is 2016
$actualwidth = 3024;
$actualheight = 2016;

Now, when i tried these sizes 3024 * 2016 pixel then watermark is not visible while when i zoom the image then it is visible
Now suppose i have width and height 1600*1027 pixel it shows me right in  center without zooming
I want want watermark in center in 3024*2016 pixel or any pixel with zooming the image.

$watermarkHeight =  Image::make(storage_path('watermark.png'))->height();
$watermarkWidth =  Image::make(storage_path('watermark.png'))->width();
$x = ($actualwidth - $watermarkWidth) / 2;
$y = ($actualheight - $watermarkHeight) / 2;
$img = Image::make(storage_path('app/images/test1.jpg'));
$img->insert(storage_path('watermark.png'), 'center',round($x),round($y));
$img->resize($actualwidth,$actualheight)->save(storage_path('app/images/watermark-test.jpg'));

Please Help me what i am doing wrong . Thanks in advance :)

Body:
If I understood right your question, here is solution (not tested)

$watermark =  Image::make(storage_path('watermark.png'));
$img = Image::make(storage_path('app/images/test1.jpg'));
//#1
$watermarkSize = $img->width() - 20; //size of the image minus 20 margins
//#2
$watermarkSize = $img->width() / 2; //half of the image size
//#3
$resizePercentage = 70;//70% less then an actual image (play with this value)
$watermarkSize = round($img->width() * ((100 - $resizePercentage) / 100), 2); //watermark will be $resizePercentage less then the actual width of the image

// resize watermark width keep height auto
$watermark->resize($watermarkSize, null, function ($constraint) {
    $constraint->aspectRatio();
});
//insert resized watermark to image center aligned
$img->insert($watermark, 'center');
//save new image
$img->save(storage_path('app/images/watermark-test.jpg'));


问:
While using the YouTube api, the loadvideo function wont work unless I alert the video id first
```<code>function playPlaylist(trackstemp) {
    trackstemp = trackstemp.split(' ');
    for (i=0; i < trackstemp.length; i++){
        tracks[i] = trackstemp[i];
    }
    numoftracks = tracks.length - 1;
    currenttrack = 0;
    loadNewVideo(tracks[currenttrack])
}

function loadNewVideo(id) {
ytplayerid.loadVideoById(id, 0);
}
</code>```

I have a prev() and next() function that work just fine by calling loadNewVideo(tracks[currenttrack]), but the initial video only works if I alert(id) within the loadNewVideo() function.

Any clue to why this is happening?

答:
Are you using onYouTubePlayerReady which tells you when the player is ready?</p>

```<code>function onYouTubePlayerReady(){
    //Call you first track here
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
function playPlaylist(trackstemp) {
    trackstemp = trackstemp.split(' ');
    for (i=0; i < trackstemp.length; i++){
        tracks[i] = trackstemp[i];
    }
    numoftracks = tracks.length - 1;
    currenttrack = 0;
    loadNewVideo(tracks[currenttrack])
}

function loadNewVideo(id) {
ytplayerid.loadVideoById(id, 0);
}

I have a prev() and next() function that work just fine by calling loadNewVideo(tracks[currenttrack]), but the initial video only works if I alert(id) within the loadNewVideo() function.

Any clue to why this is happening?

Body:
Are you using onYouTubePlayerReady which tells you when the player is ready?

function onYouTubePlayerReady(){
    //Call you first track here
}


问:
don't want whitespace to occur when text is too long and i got to enter
Is there any way when your text is too long - and you break it up with new lines - to not have whitespace happen? What I need is three values to be joint without whitespace in between.

```<code><div style='font-size:100%; color:blue'>
    {{ $record->m_pk_address_line1 }}
    {{ $record->m_pk_address_line2 }}
    {{ $record->m_pk_address_line3 }}
</div>
</code>```

Without entering new line, it'll be too long even if they can be joined together.

```<code><div style='font-size:100%; color:blue'>{{ $record->m_pk_address_line1 }}{{ $record->m_pk_address_line2 }}{{ $record->m_pk_address_line3 }}</div>
</code>```

Is there no standard way of going about this without resorting to tricks? What do people do when their code is too long and they need to break it up into new lines but they don't want the whitespace that comes with it?

答:
you have two tricks to avoid whitespace, the first is html comments:

```<code><div style='font-size:100%; color:blue'>
     {{ $record->m_pk_address_line1 }}<!--
  -->{{ $record->m_pk_address_line2 }}<!--
  -->{{ $record->m_pk_address_line3 }}
</div>
</code>```

the second is font-size: 0

```<code>.container {
  font-size: 0;
}
.container > * {
  font-size: 1rem; /** or whatever suits your needs **/
}
</code>```

Body:
Is there any way when your text is too long - and you break it up with new lines - to not have whitespace happen? What I need is three values to be joint without whitespace in between.

    {{ $record->m_pk_address_line1 }}
    {{ $record->m_pk_address_line2 }}
    {{ $record->m_pk_address_line3 }}

Without entering new line, it'll be too long even if they can be joined together.

{{ $record->m_pk_address_line1 }}{{ $record->m_pk_address_line2 }}{{ $record->m_pk_address_line3 }}

Is there no standard way of going about this without resorting to tricks? What do people do when their code is too long and they need to break it up into new lines but they don't want the whitespace that comes with it?

Body:
you have two tricks to avoid whitespace, the first is html comments:

<div style='font-size:100%; color:blue'>
     {{ $record->m_pk_address_line1 }}<!--
  -->{{ $record->m_pk_address_line2 }}<!--
  -->{{ $record->m_pk_address_line3 }}
</div>

the second is font-size: 0

.container {
  font-size: 0;
}
.container > * {
  font-size: 1rem; /** or whatever suits your needs **/
}


问:
Including csrf token in a post request from react-native app
I have a react native app that posts and gets data from a remote server. In post, i need to include csrf token to avoid token mismatch errors. This is the backend laravel method

```<code>//Android Login
    public function androidLogin(){

      return response()->json([
        'name' => 'Android Login',
        'route' => 'androidLogin'
            ]);
    }
</code>```

This is the react native code(i have stripped out error catching code).

```<code>async handleSubmit(){
  var me = this.state.message;
  console.log('this connected',me);

      let response = await fetch('http://not-brusselus.be/androidLogin', {
                              method: 'POST',
                              headers: {
                                'Accept': 'application/json',
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN':'csrf_field()'
                              },
                              body: JSON.stringify({
                                session:{
                                  email: 'chesterfield@gmail.com',
                                  password: '123456',
                                }
                              })
                            });
      //let res = await response.text();
      if (true) {
         console.log(response);
      } else {
          //Handle error
          //let error = res;
          //throw error;
      }

  }
</code>```

The response shows laravel's token mismatch page. How can i send the csrf token successfully?.

答:
Hang the CSRF token off of the window as defined in your main laravel layout file:

```<code>window.Laravel = {
    csrfToken: '{{csrf_token()}}'
}
</code>```

Then just use that in your javascript requests:

```<code>...window.Laravel.csrfToken
</code>```

Edit

To the downvoter: This is literally how Laravel does it out of the box and recommends you do it as well.

Body:
I have a react native app that posts and gets data from a remote server. In post, i need to include csrf token to avoid token mismatch errors. This is the backend laravel method

//Android Login
    public function androidLogin(){

      return response()->json([
        'name' => 'Android Login',
        'route' => 'androidLogin'
            ]);
    }

This is the react native code(i have stripped out error catching code).

async handleSubmit(){
  var me = this.state.message;
  console.log('this connected',me);

      let response = await fetch('http://not-brusselus.be/androidLogin', {
                              method: 'POST',
                              headers: {
                                'Accept': 'application/json',
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN':'csrf_field()'
                              },
                              body: JSON.stringify({
                                session:{
                                  email: 'chesterfield@gmail.com',
                                  password: '123456',
                                }
                              })
                            });
      //let res = await response.text();
      if (true) {
         console.log(response);
      } else {
          //Handle error
          //let error = res;
          //throw error;
      }

  }

The response shows laravel's token mismatch page. How can i send the csrf token successfully?.

Body:
Hang the CSRF token off of the window as defined in your main laravel layout file:

window.Laravel = {
    csrfToken: '{{csrf_token()}}'
}

Then just use that in your javascript requests:

...window.Laravel.csrfToken

Edit

To the downvoter: This is literally how Laravel does it out of the box and recommends you do it as well.


问:
Parse log file using grep or awk
I have a log file. Example of output looks like this:

...
10-MAY-95 14:16:21*(CONNECT_DATA=(SID=reltest)(CID=(PROGRAM=C:\ORAWIN\BIN\PLUS31.EXE) (HOST=WINDOWSPC)(USER=CCLOW))*(ADDRESS=(PROTOCOL=tcp)(HOST=144.25.23.246)(PORT=3366))*establish*reltest*0
...

Log parameters are entered in the appropriate component configuration files in the form:
log_parameter_component = value

So, goal is to parse the above output and display result only with key=value, key=value, etc:
log_parameter_component = value, log_parameter_component = value, etc.

The result should look as following after parsing:

...
SID=reltest, USER=CCLOW, HOST=144.25.23.246
...

How to solve this task?

答:
Found very close soulution.

But, how script will be look like if I want to add some additional patterns? If I will use awk script?
Ex. only for: SID, USER, SERVER, HOST.

Title: Parse log file using grep or awk


问:
Pagination functionality in laravel, Issue: Call to a member function paginate() on array
Laravel Framework - using version 5.4: If I used raw query as shown below in User.php controller and making paginate(3) as shown below. But it is giving error as "Call to a member function paginate() on array". solution please.</p>

```<code>DB::select("select u.email,u.name,u.created_at from users u where u.id in (select max(ui.id) from users ui where ui.status = 0) order by ui.id desc")->paginate(3);
</code>```

答:
yeah because your query ain't returning an object its returning an array. Try to use laravel query builder or Eloquent.

```<code>$users = DB::table('users')->paginate(15); //query builder example
$users = User::where('votes', '>', 100)->paginate(15); //eloquent example
</code>```

Also make sure your query is working fine.

Body:
Laravel Framework - using version 5.4: If I used raw query as shown below in User.php controller and making paginate(3) as shown below. But it is giving error as "Call to a member function paginate() on array". solution please.

DB::select("select u.email,u.name,u.created_at from users u where u.id in (select max(ui.id) from users ui where ui.status = 0) order by ui.id desc")->paginate(3);

Body:
yeah because your query ain't returning an object its returning an array. Try to use laravel query builder or Eloquent.

$users = DB::table('users')->paginate(15); //query builder example
$users = User::where('votes', '>', 100)->paginate(15); //eloquent example

Also make sure your query is working fine.


问:
I Insert values in stock.picking move_lines but after click on save it Error The Following fields are in valid stock.move in odoo10
This button

```<code>                        <span class="o_stat_value"><field name="test_field"/>Material Out</span>
</code>```

```<code>class SkylineJobOrder(models.Model):
    _name = 'skyline.job.order'
    _inherit = 'purchase.order'

    @api.multi
    def action_workorder_out(self):
        x = 0
        """ This opens the xml view specified in xml_id for the current Work Order in Manufacturing """
        self.ensure_one()
        xml_id = self.env.context.get('xml_id')
        if xml_id:
            res = self.env['ir.actions.act_window'].for_xml_id('stock', xml_id)
            production = self.env['mrp.production'].search([('product_id','=',self.product_id.id)])
            for item in production:

                x = item.bom_id.id
            bomline = self.env['mrp.bom.line'].search([('bom_id','=',x)])
            for record in bomline:

                res.update(
                    context={'default_states':'draft','default_partner_id': self.partner_id.id,'default_move_lines': [(0,0, {'address_in_id':self.partner_id.id,'product_id':record.product_id.id,'product_uom': record.product_uom_id.id,'product_uom_qty':record.product_qty,'scrapped':False,'state':'draft','picking_id':False,'name': 'test','procurement_id': record.operation_id.id,'split_from': self.id,'no_open': True,'no_create':True,'availability':1,'location_dest_id':8,'picking_id':35})]}
                )

            print res
            return res
        return False
</code>```

I inherit purchase.order and create a button and put action of
  stock.picking . The working of button is to stockout the values of raw
  material of product .so when click on save button is shows that the
  following fields are invalid stock.move.

答:
Blockquote
  value inserted form bom.line.ids to stock.move through stock.picking using picking_id, location_id,lication_dest_id and 'purchase=ok, in purchase_id.

Body:
This button

                        <field name="test_field"/>Material Out

class SkylineJobOrder(models.Model):
    _name = 'skyline.job.order'
    _inherit = 'purchase.order'

    @api.multi
    def action_workorder_out(self):
        x = 0
        """ This opens the xml view specified in xml_id for the current Work Order in Manufacturing """
        self.ensure_one()
        xml_id = self.env.context.get('xml_id')
        if xml_id:
            res = self.env['ir.actions.act_window'].for_xml_id('stock', xml_id)
            production = self.env['mrp.production'].search([('product_id','=',self.product_id.id)])
            for item in production:

                x = item.bom_id.id
            bomline = self.env['mrp.bom.line'].search([('bom_id','=',x)])
            for record in bomline:

                res.update(
                    context={'default_states':'draft','default_partner_id': self.partner_id.id,'default_move_lines': [(0,0, {'address_in_id':self.partner_id.id,'product_id':record.product_id.id,'product_uom': record.product_uom_id.id,'product_uom_qty':record.product_qty,'scrapped':False,'state':'draft','picking_id':False,'name': 'test','procurement_id': record.operation_id.id,'split_from': self.id,'no_open': True,'no_create':True,'availability':1,'location_dest_id':8,'picking_id':35})]}
                )

            print res
            return res
        return False

I inherit purchase.order and create a button and put action of
  stock.picking . The working of button is to stockout the values of raw
  material of product .so when click on save button is shows that the
  following fields are invalid stock.move.


问:
Sort Results in Mysql Asc
I have a database with this table:

Id (autogenerate)

Zipcode

Price

Adress

City

Date of sale(from 2017-2010)

The search is by zipcode
Now the ouput result is generate by mysql..I want the results order by date of sale:
 2017,2016,2015,2014...2010

My query is :

//query the database
      $resultSet = $mysqli->query("SELECT * FROM land_data WHERE ZipCode LIKE '%$search%'LIMIT 0,30");

Thanks

答:
You need to add something like this to your SQL Query: </p>

```<code>ORDER BY Name, Sale_Date DESC
</code>```

Title: Sort Results in Mysql Asc

Body:
You need to add something like this to your SQL Query:

ORDER BY Name, Sale_Date DESC


问:
Not able to Generate more than one graph in jquery using for loop
I am not able to generate more than one graph(flot chart) dynamically using for loop in jquery. it's generated only one chart . I mentioned the code below.

```<code>datedealsdata = "Any data "
for(i=0;i<3;i++){
    $('#head').html('<div class="leadConvCycle'+i+'"></div>')
    var datedataset = [{ data: datedealsdata, color: "#21abf6" }];
    $.plot($(".leadConvCycle"+i), datedataset, options);
    $(".leadConvCycle"+i).UseTooltip();
}
</code>```

html code:

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

答:
Try this

```<code>datedealsdata = "Any data "
for(i = 0; i < 3; i++) {
   var datedataset = [{ data: datedealsdata, color: "#21abf6" }];
   var ele = $(".leadConvCycle"+i);
   generateGraph(ele);
}
function generateGraph(ele) {
    $.plot(ele, datedataset, options);
    ele.UseTooltip();
}
</code>```

See working example like this

Body:
I am not able to generate more than one graph(flot chart) dynamically using for loop in jquery. it's generated only one chart . I mentioned the code below.

datedealsdata = "Any data "
for(i=0;i<3;i++){
    $('#head').html('

')
    var datedataset = [{ data: datedealsdata, color: "#21abf6" }];
    $.plot($(".leadConvCycle"+i), datedataset, options);
    $(".leadConvCycle"+i).UseTooltip();
}

html code:

Body:
Try this

datedealsdata = "Any data "
for(i = 0; i < 3; i++) {
   var datedataset = [{ data: datedealsdata, color: "#21abf6" }];
   var ele = $(".leadConvCycle"+i);
   generateGraph(ele);
}
function generateGraph(ele) {
    $.plot(ele, datedataset, options);
    ele.UseTooltip();
}

See working example like this


问:
CSS - Line height property, how it works (simple)
So in this simple example I have as final result:

This is a very simple question but I simply can't get my head around it.

To achieve the vertical centering of the numbers I used:

```<code>line-height:100px;
</code>```

Which works great and have been doing it trial and error basis.

My question is specifically why the line-height:50px; just gets if half of the way.

If the small div has a height of 100px and I an positioning relative to it, shouldn't the half of it center it to the half.

This specially puzzles me since, when I center a div:

I would use: margin:50px 0 0 50px; to get this:

I realize this question might be an overkill since the answer might be (probably will be very simple), so sorry! but I guess it is better the "why doesn't this work" questions ;)

Thanks in advance!!

答: This doesn't work because line-height is specific to text and not to actual heights of elements like divs. I would suggest using height and not line-height when your subject is not in fact text.</p>

Body:
So in this simple example I have as final result:

This is a very simple question but I simply can't get my head around it.

To achieve the vertical centering of the numbers I used:

line-height:100px;

Which works great and have been doing it trial and error basis.

My question is specifically why the line-height:50px; just gets if half of the way.

If the small div has a height of 100px and I an positioning relative to it, shouldn't the half of it center it to the half.

This specially puzzles me since, when I center a div:

I would use: margin:50px 0 0 50px; to get this:

I realize this question might be an overkill since the answer might be (probably will be very simple), so sorry! but I guess it is better the "why doesn't this work" questions ;)

Thanks in advance!!


问:
Horizontally Placed Equal Width Equal Horizontal Space Buttons With Auto Layout
I have written the following code to achieve

Horizontally spaced equal width fixed height equal horizontal spaced three button but somehow it's not working fine. Can anyone rectify this ?

```<code>UIButton *cancelBtn = [UIButton new];

cancelBtn.frame = CGRectMake(10, 5, (popupView.bounds.size.width-40)/3, 30);

[cancelBtn setTitle:@"Cancel" forState:UIControlStateNormal];

[cancelBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];

[cancelBtn setBackgroundColor:[UIColor lightGrayColor]];

[popupView addSubview:cancelBtn];

UIButton *resetBtn = [UIButton new];

resetBtn.frame = CGRectMake(cancelBtn.frame.origin.x+cancelBtn.bounds.size.width+10, 5, (popupView.bounds.size.width-40)/3, 30);

[resetBtn setTitle:@"Reset" forState:UIControlStateNormal];

[resetBtn setTitleColor:[UIColor yellowColor] forState:UIControlStateNormal];

[resetBtn setBackgroundColor:[UIColor darkGrayColor]];

[popupView addSubview:resetBtn];

UIButton *doneBtn = [UIButton new];

doneBtn.frame = CGRectMake(popupView.bounds.size.width-10-((popupView.bounds.size.width-40)/3), 5, (popupView.bounds.size.width-40)/3, 30);

[doneBtn setTitle:@"Done" forState:UIControlStateNormal];

[doneBtn setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];

[doneBtn setBackgroundColor:[UIColor blackColor]];

[popupView addSubview:doneBtn];

cancelBtn.translatesAutoresizingMaskIntoConstraints = NO;

[cancelBtn addConstraint:[NSLayoutConstraint constraintWithItem:cancelBtn attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1 constant:30]];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:cancelBtn attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:popupView attribute:NSLayoutAttributeTop multiplier:1.0f constant:5.0f] ];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:cancelBtn attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:popupView attribute:NSLayoutAttributeLeft multiplier:1.0f constant:10.0f]];
 resetBtn.translatesAutoresizingMaskIntoConstraints = NO;

[resetBtn addConstraint:[NSLayoutConstraint constraintWithItem:resetBtn attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1 constant:30]];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:resetBtn attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:popupView attribute:NSLayoutAttributeTop multiplier:1.0f constant:5.0f] ];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:cancelBtn attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:resetBtn attribute:NSLayoutAttributeLeft multiplier:1.0f constant:10.0f]];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:doneBtn attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:resetBtn attribute:NSLayoutAttributeRight multiplier:1.0f constant:-10.0f]];

doneBtn.translatesAutoresizingMaskIntoConstraints = NO;

[doneBtn addConstraint:[NSLayoutConstraint constraintWithItem:doneBtn attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1 constant:30]];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:doneBtn attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:popupView attribute:NSLayoutAttributeTop multiplier:1.0f constant:5.0f] ];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:doneBtn attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:popupView attribute:NSLayoutAttributeRight multiplier:1.0f constant:-10.0f]];
[popupView addConstraint:[NSLayoutConstraint     constraintWithItem:cancelBtn attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:resetBtn attribute:NSLayoutAttributeWidth multiplier:1 constant:0]];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:resetBtn attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:doneBtn attribute:NSLayoutAttributeWidth multiplier:1 constant:0]];
</code>```

How to fix this ?

I want to achieve a popup like this.

enter image description here

答:
SOLVED ! Fixed it.

```<code>UIButton *cancelBtn = [UIButton new];

cancelBtn.frame = CGRectMake(10, 5, (popupView.bounds.size.width-40)/3, 30);

[cancelBtn setTitle:@"Cancel" forState:UIControlStateNormal];

[cancelBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];

[cancelBtn setBackgroundColor:[UIColor lightGrayColor]];

[popupView addSubview:cancelBtn];

UIButton *resetBtn = [UIButton new];

resetBtn.frame = CGRectMake(cancelBtn.frame.origin.x+cancelBtn.bounds.size.width+10, 5, (popupView.bounds.size.width-40)/3, 30);

[resetBtn setTitle:@"Reset" forState:UIControlStateNormal];

[resetBtn setTitleColor:[UIColor yellowColor] forState:UIControlStateNormal];

[resetBtn setBackgroundColor:[UIColor darkGrayColor]];

[popupView addSubview:resetBtn];

UIButton *doneBtn = [UIButton new];

doneBtn.frame = CGRectMake(resetBtn.frame.origin.x+resetBtn.bounds.size.width+10, 5, (popupView.bounds.size.width-40)/3, 30);

[doneBtn setTitle:@"Done" forState:UIControlStateNormal];

[doneBtn setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];

[doneBtn setBackgroundColor:[UIColor blackColor]];

[popupView addSubview:doneBtn];

cancelBtn.translatesAutoresizingMaskIntoConstraints = NO;

[cancelBtn addConstraint:[NSLayoutConstraint constraintWithItem:cancelBtn attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1 constant:30]];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:cancelBtn attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:popupView attribute:NSLayoutAttributeTop multiplier:1.0f constant:5.0f] ];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:cancelBtn attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:popupView attribute:NSLayoutAttributeLeading multiplier:1.0f constant:10.0f]];

resetBtn.translatesAutoresizingMaskIntoConstraints = NO;

[resetBtn addConstraint:[NSLayoutConstraint constraintWithItem:resetBtn attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1 constant:30]];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:resetBtn attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:popupView attribute:NSLayoutAttributeTop multiplier:1.0f constant:5.0f] ];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:resetBtn attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:cancelBtn attribute:NSLayoutAttributeRight multiplier:1.0f constant:10.0f]];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:resetBtn attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:doneBtn attribute:NSLayoutAttributeLeft multiplier:1.0f constant:-10.0f]];

 doneBtn.translatesAutoresizingMaskIntoConstraints = NO;

[doneBtn addConstraint:[NSLayoutConstraint constraintWithItem:doneBtn attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1 constant:30]];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:doneBtn attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:popupView attribute:NSLayoutAttributeTop multiplier:1.0f constant:5.0f] ];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:doneBtn attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:popupView attribute:NSLayoutAttributeTrailing multiplier:1.0f constant:-10.0f]];
</code>```

// +++++++ Equal width constraints +++++++

```<code>[popupView addConstraint:[NSLayoutConstraint constraintWithItem:cancelBtn attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:resetBtn attribute:NSLayoutAttributeWidth multiplier:1.0f constant:0]];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:resetBtn attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:doneBtn attribute:NSLayoutAttributeWidth multiplier:1.0f constant:0]];
</code>```

Body:
I have written the following code to achieve

Horizontally spaced equal width fixed height equal horizontal spaced three button but somehow it's not working fine. Can anyone rectify this ?

UIButton *cancelBtn = [UIButton new];

cancelBtn.frame = CGRectMake(10, 5, (popupView.bounds.size.width-40)/3, 30);

[cancelBtn setTitle:@"Cancel" forState:UIControlStateNormal];

[cancelBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];

[cancelBtn setBackgroundColor:[UIColor lightGrayColor]];

[popupView addSubview:cancelBtn];

UIButton *resetBtn = [UIButton new];

resetBtn.frame = CGRectMake(cancelBtn.frame.origin.x+cancelBtn.bounds.size.width+10, 5, (popupView.bounds.size.width-40)/3, 30);

[resetBtn setTitle:@"Reset" forState:UIControlStateNormal];

[resetBtn setTitleColor:[UIColor yellowColor] forState:UIControlStateNormal];

[resetBtn setBackgroundColor:[UIColor darkGrayColor]];

[popupView addSubview:resetBtn];

UIButton *doneBtn = [UIButton new];

doneBtn.frame = CGRectMake(popupView.bounds.size.width-10-((popupView.bounds.size.width-40)/3), 5, (popupView.bounds.size.width-40)/3, 30);

[doneBtn setTitle:@"Done" forState:UIControlStateNormal];

[doneBtn setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];

[doneBtn setBackgroundColor:[UIColor blackColor]];

[popupView addSubview:doneBtn];

cancelBtn.translatesAutoresizingMaskIntoConstraints = NO;

[cancelBtn addConstraint:[NSLayoutConstraint constraintWithItem:cancelBtn attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1 constant:30]];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:cancelBtn attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:popupView attribute:NSLayoutAttributeTop multiplier:1.0f constant:5.0f] ];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:cancelBtn attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:popupView attribute:NSLayoutAttributeLeft multiplier:1.0f constant:10.0f]];
 resetBtn.translatesAutoresizingMaskIntoConstraints = NO;

[resetBtn addConstraint:[NSLayoutConstraint constraintWithItem:resetBtn attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1 constant:30]];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:resetBtn attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:popupView attribute:NSLayoutAttributeTop multiplier:1.0f constant:5.0f] ];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:cancelBtn attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:resetBtn attribute:NSLayoutAttributeLeft multiplier:1.0f constant:10.0f]];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:doneBtn attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:resetBtn attribute:NSLayoutAttributeRight multiplier:1.0f constant:-10.0f]];

doneBtn.translatesAutoresizingMaskIntoConstraints = NO;

[doneBtn addConstraint:[NSLayoutConstraint constraintWithItem:doneBtn attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1 constant:30]];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:doneBtn attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:popupView attribute:NSLayoutAttributeTop multiplier:1.0f constant:5.0f] ];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:doneBtn attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:popupView attribute:NSLayoutAttributeRight multiplier:1.0f constant:-10.0f]];
[popupView addConstraint:[NSLayoutConstraint     constraintWithItem:cancelBtn attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:resetBtn attribute:NSLayoutAttributeWidth multiplier:1 constant:0]];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:resetBtn attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:doneBtn attribute:NSLayoutAttributeWidth multiplier:1 constant:0]];

How to fix this ?

I want to achieve a popup like this.

enter image description here

Body:
SOLVED ! Fixed it.

UIButton *cancelBtn = [UIButton new];

cancelBtn.frame = CGRectMake(10, 5, (popupView.bounds.size.width-40)/3, 30);

[cancelBtn setTitle:@"Cancel" forState:UIControlStateNormal];

[cancelBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];

[cancelBtn setBackgroundColor:[UIColor lightGrayColor]];

[popupView addSubview:cancelBtn];

UIButton *resetBtn = [UIButton new];

resetBtn.frame = CGRectMake(cancelBtn.frame.origin.x+cancelBtn.bounds.size.width+10, 5, (popupView.bounds.size.width-40)/3, 30);

[resetBtn setTitle:@"Reset" forState:UIControlStateNormal];

[resetBtn setTitleColor:[UIColor yellowColor] forState:UIControlStateNormal];

[resetBtn setBackgroundColor:[UIColor darkGrayColor]];

[popupView addSubview:resetBtn];

UIButton *doneBtn = [UIButton new];

doneBtn.frame = CGRectMake(resetBtn.frame.origin.x+resetBtn.bounds.size.width+10, 5, (popupView.bounds.size.width-40)/3, 30);

[doneBtn setTitle:@"Done" forState:UIControlStateNormal];

[doneBtn setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];

[doneBtn setBackgroundColor:[UIColor blackColor]];

[popupView addSubview:doneBtn];

cancelBtn.translatesAutoresizingMaskIntoConstraints = NO;

[cancelBtn addConstraint:[NSLayoutConstraint constraintWithItem:cancelBtn attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1 constant:30]];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:cancelBtn attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:popupView attribute:NSLayoutAttributeTop multiplier:1.0f constant:5.0f] ];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:cancelBtn attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:popupView attribute:NSLayoutAttributeLeading multiplier:1.0f constant:10.0f]];

resetBtn.translatesAutoresizingMaskIntoConstraints = NO;

[resetBtn addConstraint:[NSLayoutConstraint constraintWithItem:resetBtn attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1 constant:30]];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:resetBtn attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:popupView attribute:NSLayoutAttributeTop multiplier:1.0f constant:5.0f] ];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:resetBtn attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:cancelBtn attribute:NSLayoutAttributeRight multiplier:1.0f constant:10.0f]];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:resetBtn attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:doneBtn attribute:NSLayoutAttributeLeft multiplier:1.0f constant:-10.0f]];

 doneBtn.translatesAutoresizingMaskIntoConstraints = NO;

[doneBtn addConstraint:[NSLayoutConstraint constraintWithItem:doneBtn attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1 constant:30]];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:doneBtn attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:popupView attribute:NSLayoutAttributeTop multiplier:1.0f constant:5.0f] ];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:doneBtn attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:popupView attribute:NSLayoutAttributeTrailing multiplier:1.0f constant:-10.0f]];

// +++++++ Equal width constraints +++++++

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:cancelBtn attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:resetBtn attribute:NSLayoutAttributeWidth multiplier:1.0f constant:0]];

[popupView addConstraint:[NSLayoutConstraint constraintWithItem:resetBtn attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:doneBtn attribute:NSLayoutAttributeWidth multiplier:1.0f constant:0]];


问:
Dataweave Always output JSON number with two decimal places
I've got the following number coming through via xml in Dataweave.

```<code><b:AmountValue>180.90</b:AmountValue>
</code>```

Using Dataweave I am trying to output a corresponding json number with two decimal places (to represent currency).

Here is what my Dataweave expression looks like...

```<code>amount: $.AmountValue as :number as :string {format: ".00"} as :number
</code>```

The output json is losing the trailing zero.

```<code>i.e. "amount":180.9
</code>```

How can I change my Dataweave expression to always have two decimal places?

Or perhaps I'm misunderstanding the json number type?

thanks

答:
remote the last as :number if you can live with amount being a string

```<code>amount: $.AmountValue as :number as :string {format: ".00"}
</code>```

Body:
I've got the following number coming through via xml in Dataweave.

180.90

Using Dataweave I am trying to output a corresponding json number with two decimal places (to represent currency).

Here is what my Dataweave expression looks like...

amount: $.AmountValue as :number as :string {format: ".00"} as :number

The output json is losing the trailing zero.

i.e. "amount":180.9

How can I change my Dataweave expression to always have two decimal places?

Or perhaps I'm misunderstanding the json number type?

thanks

Body:
remote the last as :number if you can live with amount being a string

amount: $.AmountValue as :number as :string {format: ".00"}


问:
C# enum query linq and general type?
So I want to know that, from my enum value list, how many specific enum value exists.

So I wrote like

```<code>public int GetNumFromList(List<Elements> list, Elements eType)
{
    IEnumerable<Elements> query = //list.Where(p => p.GetType() == eType);
        from listchild in list
        where listchild == eType
        select listchild;
    /*
    Debug.Log("Cur check type is " + eType + " and now selected number is " + query.Count());
    if(query.Count() > 0)
        Debug.Log(" and query 0 value is "+ query.ToArray().GetValue(0) + " type is "+ query.ToArray().GetValue(0).GetType());
        */
    return query.Count();
}
  public enum Elements{Fire, Water, Wood, Metal, Earth, None}
</code>```

So this works well, but can I make this more shorter and neat?

```<code>//list.Where(p => p.GetType() == eType);  This part doesn't worked.
</code>```

And how can make this for generic type, T?

答:
This should work for enums and value types</p>

```<code>public int GetNumFromList<T>(List<T> list, T item)
{
    return list.Count(x => x.Equals(item));
}
</code>```

Title: C# enum query linq and general type?

Body:
So I want to know that, from my enum value list, how many specific enum value exists.

So I wrote like

public int GetNumFromList(List<Elements> list, Elements eType)
{
    IEnumerable<Elements> query = //list.Where(p => p.GetType() == eType);
        from listchild in list
        where listchild == eType
        select listchild;
    /*
    Debug.Log("Cur check type is " + eType + " and now selected number is " + query.Count());
    if(query.Count() > 0)
        Debug.Log(" and query 0 value is "+ query.ToArray().GetValue(0) + " type is "+ query.ToArray().GetValue(0).GetType());
        */
    return query.Count();
}
  public enum Elements{Fire, Water, Wood, Metal, Earth, None}

So this works well, but can I make this more shorter and neat?

//list.Where(p => p.GetType() == eType);  This part doesn't worked.

And how can make this for generic type, T?

Body:
This should work for enums and value types

public int GetNumFromList<T>(List<T> list, T item)
{
    return list.Count(x => x.Equals(item));
}


问:
Error running bash script
Trying to run the following bash script but get the below error message(s) - any ideas how to correct?

答:
You don't have a wget program on Your mac. The fastest way to get it is via cURL.

curl -O http://ftp.gnu.org/gnu/wget/wget-1.15.tar.gz

Extract cURL:

tar -zxvf wget-1.15.tar.gz

open folder:

cd wget-1.15/

And run installer

./configure

Title: Error running bash script


问:
Hibernate query with to join user with friends where user-friends are mapped using many-to-many relationship
I'm using Hibernate and JPA.

```<code>public class UserBean {
    private String email;
    private String name;
    private Set<UserBean> friends;
    private Set<UserBean> befriended;
}

@ManyToMany(
    targetEntity=com.pixping.model.UserBean.class,
    fetch = FetchType.LAZY
)
@JoinTable(
    name="user_friends",
    joinColumns=@JoinColumn(name="USER_ID", nullable=false),
    inverseJoinColumns=@JoinColumn(name="FRIEND_ID", nullable=false)
)
public Set<UserBean> getFriends() {
    return friends;
}

public void setFriends(Set<UserBean> friends) {
     this.friends = friends;
}

@ManyToMany(mappedBy = "friends", fetch = FetchType.LAZY)
public Set<UserBean> getBefriended() {
    return befriended;
}
</code>```

I would like to implement this function

```<code>public UserBean findUser(Long userId, Long friendId) {

}
</code>```

where the input is a user id and a friend id and if the user is friends with that person, return the User with the friend, else return just the user. This friend could be in either of the collections 'friends' or 'befriended' and when returned, these collections should contain only this friend and no other friends.

How do I implement a query to do this? If possible please provide an example.

答: I'm not sure if this can be done using a query (HQL or Criteria), but this can be done using a filter. Have you tried using one? </p>

Body:
I'm using Hibernate and JPA.

public class UserBean {
    private String email;
    private String name;
    private Set<UserBean> friends;
    private Set<UserBean> befriended;
}

@ManyToMany(
    targetEntity=com.pixping.model.UserBean.class,
    fetch = FetchType.LAZY
)
@JoinTable(
    name="user_friends",
    joinColumns=@JoinColumn(name="USER_ID", nullable=false),
    inverseJoinColumns=@JoinColumn(name="FRIEND_ID", nullable=false)
)
public Set<UserBean> getFriends() {
    return friends;
}

public void setFriends(Set<UserBean> friends) {
     this.friends = friends;
}

@ManyToMany(mappedBy = "friends", fetch = FetchType.LAZY)
public Set<UserBean> getBefriended() {
    return befriended;
}

I would like to implement this function

public UserBean findUser(Long userId, Long friendId) {

}

where the input is a user id and a friend id and if the user is friends with that person, return the User with the friend, else return just the user. This friend could be in either of the collections 'friends' or 'befriended' and when returned, these collections should contain only this friend and no other friends.

How do I implement a query to do this? If possible please provide an example.


问:
Add external .so library to jni project with nar-maven-plugin
I have file.c which I want to include to my Java application.
I've created JNI module and included it to application with nar-maven-plugin.

Here's it's configuration:

```<code><plugin>
    <groupId>com.github.maven-nar</groupId>
    <artifactId>nar-maven-plugin</artifactId>
    <version>3.5.2</version>
    <extensions>true</extensions>
    <configuration>
        <libraries>
            <library>
                <type>jni</type>
                <narSystemPackage>my.package.nativelib</narSystemPackage>
            </library>
        </libraries>
    </configuration>
</plugin>
</code>```

After I run mvn clean install, it creates libmy-native-lib.so file.

I managed to reach C-functions from Java, but there's one problem: file.c uses external libexternal.so library (which is included in file.c as #include "external.h"), and when it reaches  any function from external.h it fails with "symbol lookup error".

I tried using

```<code>static {
    System.load("/usr/lib/libexternal.so");
}
</code>```

and

```<code>static {
    System.loadLibrary("external");
}
</code>```

but nothing seems to be working.

So how can I add external *.so library to JNI project?

答:
Take a look here to see how to deal with JNI and shared libraries:

http://jnicookbook.owsiak.org/recipe-No-023/

What you need to do is to link your shared library (JNI) with one that is used by JNI code.

Then, you can provide this library with your code, or you can require for user to have it installed in system (e.g. via packages).

Have fun with JNI

Body:
I have file.c which I want to include to my Java application.
I've created JNI module and included it to application with nar-maven-plugin.

Here's it's configuration:

<plugin>
    <groupId>com.github.maven-nar</groupId>
    <artifactId>nar-maven-plugin</artifactId>
    <version>3.5.2</version>
    <extensions>true</extensions>
    <configuration>
        <libraries>
            <library>
                <type>jni</type>
                <narSystemPackage>my.package.nativelib</narSystemPackage>
            </library>
        </libraries>
    </configuration>
</plugin>

After I run mvn clean install, it creates libmy-native-lib.so file.

I managed to reach C-functions from Java, but there's one problem: file.c uses external libexternal.so library (which is included in file.c as #include "external.h"), and when it reaches  any function from external.h it fails with "symbol lookup error".

I tried using

static {
    System.load("/usr/lib/libexternal.so");
}

and

static {
    System.loadLibrary("external");
}

but nothing seems to be working.

So how can I add external *.so library to JNI project?


问:
Process Spring Boot externalized property values
I have the task of obfuscating passwords in our configuration files. While I don't think this is the right approach, managers disagree...

So the project I am working on is based on Spring Boot and we are using YAML configuration files. Currently the passwords are in plain text:

```<code>spring:
    datasource:
        url: jdbc:sqlserver://DatabaseServer
        driverClassName: com.microsoft.sqlserver.jdbc.SQLServerDriver
        username: ele
        password: NotTheRealPassword
</code>```

The idea is to have some special syntax that supports an obfuscated or encrypted password:

```<code>spring:
    datasource:
        url: jdbc:sqlserver://DatabaseServer
        driverClassName: com.microsoft.sqlserver.jdbc.SQLServerDriver
        username: ele
        password: password(Tm90VGhlUmVhbFBhc3N3b3Jk)
</code>```

In order for this to work I want to parse the property values using a regular expression and if it matches replace the value with the deobfuscated/decrypted value.

But how do I intercept the property value?

答:
Inspired by @gogstad. Here is my major action in the spring boot project to encrypted my username and password and decrypted them in the project to work with tomcat:

1. In pom.xml file

```<code>    <dependency>
        <groupId>com.github.ulisesbocchio</groupId>
        <artifactId>jasypt-spring-boot</artifactId>
        <version>1.12</version>
    </dependency>
    …
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
                </includes>
                <targetPath>${project.build.directory}/classes</targetPath>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                </includes>
                <targetPath>${project.build.directory}/classes</targetPath>
        </resource>
    </resources>
    …
    </build>
</code>```

2. In App.java (Note:to deploy the decryted springboot on tomcat, you should add the @ServletComponentScan annotation and extends the SpringBootServletInitializer)

```<code>    @SpringBootApplication
    @ServletComponentScan
    @EnableEncryptableProperties
    @PropertySource(name="EncryptedProperties", value = "classpath:config/encrypted.properties")
    public class App extends SpringBootServletInitializer {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(App.class, args);
        }

    }
</code>```

3. Encrypted your username and password and fill the application.properties file with the result：

```<code>    java -cp ~/.m2/repository/org/jasypt/jasypt/1.9.2/jasypt-1.9.2.jar  org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input="mypassword" password=mykey algorithm=PBEWithMD5AndDES
</code>```

output is like the demo below:

```<code>    java -cp ~/.m2/repository/org/jasypt/jasypt/1.9.2/jasypt-1.9.2.jar  org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input="mypassword" password=mykey algorithm=PBEWithMD5AndDES

    ----ENVIRONMENT-----------------

    Runtime: Oracle Corporation Java HotSpot(TM) 64-Bit Server VM 25.45-b02

    ----ARGUMENTS-------------------

    algorithm: PBEWithMD5AndDES
    input: mypassword
    password: mykey

    ----OUTPUT----------------------

    5XNwZF4qoCKTO8M8KUjRprQbivTkmI8H
</code>```

4. under the directory src/main/resources/config add two properties file：

```<code>    a. application.properties
        spring.datasource.driver-class-name=com.mysql.jdbc.Driver
        spring.datasource.url=jdbc:mysql://xxx
        spring.datasource.username=ENC(xxx)
        spring.datasource.password=ENC(xxx)
        mybatis.mapper-locations=classpath:*/mapper/*.xml
        mybatis.type-aliases-package=com.xx.xxx.model
        logging.level.com.xx.xxx: DEBUG

    b. encrypted.properties
        jasypt.encryptor.password=mykey
</code>```

Body:
I have the task of obfuscating passwords in our configuration files. While I don't think this is the right approach, managers disagree...

So the project I am working on is based on Spring Boot and we are using YAML configuration files. Currently the passwords are in plain text:

spring:
    datasource:
        url: jdbc:sqlserver://DatabaseServer
        driverClassName: com.microsoft.sqlserver.jdbc.SQLServerDriver
        username: ele
        password: NotTheRealPassword

The idea is to have some special syntax that supports an obfuscated or encrypted password:

spring:
    datasource:
        url: jdbc:sqlserver://DatabaseServer
        driverClassName: com.microsoft.sqlserver.jdbc.SQLServerDriver
        username: ele
        password: password(Tm90VGhlUmVhbFBhc3N3b3Jk)

In order for this to work I want to parse the property values using a regular expression and if it matches replace the value with the deobfuscated/decrypted value.

But how do I intercept the property value?

Body:
Inspired by @gogstad. Here is my major action in the spring boot project to encrypted my username and password and decrypted them in the project to work with tomcat:

1. In pom.xml file

    <dependency>
        <groupId>com.github.ulisesbocchio</groupId>
        <artifactId>jasypt-spring-boot</artifactId>
        <version>1.12</version>
    </dependency>
    …
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
                </includes>
                <targetPath>${project.build.directory}/classes</targetPath>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                </includes>
                <targetPath>${project.build.directory}/classes</targetPath>
        </resource>
    </resources>
    …
    </build>

2. In App.java (Note:to deploy the decryted springboot on tomcat, you should add the @ServletComponentScan annotation and extends the SpringBootServletInitializer)

    @SpringBootApplication
    @ServletComponentScan
    @EnableEncryptableProperties
    @PropertySource(name="EncryptedProperties", value = "classpath:config/encrypted.properties")
    public class App extends SpringBootServletInitializer {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(App.class, args);
        }

    }

3. Encrypted your username and password and fill the application.properties file with the result：

    java -cp ~/.m2/repository/org/jasypt/jasypt/1.9.2/jasypt-1.9.2.jar  org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input="mypassword" password=mykey algorithm=PBEWithMD5AndDES

output is like the demo below:

    java -cp ~/.m2/repository/org/jasypt/jasypt/1.9.2/jasypt-1.9.2.jar  org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input="mypassword" password=mykey algorithm=PBEWithMD5AndDES

    ----ENVIRONMENT-----------------

    Runtime: Oracle Corporation Java HotSpot(TM) 64-Bit Server VM 25.45-b02

    ----ARGUMENTS-------------------

    algorithm: PBEWithMD5AndDES
    input: mypassword
    password: mykey

    ----OUTPUT----------------------

    5XNwZF4qoCKTO8M8KUjRprQbivTkmI8H

4. under the directory src/main/resources/config add two properties file：

    a. application.properties
        spring.datasource.driver-class-name=com.mysql.jdbc.Driver
        spring.datasource.url=jdbc:mysql://xxx
        spring.datasource.username=ENC(xxx)
        spring.datasource.password=ENC(xxx)
        mybatis.mapper-locations=classpath:*/mapper/*.xml
        mybatis.type-aliases-package=com.xx.xxx.model
        logging.level.com.xx.xxx: DEBUG

    b. encrypted.properties
        jasypt.encryptor.password=mykey


答:
This code will do the job </p>

```<code> DB::table('users as u')->select(['u.email','u.name','u.created_at'])->whereRaw("u.id in (select max(ui.id) from users ui where ui.status = 0)")->orderBy("ui.id","desc")->paginate(3);
</code>```

Title: Pagination functionality in laravel, Issue: Call to a member function paginate() on array

Body:
Laravel Framework - using version 5.4: If I used raw query as shown below in User.php controller and making paginate(3) as shown below. But it is giving error as "Call to a member function paginate() on array". solution please.

DB::select("select u.email,u.name,u.created_at from users u where u.id in (select max(ui.id) from users ui where ui.status = 0) order by ui.id desc")->paginate(3);

Body:
This code will do the job

 DB::table('users as u')->select(['u.email','u.name','u.created_at'])->whereRaw("u.id in (select max(ui.id) from users ui where ui.status = 0)")->orderBy("ui.id","desc")->paginate(3);


问:
Unexpected behaviour after memcached server restarts. How to configure/rectify it?
I have a pool of persistent connections(Memcached clients). Data are being cached in the memcached server. If after restarting the memcached server, I try to get the cached data using the client from the pool, I m getting the below exception:

```<code>java.util.concurrent.ExecutionException: java.lang.RuntimeException: Cancelled
    at net.spy.memcached.MemcachedClient$OperationFuture.get(MemcachedClient.java:1662)
    at net.spy.memcached.MemcachedClient$GetFuture.get(MemcachedClient.java:1708)
    at com.eos.gds.cache.CacheClient.get(CacheClient.java:49)
</code>```

I get this exception only for the first time after the restart when I try to get the cached data. I did a lot of search. But unable to find the exact reason for this.

答:
I had the same issue. I am using Spymemcached client to connect with Memcache server.

I found .

There must be a connection issue.

Ref: https://github.com/couchbase/spymemcached/blob/master/src/main/java/net/spy/memcached/internal/OperationFuture.java

Body:
I have a pool of persistent connections(Memcached clients). Data are being cached in the memcached server. If after restarting the memcached server, I try to get the cached data using the client from the pool, I m getting the below exception:

java.util.concurrent.ExecutionException: java.lang.RuntimeException: Cancelled
    at net.spy.memcached.MemcachedClient$OperationFuture.get(MemcachedClient.java:1662)
    at net.spy.memcached.MemcachedClient$GetFuture.get(MemcachedClient.java:1708)
    at com.eos.gds.cache.CacheClient.get(CacheClient.java:49)

I get this exception only for the first time after the restart when I try to get the cached data. I did a lot of search. But unable to find the exact reason for this.


问:
Wrong text entered by sendkeys
I am trying to automate a webpage where i have to enter credit card details.
During manually entering CVV of the credit card I am able to move forward, but while entering value using sendkeys it throws an error.

```<code>driver.findElement(By.name("password_ccCvv")).click();
driver.findElement(By.name("password_ccCvv")).sendKeys("999");
</code>```

I tried clicking on the textbox and then entered value. This also didn't work.

While entering value through send keys, i cant see what value is being sent because its encrypted.

答:
If Webdriver is not able to enter data using standard way (using sendKeys method), you can use a workaround using JavaScriptExecuter, as shown below:

```<code>JavascriptExecutor e = (JavascriptExecutor)driver;
e.executeScript("arguments[0].setAttribute('value', arguments[1])", driver.findElement(By.name("password_ccCvv")), "999");
</code>```

Let me know, whether it works for you.

Title: Wrong text entered by sendkeys

Body:
I am trying to automate a webpage where i have to enter credit card details.
During manually entering CVV of the credit card I am able to move forward, but while entering value using sendkeys it throws an error.

driver.findElement(By.name("password_ccCvv")).click();
driver.findElement(By.name("password_ccCvv")).sendKeys("999");

I tried clicking on the textbox and then entered value. This also didn't work.

While entering value through send keys, i cant see what value is being sent because its encrypted.

Body:
If Webdriver is not able to enter data using standard way (using sendKeys method), you can use a workaround using JavaScriptExecuter, as shown below:

JavascriptExecutor e = (JavascriptExecutor)driver;
e.executeScript("arguments[0].setAttribute('value', arguments[1])", driver.findElement(By.name("password_ccCvv")), "999");

Let me know, whether it works for you.


问:
how to add array object values in javascript
hi all i am using javascript working with array i have a set of data to do add array values object here i attached my code help how to solve this

data

```<code>var data=[{one:1,two:2},{one:1,two:2},{one:1,two:2},{one:1,two:2}]
</code>```

expected output

```<code>var sumdata=[{one:4,two:8}]
</code>```

NOTE:one two column name is not static

答:
```<code>var resObj = {};
for (var i = 0; i < data.length; i++) {
   for (var item in data[i]) {
      if (!resObj.hasOwnProperty(item)) {
         resObj[item] = data[i][item];
      } else {
         resObj[item] += data[i][item];
      }
    }
 }
 var sumdata = [resObj];
</code>```

Body:
hi all i am using javascript working with array i have a set of data to do add array values object here i attached my code help how to solve this

data

var data=[{one:1,two:2},{one:1,two:2},{one:1,two:2},{one:1,two:2}]

expected output

var sumdata=[{one:4,two:8}]

NOTE:one two column name is not static


答:
Use this query:</p>

```<code>SELECT * FROM <table_name> ORDER BY name ASC, Sale_Date DESC
</code>```

Title: Sort Results in Mysql Asc

Body:
I have a database with this table:

Id (autogenerate)

Zipcode

Price

Adress

City

Date of sale(from 2017-2010)

The search is by zipcode
Now the ouput result is generate by mysql..I want the results order by date of sale:
 2017,2016,2015,2014...2010

My query is :

//query the database
      $resultSet = $mysqli->query("SELECT * FROM land_data WHERE ZipCode LIKE '%$search%'LIMIT 0,30");

Thanks

Body:
Use this query:

SELECT * FROM <table_name> ORDER BY name ASC, Sale_Date DESC


问:
Latex Itemization
How can I edit the enumerate command in latex such that when I type \item it shows item list like this

```<code>[1] Line 1
[2] Line 2
</code>```

答:
Use enumitem to change the label representation:

```<code>\documentclass{article}

\usepackage{enumitem}

\begin{document}

\begin{enumerate}[label={[\arabic*]}]
  \item Line 1
  \item Line 2
\end{enumerate}

\end{document}
</code>```

Title: Latex Itemization

Body:
How can I edit the enumerate command in latex such that when I type \item it shows item list like this

[1] Line 1
[2] Line 2

Body:
Use enumitem to change the label representation:

\documentclass{article}

\usepackage{enumitem}

\begin{document}

\begin{enumerate}[label={[\arabic*]}]
  \item Line 1
  \item Line 2
\end{enumerate}

\end{document}


问:
ASP.NET MVC2 Reading JSON data with controller
I have problems to receive json values from my javascript/jQuery request to my controller.

MyClass looks like the following:

```<code>function MyClass() {
    this.MyString = null;
    this.MyInt = null;
    this.Subs = null;
}
</code>```

My Request looks like the following:

```<code>var testData1 = new MyClass();
testData1.MyInt = 1234;
testData1.MyString = "abcDEF";
testData1.Subs = new Array();
var testData2 = new MyClass();
testData2.MyInt = 5678;
testData2.MyString = "GHIjkl";
testData1.Subs.push(testData2);
var jsonData = JSON.stringify(testData1);
var self = this;
$.ajax({
    url: '/Home/Request',
    type: 'POST',
    dataType: 'json',
    data: jsonData,
    contentType: 'application/json; charset=utf-8',
    success: function (x) {
        self.ParseResult(x);
    }
});
</code>```

Now I have a controller:

```<code>public JsonResult Request(MyClass myObj)
{
    var answer = ...
    return Json(answer, JsonRequestBehavior.DenyGet);
}
</code>```

With the following class:

```<code>public class  MyClass
{
    public string MyString { get; set; }
    public int MyInt { get; set; }
    public List<MyClass> Subs { get; set; }
}
</code>```

All names in jsonData are exactly the same like in my class "MyClass". But there are no values in myObj.

Where is the Problem. Is there anything I can do to get this mapping working correctly?

Thank you very much in advance,

Chris

UPDATE:

Thank you for your repley. I have used the JavascriptSerializer. But I have the problem, that myString is null:

```<code>public JsonResult Data(string myString)
{
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    var data = serializer.Deserialize<MyClass>(myString);
var answer = ...
    return Json(answer, JsonRequestBehavior.DenyGet);
}
</code>```

Where is the value? Should I take the value from the request-data?

@Dave Ward

You second solution is working. But I have a problem with the subs.

```<code>var testData1 = new MyClass();
testData1.MyInt = 1234;
testData1.MyString = "abcDEF";
testData1.Subs = new Array();
for (var i = 0; i < 10; i++) {
    var testData2 = new MyClass();
    testData2.MyInt = i;
    testData2.MyString = "abcDEF";
    testData1.Subs.push(testData2);
}
</code>```

I get 10 Subs in my controller, but all are empty. What can I do?

@Dave Ward, @ALL

Using the traditional settings my 10 Subs are bot empty, they are not there. Subs count is 0 (not NULL).
I tried to change the Subs Type from List to IEnumerable but that didn't help.
Do you know anything else I can do to get Subs filled in my controller?

Ok, thank you Dave Ward, I will use the JSON method.

For somebody else having the same problem this controller code could be from help:

```<code>MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(myString));
var serializer = new DataContractJsonSerializer(typeof(MyClass));
MyClass se = serializer.ReadObject(ms) as MyClass;
ms.Close();
</code>```

答:
Right now, you're sending the JSON string as the entire body of your POST.  MVC has no way to connect the dots and understand that you wanted it to provide that entire string as a parameter named myString.

To do that, change your client-side data parameter like this:

```<code>$.ajax({
  url: '/Home/Request',
  type: 'POST',
  dataType: 'json',
  data: { myString: jsonData },
  contentType: 'application/json; charset=utf-8',
  success: function (x) {
    // If ParseResult is some sort of JSON deserializing, don't do that.
    // When the dataType is set to 'json', jQuery handles this for you
    //  automatically before the success handler is called.
    self.ParseResult(x);
  }
});
</code>```

When you provide jQuery an object as its data parameter, it automatically URLEncodes that before sending, so something like this will be POSTed to the server:

```<code>myString={json:data, here:etc}
</code>```

MVC will pick that up as the myString parameter as desired then, and you can proceed with deserializing it with JavaScriptSerializer.

Also, unless you're doing something more complicated on the client-side than you're showing, the JavaScript class is unnecessary.  Something like this would work:

```<code>var testData2 = {
  MyInt: 5678,
  MyString: "GHIjkl",
}

var testData1 = {
  MyInt: 1234,
  MyString: "abcDEF",
  Subs: [ testData2 ]
}
</code>```

All that said, why are you using JSON for the request?  If you accept a parameter of the custom type in your action, MVC's model binder is pretty good at hydrating that type from standard URLEncoded input data:

```<code>public JsonResult Data(MyClass request)
{
  // request.MyInt, request.MyString, etc should exist here.

  var answer = ...

  // It's okay to accept URLEncoded input parameters, but still return JSON.
  return Json(answer, JsonRequestBehavior.DenyGet);
}
</code>```

Then, calling it doesn't require the client-side JSON serialization:

```<code>var testData2 = {
  MyInt: 5678,
  MyString: "GHIjkl",
}

var testData1 = {
  MyInt: 1234,
  MyString: "abcDEF",
  Subs: [ testData2 ]
}

$.ajax({
  url: '/Home/Request',
  type: 'POST',
  traditional: true,
  dataType: 'json',
  data: testData1
  success: function (x) {
    self.ParseResult(x);
  }
});
</code>```

It's a bit simpler all around, and is faster since you've removed a layer of serialization on the client-side and deserialization on the server-side.

Body:
I have problems to receive json values from my javascript/jQuery request to my controller.

MyClass looks like the following:

function MyClass() {
    this.MyString = null;
    this.MyInt = null;
    this.Subs = null;
}

My Request looks like the following:

var testData1 = new MyClass();
testData1.MyInt = 1234;
testData1.MyString = "abcDEF";
testData1.Subs = new Array();
var testData2 = new MyClass();
testData2.MyInt = 5678;
testData2.MyString = "GHIjkl";
testData1.Subs.push(testData2);
var jsonData = JSON.stringify(testData1);
var self = this;
$.ajax({
    url: '/Home/Request',
    type: 'POST',
    dataType: 'json',
    data: jsonData,
    contentType: 'application/json; charset=utf-8',
    success: function (x) {
        self.ParseResult(x);
    }
});

Now I have a controller:

public JsonResult Request(MyClass myObj)
{
    var answer = ...
    return Json(answer, JsonRequestBehavior.DenyGet);
}

With the following class:

public class  MyClass
{
    public string MyString { get; set; }
    public int MyInt { get; set; }
    public List<MyClass> Subs { get; set; }
}

All names in jsonData are exactly the same like in my class "MyClass". But there are no values in myObj.

Where is the Problem. Is there anything I can do to get this mapping working correctly?

Thank you very much in advance,

Chris

UPDATE:

Thank you for your repley. I have used the JavascriptSerializer. But I have the problem, that myString is null:

public JsonResult Data(string myString)
{
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    var data = serializer.Deserialize<MyClass>(myString);
var answer = ...
    return Json(answer, JsonRequestBehavior.DenyGet);
}

Where is the value? Should I take the value from the request-data?

@Dave Ward

You second solution is working. But I have a problem with the subs.

var testData1 = new MyClass();
testData1.MyInt = 1234;
testData1.MyString = "abcDEF";
testData1.Subs = new Array();
for (var i = 0; i < 10; i++) {
    var testData2 = new MyClass();
    testData2.MyInt = i;
    testData2.MyString = "abcDEF";
    testData1.Subs.push(testData2);
}

I get 10 Subs in my controller, but all are empty. What can I do?

@Dave Ward, @ALL

Using the traditional settings my 10 Subs are bot empty, they are not there. Subs count is 0 (not NULL).
I tried to change the Subs Type from List to IEnumerable but that didn't help.
Do you know anything else I can do to get Subs filled in my controller?

Ok, thank you Dave Ward, I will use the JSON method.

For somebody else having the same problem this controller code could be from help:

MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(myString));
var serializer = new DataContractJsonSerializer(typeof(MyClass));
MyClass se = serializer.ReadObject(ms) as MyClass;
ms.Close();

Body:
Right now, you're sending the JSON string as the entire body of your POST.  MVC has no way to connect the dots and understand that you wanted it to provide that entire string as a parameter named myString.

To do that, change your client-side data parameter like this:

$.ajax({
  url: '/Home/Request',
  type: 'POST',
  dataType: 'json',
  data: { myString: jsonData },
  contentType: 'application/json; charset=utf-8',
  success: function (x) {
    // If ParseResult is some sort of JSON deserializing, don't do that.
    // When the dataType is set to 'json', jQuery handles this for you
    //  automatically before the success handler is called.
    self.ParseResult(x);
  }
});

When you provide jQuery an object as its data parameter, it automatically URLEncodes that before sending, so something like this will be POSTed to the server:

myString={json:data, here:etc}

MVC will pick that up as the myString parameter as desired then, and you can proceed with deserializing it with JavaScriptSerializer.

Also, unless you're doing something more complicated on the client-side than you're showing, the JavaScript class is unnecessary.  Something like this would work:

var testData2 = {
  MyInt: 5678,
  MyString: "GHIjkl",
}

var testData1 = {
  MyInt: 1234,
  MyString: "abcDEF",
  Subs: [ testData2 ]
}

All that said, why are you using JSON for the request?  If you accept a parameter of the custom type in your action, MVC's model binder is pretty good at hydrating that type from standard URLEncoded input data:

public JsonResult Data(MyClass request)
{
  // request.MyInt, request.MyString, etc should exist here.

  var answer = ...

  // It's okay to accept URLEncoded input parameters, but still return JSON.
  return Json(answer, JsonRequestBehavior.DenyGet);
}

Then, calling it doesn't require the client-side JSON serialization:

var testData2 = {
  MyInt: 5678,
  MyString: "GHIjkl",
}

var testData1 = {
  MyInt: 1234,
  MyString: "abcDEF",
  Subs: [ testData2 ]
}

$.ajax({
  url: '/Home/Request',
  type: 'POST',
  traditional: true,
  dataType: 'json',
  data: testData1
  success: function (x) {
    self.ParseResult(x);
  }
});

It's a bit simpler all around, and is faster since you've removed a layer of serialization on the client-side and deserialization on the server-side.


问:
Hide 1 line of text with CSS
I have two lines of code in a PHP file

```<code><div align="center">The quick brown fox</div>
<div align="center">jumps over the lazy dog.</div>
</code>```

How can I hide only the first line of text displayed with CSS?

答:
Try This:

```<code>div[align="center"]:first-child {
       display:none;
}
</code>```

Title: Hide 1 line of text with CSS

Body:
I have two lines of code in a PHP file

The quick brown fox

jumps over the lazy dog.

How can I hide only the first line of text displayed with CSS?

Body:
Try This:

div[align="center"]:first-child {
       display:none;
}


问:
Get the average value of a table by day column in mysql
I try to get the average value of a table by day column, for example

```<code>table1
id  |  day  |  value |
F01 |  01   |   3    |
F02 |  02   |   2    |
F03 |  03   |   1    |
F04 |  04   |   2    |
F05 |  05   |   2    |
.   |  .    |   .    |
.   |  .    |   .    |
F30 |  30   |   4    |
F31 |  31   |   2    |
</code>```

From the table above I want to get the average value of 5 days from the value column so in the above example I will get the value 2.
thanks before

答:
Use AVG():

```<code>SELECT `day` AS `Day`,
       AVG(`value`) AS `Average`
FROM `table`
WHERE `day` <= 5
GROUP BY `day`
ORDER BY `day` ASC;
</code>```

Body:
I try to get the average value of a table by day column, for example

table1
id  |  day  |  value |
F01 |  01   |   3    |
F02 |  02   |   2    |
F03 |  03   |   1    |
F04 |  04   |   2    |
F05 |  05   |   2    |
.   |  .    |   .    |
.   |  .    |   .    |
F30 |  30   |   4    |
F31 |  31   |   2    |

From the table above I want to get the average value of 5 days from the value column so in the above example I will get the value 2.
thanks before

Body:
Use AVG():

SELECT `day` AS `Day`,
       AVG(`value`) AS `Average`
FROM `table`
WHERE `day` <= 5
GROUP BY `day`
ORDER BY `day` ASC;


问:
How we remove full object of array from array of object using JavaScript or lodash?
My JSON looks like this:

```<code>     {
      "success": true,
      "data": [
        {
          "user": {
            "firstname": "demo",
            test1": {
              "role": {
                "name": "demo"
              },
              "status": "pending",
              "test2": {
                "telephone": "+demo"
              }
            }
          },
          "authData": [
            {
              "_key": "demo",
              "_id": "demo",
            }
          ]
        }
      ],
      "session": {
        "_key": "demo",
        "uid": "demo",
      }
    }
</code>```

I want to remove authData array from JSON.

答:
First your JSON is invalid. This is corrected version:

```<code>{
          "success": true,
          "data": [
            {
              "user": {
                "firstname": "demo",
                "test1": {
                  "role": {
                    "name": "demo"
                  },
                  "status": "pending",
                  "test2": {
                    "telephone": "+demo"
                  }
                }
              },
              "authData": [
                {
                  "_key": "demo",
                  "_id": "demo"
                }
              ]
            }
          ],
          "session": {
            "_key": "demo",
            "uid": "demo"
          }
        }
</code>```

Now you can use DELETE operator to delete your key.

Body:
My JSON looks like this:

     {
      "success": true,
      "data": [
        {
          "user": {
            "firstname": "demo",
            test1": {
              "role": {
                "name": "demo"
              },
              "status": "pending",
              "test2": {
                "telephone": "+demo"
              }
            }
          },
          "authData": [
            {
              "_key": "demo",
              "_id": "demo",
            }
          ]
        }
      ],
      "session": {
        "_key": "demo",
        "uid": "demo",
      }
    }

I want to remove authData array from JSON.

Body:
First your JSON is invalid. This is corrected version:

{
          "success": true,
          "data": [
            {
              "user": {
                "firstname": "demo",
                "test1": {
                  "role": {
                    "name": "demo"
                  },
                  "status": "pending",
                  "test2": {
                    "telephone": "+demo"
                  }
                }
              },
              "authData": [
                {
                  "_key": "demo",
                  "_id": "demo"
                }
              ]
            }
          ],
          "session": {
            "_key": "demo",
            "uid": "demo"
          }
        }

Now you can use DELETE operator to delete your key.


问:
How to show picture depending on the value of a textbox
i downloaded a java billiard game. I want to modify it.

Note: the sum of the score is store in score_text_total

So when the player shoots the Ball with sum of less than 10, a picture, for example, of a DOG will show

If sum of ball shoots is more than 10 but less 20, picture of CAT (replaces/hides the DOG picture)

If sum of ball shoots is more than 30, a picture of trophy appears (replaces/hides the CAT picture)

```<code><!doctype html>
<html lang="en">
<head>

</style>
</head>

<body>

<img src="assets/images/DOG.gif" style="display: none; background: #000;" id="DOG"/>
<img src="assets/images/CAT.gif" style="display: none; background: #ff0000;" id="CAT"/>

<script type="text/javascript">

var DOG =    document.getElementById('DOG');
var CAT =    document.getElementById('CAT');

function picture() {
if(curent_score < 10) {
DOG.style.display = 'block';
CAT.style.display = 'none';
}
else {
DOG.style.display = 'none';
CAT.style.display = 'block';
}
}

</script>

</body>
</html>
</code>```

答:
I'm assuming you mean JavaScript and not Java. I'm also assuming you are using vanilla JS.

You could make a div and then set its background image. This would allow you to style the div/absolutely position it where you want, and then change the picture as a single CSS property.

You could try something like (untested):
var score = document.getElementbyId('scoreboard');
score.style.background = "none";

There are similar solutions around on Stack Overflow as well that inspired this suggestion:
Set CSS property in Javascript?

Body:
i downloaded a java billiard game. I want to modify it.

Note: the sum of the score is store in score_text_total

So when the player shoots the Ball with sum of less than 10, a picture, for example, of a DOG will show

If sum of ball shoots is more than 10 but less 20, picture of CAT (replaces/hides the DOG picture)

If sum of ball shoots is more than 30, a picture of trophy appears (replaces/hides the CAT picture)

<!doctype html>

</style>