问:
Application Not Receiving Serial Data from COM Port - C++
My application is not properly receiving data from the COM port.  This used to work.  I don't know what happened.  I know that the proper data is being sent/received over the line because I can see it on my protocol analyzer.

The PC gets into the WAIT_OBJECT_0 + 1 state, but the buffer contents are always zero.  I know this is a lot, but if anyone can point out what I'm doing wrong, I'd really appreciate it.  I can add/remove details as requested.  Thanks.

EDIT: Additional Information

I have been able to verify that the PC makes the call to ReadFileEx, and it "succeeds."  However, the PC never gets into FileIOCompletionRoutine.  Any ideas?  (I removed the error-handling from the code to make life simpler.)  Also, from what I read on the MSDN website, it looks like FileIOCompletionRoutine will get called asynchronously in its own thread.  Is that correct?  Thanks.

EDIT: Final Solution

This is what I came up with.  Obviously, the initialization and error-handling code is not here.  We can't make things too easy. :)

```<code>// Load event handles.
pHandles[0] = s_hSerialPortRxThreadExitEvent;
// OVERLAPPED structure event handle is loaded in loop.

while ( blContinue )
{
    // Wait for a communications event.
    if ( !::WaitCommEvent( s_hSerialPort, &dwEventMask, &s_ov ) )
    {
        if ( ::GetLastError() != ERROR_IO_PENDING )
        {
            blContinue = FALSE;
            continue;
        }
        else if ( ::WaitForSingleObject( pHandles[0], 0 ) == WAIT_OBJECT_0 )
        {
            // The thread-exit event has been signaled.  Get out of here.
            blContinue = FALSE;
            continue;
        }
    }
    else
    {
        // Load OVERLAPPED structure event handle.
        pHandles[1] = s_ov.hEvent;
    }

    if ( dwEventMask & EV_RXCHAR )
    {
        if ( !::ReadFile( s_hSerialPort, pBuf, RX_BUF_SIZE, NULL, &s_ov ) )
        {
            if ( ::GetLastError() == ERROR_IO_PENDING )
            {
                // Wait for events.
                dwObjectWaitState = ::WaitForMultipleObjects( 2, pHandles, FALSE, INFINITE );

                // Switch on event.
                switch ( dwObjectWaitState )
                {
                case WAIT_OBJECT_0:             // thread exit event signaled
                    blContinue = FALSE;
                    continue;

                case WAIT_OBJECT_0 + 1:         // OVERLAPPED structure event signalled
                    // Reset event first to mitigate underrun condition.
                    if ( !::ResetEvent( pHandles[1] ) )
                    {
                        blContinue = FALSE;
                        continue;
                    }

                    // Get the OVERLAPPED result.
                    if ( !::GetOverlappedResult( s_hSerialPort, &s_ov, &dwBytesRead, FALSE ) )
                    {
                        blContinue = FALSE;
                        continue;
                    }
                    break;

                default:                        // Error
                    blContinue = FALSE;
                    continue;
                }
            }
        }
        else if ( !::GetOverlappedResult( s_hSerialPort, &s_ov, &dwBytesRead, FALSE ) )
        {
            blContinue = FALSE;
            continue;
        }

        // If bytes were read...
        if ( dwBytesRead > 0 )
        {
            // Copy received data from local buffer to thread-safe serial port buffer.
            ::EnterCriticalSection( &s_csRxRingBuffer );
            blSuccess = s_pobjRxRingBuffer->Add( pBuf, dwBytesRead, TRUE );
            ::LeaveCriticalSection( &s_csRxRingBuffer );

            if ( !blSuccess )
            {
                blContinue = FALSE;
                continue;
            }

            // Set the received data event.
            if ( !::SetEvent( s_phEventIds[RECEIVE_EVENT] ) )
            {
                blContinue = FALSE;
                continue;
            }
        }
    }

    if ( dwEventMask & EV_TXEMPTY )
    {
        // Set the transmit complete event.
        if ( !::SetEvent( s_phEventIds[TRANSMIT_EVENT] ) )
        {
            blContinue = FALSE;
            continue;
        }
    }

} // end while ( blContinue );
</code>```

答:
I don't know if I see your code wrong, but I see that you are setting up event, and waiting for the event without telling the O/S what are you waiting for, you should do ReadFileEx() first to tell O/S you are waiting for event when there's data in the buffer to read, then you do WFSO()/WFMO(), this what I do on my Serial port library (on receiver thread):

```<code>do
{
    byteRead = 0;
    readBuffer = 0;
    if(!::ReadFile(this->commHandle,&readBuffer,
                   1,NULL,&this->readOverlapIO))
    {
         if(GetLastError() == ERROR_IO_PENDING)
         {
             if(::WaitForSingleObject(this->readOverlapIO.hEvent,INFINITE) == WAIT_OBJECT_0)
             {
                 if(!::GetOverlappedResult(this->commHandle,&this->readOverlapIO,&byteRead,FALSE))
                 {
                     byteRead = 0;
                 }
             }
         }
    }
    else
    {
         if(!::GetOverlappedResult(this->commHandle,&this->readOverlapIO,&byteRead,FALSE))
         {
              byteRead = 0;
         }
    }
    if(byteRead > 0)
    {
          totalByteRead += this->ringBuffer.push(readBuffer,1);
    }
}while(byteRead);
</code>```

I use completion event using event signal here, you can change it to completion function if you wanted to.

Body:
My application is not properly receiving data from the COM port.  This used to work.  I don't know what happened.  I know that the proper data is being sent/received over the line because I can see it on my protocol analyzer.

The PC gets into the WAIT_OBJECT_0 + 1 state, but the buffer contents are always zero.  I know this is a lot, but if anyone can point out what I'm doing wrong, I'd really appreciate it.  I can add/remove details as requested.  Thanks.

EDIT: Additional Information

I have been able to verify that the PC makes the call to ReadFileEx, and it "succeeds."  However, the PC never gets into FileIOCompletionRoutine.  Any ideas?  (I removed the error-handling from the code to make life simpler.)  Also, from what I read on the MSDN website, it looks like FileIOCompletionRoutine will get called asynchronously in its own thread.  Is that correct?  Thanks.

EDIT: Final Solution

This is what I came up with.  Obviously, the initialization and error-handling code is not here.  We can't make things too easy. :)

// Load event handles.
pHandles[0] = s_hSerialPortRxThreadExitEvent;
// OVERLAPPED structure event handle is loaded in loop.

while ( blContinue )
{
    // Wait for a communications event.
    if ( !::WaitCommEvent( s_hSerialPort, &dwEventMask, &s_ov ) )
    {
        if ( ::GetLastError() != ERROR_IO_PENDING )
        {
            blContinue = FALSE;
            continue;
        }
        else if ( ::WaitForSingleObject( pHandles[0], 0 ) == WAIT_OBJECT_0 )
        {
            // The thread-exit event has been signaled.  Get out of here.
            blContinue = FALSE;
            continue;
        }
    }
    else
    {
        // Load OVERLAPPED structure event handle.
        pHandles[1] = s_ov.hEvent;
    }

    if ( dwEventMask & EV_RXCHAR )
    {
        if ( !::ReadFile( s_hSerialPort, pBuf, RX_BUF_SIZE, NULL, &s_ov ) )
        {
            if ( ::GetLastError() == ERROR_IO_PENDING )
            {
                // Wait for events.
                dwObjectWaitState = ::WaitForMultipleObjects( 2, pHandles, FALSE, INFINITE );

                // Switch on event.
                switch ( dwObjectWaitState )
                {
                case WAIT_OBJECT_0:             // thread exit event signaled
                    blContinue = FALSE;
                    continue;

                case WAIT_OBJECT_0 + 1:         // OVERLAPPED structure event signalled
                    // Reset event first to mitigate underrun condition.
                    if ( !::ResetEvent( pHandles[1] ) )
                    {
                        blContinue = FALSE;
                        continue;
                    }

                    // Get the OVERLAPPED result.
                    if ( !::GetOverlappedResult( s_hSerialPort, &s_ov, &dwBytesRead, FALSE ) )
                    {
                        blContinue = FALSE;
                        continue;
                    }
                    break;

                default:                        // Error
                    blContinue = FALSE;
                    continue;
                }
            }
        }
        else if ( !::GetOverlappedResult( s_hSerialPort, &s_ov, &dwBytesRead, FALSE ) )
        {
            blContinue = FALSE;
            continue;
        }

        // If bytes were read...
        if ( dwBytesRead > 0 )
        {
            // Copy received data from local buffer to thread-safe serial port buffer.
            ::EnterCriticalSection( &s_csRxRingBuffer );
            blSuccess = s_pobjRxRingBuffer->Add( pBuf, dwBytesRead, TRUE );
            ::LeaveCriticalSection( &s_csRxRingBuffer );

            if ( !blSuccess )
            {
                blContinue = FALSE;
                continue;
            }

            // Set the received data event.
            if ( !::SetEvent( s_phEventIds[RECEIVE_EVENT] ) )
            {
                blContinue = FALSE;
                continue;
            }
        }
    }

    if ( dwEventMask & EV_TXEMPTY )
    {
        // Set the transmit complete event.
        if ( !::SetEvent( s_phEventIds[TRANSMIT_EVENT] ) )
        {
            blContinue = FALSE;
            continue;
        }
    }

} // end while ( blContinue );

Body:
I don't know if I see your code wrong, but I see that you are setting up event, and waiting for the event without telling the O/S what are you waiting for, you should do ReadFileEx() first to tell O/S you are waiting for event when there's data in the buffer to read, then you do WFSO()/WFMO(), this what I do on my Serial port library (on receiver thread):

do
{
    byteRead = 0;
    readBuffer = 0;
    if(!::ReadFile(this->commHandle,&readBuffer,
                   1,NULL,&this->readOverlapIO))
    {
         if(GetLastError() == ERROR_IO_PENDING)
         {
             if(::WaitForSingleObject(this->readOverlapIO.hEvent,INFINITE) == WAIT_OBJECT_0)
             {
                 if(!::GetOverlappedResult(this->commHandle,&this->readOverlapIO,&byteRead,FALSE))
                 {
                     byteRead = 0;
                 }
             }
         }
    }
    else
    {
         if(!::GetOverlappedResult(this->commHandle,&this->readOverlapIO,&byteRead,FALSE))
         {
              byteRead = 0;
         }
    }
    if(byteRead > 0)
    {
          totalByteRead += this->ringBuffer.push(readBuffer,1);
    }
}while(byteRead);

I use completion event using event signal here, you can change it to completion function if you wanted to.


来源: stackexchange

问:
Useless Parent layout
** This ScrollView layout or its LinearLayout parent is useless; transfer the background attribute to the other view  A layout with children that has no siblings, is not a scrollview or a root layout, and does not have a background, can be removed and have its children moved directly into the parent for a flatter and more efficient layout hierarchy. **

`

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"

android:padding="10dp"
android:background="#504b4b"
tools:context="com.example.sompod.imageview.MainActivity">

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:visibility="visible"
    >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_gravity="center"
        >

        <ImageView
            android:id="@+id/p1"
            android:layout_width="260dp"
            android:layout_height="260dp"

            android:layout_marginLeft="25dp"
            android:layout_marginStart="25dp"
            android:contentDescription="@null"
            android:rotation="270"

            android:scaleType="fitXY"
            android:src="@drawable/img_5116"
            />

        <ImageView
            android:id="@+id/p2"
            android:layout_width="300dp"
            android:layout_height="200dp"
            android:layout_marginLeft="15dp"
            android:layout_marginStart="15dp"
            android:layout_marginTop="25dp"
            android:contentDescription="@null"
            android:scaleType="fitXY"
            android:src="@drawable/bdboss" />

        <ImageView
            android:id="@+id/p3"
            android:layout_width="292dp"
            android:layout_height="335dp"
            android:layout_marginLeft="20dp"
            android:layout_marginStart="20dp"
            android:layout_marginTop="30dp"
            android:contentDescription="@null"
            android:rotation="270"
            android:scaleType="fitXY"
            android:src="@drawable/img_5123" />

        <ImageView
            android:id="@+id/p4"
            android:layout_width="225dp"
            android:layout_height="279dp"
            android:layout_marginLeft="25dp"
            android:layout_marginStart="25dp"
            android:layout_marginTop="15dp"
            android:contentDescription="@null"
            android:scaleType="fitXY"
            android:src="@drawable/bestone1" />

    </LinearLayout>

</ScrollView>

</LinearLayout>
</code>```

`

答:
Parent LinearLayout is useless - no value added. You can achive the same in this way in simpler way:

```<code><ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#504b4b"
tools:context="com.example.sompod.imageview.MainActivity">

    <LinearLayout
        android:clipToPadding="false"
        android:padding="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_gravity="center"
        >

        <ImageView
            android:id="@+id/p1"
            android:layout_width="260dp"
            android:layout_height="260dp"

            android:layout_marginLeft="25dp"
            android:layout_marginStart="25dp"
            android:contentDescription="@null"
            android:rotation="270"

            android:scaleType="fitXY"
            android:src="@drawable/img_5116"
            />

        <ImageView
            android:id="@+id/p2"
            android:layout_width="300dp"
            android:layout_height="200dp"
            android:layout_marginLeft="15dp"
            android:layout_marginStart="15dp"
            android:layout_marginTop="25dp"
            android:contentDescription="@null"
            android:scaleType="fitXY"
            android:src="@drawable/bdboss" />

        <ImageView
            android:id="@+id/p3"
            android:layout_width="292dp"
            android:layout_height="335dp"
            android:layout_marginLeft="20dp"
            android:layout_marginStart="20dp"
            android:layout_marginTop="30dp"
            android:contentDescription="@null"
            android:rotation="270"
            android:scaleType="fitXY"
            android:src="@drawable/img_5123" />

        <ImageView
            android:id="@+id/p4"
            android:layout_width="225dp"
            android:layout_height="279dp"
            android:layout_marginLeft="25dp"
            android:layout_marginStart="25dp"
            android:layout_marginTop="15dp"
            android:contentDescription="@null"
            android:scaleType="fitXY"
            android:src="@drawable/bestone1" />

    </LinearLayout>

  </ScrollView>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Useless Parent layout

Body:
** This ScrollView layout or its LinearLayout parent is useless; transfer the background attribute to the other view  A layout with children that has no siblings, is not a scrollview or a root layout, and does not have a background, can be removed and have its children moved directly into the parent for a flatter and more efficient layout hierarchy. **

`

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"

android:padding="10dp"
android:background="#504b4b"
tools:context="com.example.sompod.imageview.MainActivity">

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:visibility="visible"
    >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_gravity="center"
        >

        <ImageView
            android:id="@+id/p1"
            android:layout_width="260dp"
            android:layout_height="260dp"

            android:layout_marginLeft="25dp"
            android:layout_marginStart="25dp"
            android:contentDescription="@null"
            android:rotation="270"

            android:scaleType="fitXY"
            android:src="@drawable/img_5116"
            />

        <ImageView
            android:id="@+id/p2"
            android:layout_width="300dp"
            android:layout_height="200dp"
            android:layout_marginLeft="15dp"
            android:layout_marginStart="15dp"
            android:layout_marginTop="25dp"
            android:contentDescription="@null"
            android:scaleType="fitXY"
            android:src="@drawable/bdboss" />

        <ImageView
            android:id="@+id/p3"
            android:layout_width="292dp"
            android:layout_height="335dp"
            android:layout_marginLeft="20dp"
            android:layout_marginStart="20dp"
            android:layout_marginTop="30dp"
            android:contentDescription="@null"
            android:rotation="270"
            android:scaleType="fitXY"
            android:src="@drawable/img_5123" />

        <ImageView
            android:id="@+id/p4"
            android:layout_width="225dp"
            android:layout_height="279dp"
            android:layout_marginLeft="25dp"
            android:layout_marginStart="25dp"
            android:layout_marginTop="15dp"
            android:contentDescription="@null"
            android:scaleType="fitXY"
            android:src="@drawable/bestone1" />

    </LinearLayout>

</ScrollView>

</LinearLayout>

`

Body:
Parent LinearLayout is useless - no value added. You can achive the same in this way in simpler way:

<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#504b4b"
tools:context="com.example.sompod.imageview.MainActivity">

    <LinearLayout
        android:clipToPadding="false"
        android:padding="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_gravity="center"
        >

        <ImageView
            android:id="@+id/p1"
            android:layout_width="260dp"
            android:layout_height="260dp"

            android:layout_marginLeft="25dp"
            android:layout_marginStart="25dp"
            android:contentDescription="@null"
            android:rotation="270"

            android:scaleType="fitXY"
            android:src="@drawable/img_5116"
            />

        <ImageView
            android:id="@+id/p2"
            android:layout_width="300dp"
            android:layout_height="200dp"
            android:layout_marginLeft="15dp"
            android:layout_marginStart="15dp"
            android:layout_marginTop="25dp"
            android:contentDescription="@null"
            android:scaleType="fitXY"
            android:src="@drawable/bdboss" />

        <ImageView
            android:id="@+id/p3"
            android:layout_width="292dp"
            android:layout_height="335dp"
            android:layout_marginLeft="20dp"
            android:layout_marginStart="20dp"
            android:layout_marginTop="30dp"
            android:contentDescription="@null"
            android:rotation="270"
            android:scaleType="fitXY"
            android:src="@drawable/img_5123" />

        <ImageView
            android:id="@+id/p4"
            android:layout_width="225dp"
            android:layout_height="279dp"
            android:layout_marginLeft="25dp"
            android:layout_marginStart="25dp"
            android:layout_marginTop="15dp"
            android:contentDescription="@null"
            android:scaleType="fitXY"
            android:src="@drawable/bestone1" />

    </LinearLayout>

  </ScrollView>


问:
Handling certificate errors in Android Webview and clearing the certificate peferences
I am trying to find a proper way to handle SSL certificate errors in the Android Webview.
My goal is to provide a way to load pages with SSL certificate errors, but let the user choose to load the page after warning him about security any time he tries to load a URL with certificate errors.

The closest solutions I found in threads suggest overriding the WebViewClient as following:

```<code>webView.setWebViewClient(new WebViewClient() {
    @Override
    public void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error) {
        handler.proceed();
    }
});
</code>```

However this basically disables SSL in the WebView without the user consent.

For reference here are the threads where I found that solution:

Android WebView SSL 'Security Warning'

Does the Web View on Android support SSL?

Android WebView not loading an HTTPS URL

android webview with client certificate

Web view shows blank/white page after loading URL when using WIFI in Android

Unable to load a specific webpage on Android webview

WebView displays a blank view for certain links

Android WebView blocks redirect from https to http

Ignore ssl certificate requests in webview

I went ahead and implemented a slightly different version which prompts the user:

```<code>webView.setWebViewClient(new WebViewClient() {
    @Override
    public void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error) {
        //Showing a first confirmation dialog
        AndroidUtils.showYesNoDialog(
            //First confirmation message
            "WARNING - THIS PAGE IS NOT SECURE! Are you sure you want to continue loading it?",
            //First confirmation "YES" option runnable
            new Runnable() {
                @Override
                public void run() {
                    //Showing a second confirmation dialog
                    AndroidUtils.showYesNoDialogWithResId(
                        //Second confirmation message
                        "You chose to load an unsecure page, are you sure you want to do that?",
                        //Second confirmation "YES" option runnable
                        new Runnable() {
                            @Override
                            public void run() {
                                //Disregard the error and proceed with the bad certificate anyways
                                handler.proceed();
                            }
                        },
                        //Second confirmation "NO" option runnable
                        new Runnable() {
                            @Override
                            public void run() {
                                //Cancel loading the page with that certificate error
                                handler.cancel();
                            }
                        }
                    );
                }
            },
            //First confirmation "NO" option runnable
            new Runnable() {
                @Override
                public void run() {
                    //Cancel loading the page with that certificate error
                    handler.cancel();
                }
            });
    }
});
</code>```

This implementation asks the user twice if he wants to load the page, if he says yes twice, then the error is disregarded and the page loads, otherwise the page loading is canceled.

The first time a URL with certificate error loads, WebViewClient.onReceivedSslError is called, however if the user proceeds with the certificate error and SslErrorHandler.proceed() is called, the following times the same URL loads, WebViewClient.onReceivedSslError is never called again: only killing the app resets this behavior.

I would want WebViewClient.onReceivedSslError to be called systematically when a URL with a certificate error loads, not just the first time. I tried calling those methods without success:

```<code>/** JAVADOC QUOTE: Clears the SSL preferences table stored in response to proceeding with SSL certificate errors.*/
webView.clearSslPreferences();
//Those other methods I tried out of despair just in case
webView.clearFormData();
webView.clearCache(true);
webView.clearHistory();
webView.clearMatches();
</code>```

Does anybody know how to make the WebView call WebViewClient.onReceivedSslError more than once for the same URL, after SslErrorHandler.proceed() has been called?

答:
I will just post the answer that Tssomas has given in the original question's comments, because after all this time, it's the only solution that works reliably even though it's a hack.

Quoting Tssomas:

If the user proceeds, their preference to go ahead anyway is only kept
  for that session (if they close the app and start it again the dialog
  will re-show). So what i did to make sure the user sees the dialog
  every time was to add the unsecure url to an array list and add a
  check so that every time the webview finishes loading, the array list
  is checked for the webview's current url. So then of course, if the
  array list contains the current url, show the dialog.. its not a
  pretty solution at all but it works...

This is how the code might look like...

```<code>//This has to be static because it will be reset only once the app process is killed
private static final Set<String> unsecureURLSet = new TreeSet<>();

webView.setWebViewClient(new WebViewClient() {
    @Override
    public void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error) {
        //Adding the insecure URL to the set
        unsecureURLSet.add(error.getUrl());
        //Showing a first confirmation dialog
        AndroidUtils.showYesNoDialog(
            //First confirmation message
            "WARNING - THIS PAGE IS NOT SECURE! Are you sure you want to continue loading it?",
            //First confirmation "YES" option runnable
            new Runnable() {
                @Override
                public void run() {
                    //Showing a second confirmation dialog
                    AndroidUtils.showYesNoDialogWithResId(
                        //Second confirmation message
                        "You chose to load an unsecure page, are you sure you want to do that?",
                        //Second confirmation "YES" option runnable
                        new Runnable() {
                            @Override
                            public void run() {
                                //Disregard the error and proceed with the bad certificate anyways
                                handler.proceed();
                            }
                        },
                        //Second confirmation "NO" option runnable
                        new Runnable() {
                            @Override
                            public void run() {
                                //Cancel loading the page with that certificate error
                                handler.cancel();
                            }
                        }
                    );
                }
            },
            //First confirmation "NO" option runnable
            new Runnable() {
                @Override
                public void run() {
                    //Cancel loading the page with that certificate error
                    handler.cancel();
                }
            });
    }

    @Override
    public boolean shouldOverrideUrlLoading(final WebView _view, final String _url) {
        if (unsecureURLSet.contains(_url)){
            //Code here should mimic the dialog in onReceivedSslError
            //And replace the "handler.proceed()" with a forced load of _url
            return true;
        }
        return super.shouldOverrideUrlLoading(_view, _url);
    }
});
</code>```

Body:
I am trying to find a proper way to handle SSL certificate errors in the Android Webview.
My goal is to provide a way to load pages with SSL certificate errors, but let the user choose to load the page after warning him about security any time he tries to load a URL with certificate errors.

The closest solutions I found in threads suggest overriding the WebViewClient as following:

webView.setWebViewClient(new WebViewClient() {
    @Override
    public void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error) {
        handler.proceed();
    }
});

However this basically disables SSL in the WebView without the user consent.

For reference here are the threads where I found that solution:

Android WebView SSL 'Security Warning'

Does the Web View on Android support SSL?

Android WebView not loading an HTTPS URL

android webview with client certificate

Web view shows blank/white page after loading URL when using WIFI in Android

Unable to load a specific webpage on Android webview

WebView displays a blank view for certain links

Android WebView blocks redirect from https to http

Ignore ssl certificate requests in webview

I went ahead and implemented a slightly different version which prompts the user:

webView.setWebViewClient(new WebViewClient() {
    @Override
    public void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error) {
        //Showing a first confirmation dialog
        AndroidUtils.showYesNoDialog(
            //First confirmation message
            "WARNING - THIS PAGE IS NOT SECURE! Are you sure you want to continue loading it?",
            //First confirmation "YES" option runnable
            new Runnable() {
                @Override
                public void run() {
                    //Showing a second confirmation dialog
                    AndroidUtils.showYesNoDialogWithResId(
                        //Second confirmation message
                        "You chose to load an unsecure page, are you sure you want to do that?",
                        //Second confirmation "YES" option runnable
                        new Runnable() {
                            @Override
                            public void run() {
                                //Disregard the error and proceed with the bad certificate anyways
                                handler.proceed();
                            }
                        },
                        //Second confirmation "NO" option runnable
                        new Runnable() {
                            @Override
                            public void run() {
                                //Cancel loading the page with that certificate error
                                handler.cancel();
                            }
                        }
                    );
                }
            },
            //First confirmation "NO" option runnable
            new Runnable() {
                @Override
                public void run() {
                    //Cancel loading the page with that certificate error
                    handler.cancel();
                }
            });
    }
});

This implementation asks the user twice if he wants to load the page, if he says yes twice, then the error is disregarded and the page loads, otherwise the page loading is canceled.

The first time a URL with certificate error loads, WebViewClient.onReceivedSslError is called, however if the user proceeds with the certificate error and SslErrorHandler.proceed() is called, the following times the same URL loads, WebViewClient.onReceivedSslError is never called again: only killing the app resets this behavior.

I would want WebViewClient.onReceivedSslError to be called systematically when a URL with a certificate error loads, not just the first time. I tried calling those methods without success:

/** JAVADOC QUOTE: Clears the SSL preferences table stored in response to proceeding with SSL certificate errors.*/
webView.clearSslPreferences();
//Those other methods I tried out of despair just in case
webView.clearFormData();
webView.clearCache(true);
webView.clearHistory();
webView.clearMatches();

Does anybody know how to make the WebView call WebViewClient.onReceivedSslError more than once for the same URL, after SslErrorHandler.proceed() has been called?

Body:
I will just post the answer that Tssomas has given in the original question's comments, because after all this time, it's the only solution that works reliably even though it's a hack.

Quoting Tssomas:

If the user proceeds, their preference to go ahead anyway is only kept
  for that session (if they close the app and start it again the dialog
  will re-show). So what i did to make sure the user sees the dialog
  every time was to add the unsecure url to an array list and add a
  check so that every time the webview finishes loading, the array list
  is checked for the webview's current url. So then of course, if the
  array list contains the current url, show the dialog.. its not a
  pretty solution at all but it works...

This is how the code might look like...

//This has to be static because it will be reset only once the app process is killed
private static final Set<String> unsecureURLSet = new TreeSet<>();

webView.setWebViewClient(new WebViewClient() {
    @Override
    public void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error) {
        //Adding the insecure URL to the set
        unsecureURLSet.add(error.getUrl());
        //Showing a first confirmation dialog
        AndroidUtils.showYesNoDialog(
            //First confirmation message
            "WARNING - THIS PAGE IS NOT SECURE! Are you sure you want to continue loading it?",
            //First confirmation "YES" option runnable
            new Runnable() {
                @Override
                public void run() {
                    //Showing a second confirmation dialog
                    AndroidUtils.showYesNoDialogWithResId(
                        //Second confirmation message
                        "You chose to load an unsecure page, are you sure you want to do that?",
                        //Second confirmation "YES" option runnable
                        new Runnable() {
                            @Override
                            public void run() {
                                //Disregard the error and proceed with the bad certificate anyways
                                handler.proceed();
                            }
                        },
                        //Second confirmation "NO" option runnable
                        new Runnable() {
                            @Override
                            public void run() {
                                //Cancel loading the page with that certificate error
                                handler.cancel();
                            }
                        }
                    );
                }
            },
            //First confirmation "NO" option runnable
            new Runnable() {
                @Override
                public void run() {
                    //Cancel loading the page with that certificate error
                    handler.cancel();
                }
            });
    }

    @Override
    public boolean shouldOverrideUrlLoading(final WebView _view, final String _url) {
        if (unsecureURLSet.contains(_url)){
            //Code here should mimic the dialog in onReceivedSslError
            //And replace the "handler.proceed()" with a forced load of _url
            return true;
        }
        return super.shouldOverrideUrlLoading(_view, _url);
    }
});


问:
Receiving the key value pair as input parameter
I am trying to receive the below key value pair as the input parameter to my Web API

```<code>json=%7B%0A%22MouseSampleBarcode%22%20%3A%20%22MOS81%22%0A%7D%0A
</code>```

where the right of the string is the URL encoded JSON which looks like

```<code>{
"MouseSampleBarcode" : "MOS81"
}
</code>```

How can I parse this and store them in to the Model class

```<code> [HttpPost]
 public async Task<IHttpActionResult> Get([FromBody] CoreBarCodeDTO.RootObject coreBarCode)
 {
  string Bar_Code = coreBarCode.MouseSampleBarcode.ToString();
</code>```

where the CoreBarCodeDTO looks like below

```<code>public class CoreBarCodeDTO
{
    public class RootObject
    {
        public string MouseSampleBarcode { get; set; }
    }
 }
</code>```

答:
So, as I said: Get doesn't have body.

Follow @KinSlayerUY answer.

```<code>[HttpPost("/")]
public async Task<IHttpActionResult> Post([FromBody] CoreBarCodeDTO.RootObject coreBarCode)
{
   string Bar_Code = coreBarCode.MouseSampleBarcode.ToString();
   ...
}
</code>```

If you need use GET remove [FromBody] attribute and send data as single parameters

```<code>[HttpGet("/")]
public async Task<IHttpActionResult> Get(string mouseSampleBarcode)
{
   var rootObject = new CoreBarCodeDTO.RootObject
   {
        MouseSampleBarcode = mouseSampleBarcode
   }
   ...
}
</code>```

Body:
I am trying to receive the below key value pair as the input parameter to my Web API

json=%7B%0A%22MouseSampleBarcode%22%20%3A%20%22MOS81%22%0A%7D%0A

where the right of the string is the URL encoded JSON which looks like

{
"MouseSampleBarcode" : "MOS81"
}

How can I parse this and store them in to the Model class

 [HttpPost]
 public async Task<IHttpActionResult> Get([FromBody] CoreBarCodeDTO.RootObject coreBarCode)
 {
  string Bar_Code = coreBarCode.MouseSampleBarcode.ToString();

where the CoreBarCodeDTO looks like below

public class CoreBarCodeDTO
{
    public class RootObject
    {
        public string MouseSampleBarcode { get; set; }
    }
 }

Body:
So, as I said: Get doesn't have body.

Follow @KinSlayerUY answer.

[HttpPost("/")]
public async Task<IHttpActionResult> Post([FromBody] CoreBarCodeDTO.RootObject coreBarCode)
{
   string Bar_Code = coreBarCode.MouseSampleBarcode.ToString();
   ...
}

If you need use GET remove [FromBody] attribute and send data as single parameters

[HttpGet("/")]
public async Task<IHttpActionResult> Get(string mouseSampleBarcode)
{
   var rootObject = new CoreBarCodeDTO.RootObject
   {
        MouseSampleBarcode = mouseSampleBarcode
   }
   ...
}


问:
Why is the error "Not a valid command: assembly-merge-strategy"?
I have the following build.sbt file.

```<code>import AssemblyKeys._

name := "approxstrmatch"

version := "1.0"

scalaVersion := "2.10.4"

libraryDependencies+="org.apache.spark" %% "spark-core" % "1.0.0"

resolvers += "AkkaRepository" at "http://repo.akka.io/releases/"

// My merge strategy is specified here.

lazy val app = Project("approxstrmatch", file("approxstrmatch"),
    settings = buildSettings ++ assemblySettings ++ Seq(
    mergeStrategy in assembly <<= (mergeStrategy in assembly) { (old) =>
    {
        case PathList("javax", "servlet", xs @ _*)         => MergeStrategy.first
        case PathList("javax", "transaction", xs @ _*)     => MergeStrategy.first
        case PathList("javax", "mail", xs @ _*)     => MergeStrategy.first
        case PathList("javax", "activation", xs @ _*)     => MergeStrategy.first
        case PathList(ps @ _*) if ps.last endsWith ".html" => MergeStrategy.first
        case "application.conf" => MergeStrategy.concat
        case "unwanted.txt"     => MergeStrategy.discard
        case x => old(x)
        }
    })
  )

mainClass in assembly := Some("approxstrmatch.JaccardScore")
// jarName in assembly := "approstrmatch.jar"
</code>```

When I execute the following command sbt assembly-merge-strategy there's an error I don't understand. Any help appreciated.

```<code>approxstrmatch]$ sbt assembly-merge-strategy
[info] Loading project definition from /apps/sameert/software/approxstrmatch/project
[info] Set current project to approxstrmatch (in buildfile:/apps/sameert/software/approxstrmatch/)
[error] Not a valid command: assembly-merge-strategy
[error] No such setting/task
</code>```

答: add assemblySettings in your build.sbt will help

Body:
I have the following build.sbt file.

import AssemblyKeys._

name := "approxstrmatch"

version := "1.0"

scalaVersion := "2.10.4"

libraryDependencies+="org.apache.spark" %% "spark-core" % "1.0.0"

resolvers += "AkkaRepository" at "http://repo.akka.io/releases/"

// My merge strategy is specified here.

lazy val app = Project("approxstrmatch", file("approxstrmatch"),
    settings = buildSettings ++ assemblySettings ++ Seq(
    mergeStrategy in assembly <<= (mergeStrategy in assembly) { (old) =>
    {
        case PathList("javax", "servlet", xs @ _*)         => MergeStrategy.first
        case PathList("javax", "transaction", xs @ _*)     => MergeStrategy.first
        case PathList("javax", "mail", xs @ _*)     => MergeStrategy.first
        case PathList("javax", "activation", xs @ _*)     => MergeStrategy.first
        case PathList(ps @ _*) if ps.last endsWith ".html" => MergeStrategy.first
        case "application.conf" => MergeStrategy.concat
        case "unwanted.txt"     => MergeStrategy.discard
        case x => old(x)
        }
    })
  )

mainClass in assembly := Some("approxstrmatch.JaccardScore")
// jarName in assembly := "approstrmatch.jar"

When I execute the following command sbt assembly-merge-strategy there's an error I don't understand. Any help appreciated.

approxstrmatch]$ sbt assembly-merge-strategy
[info] Loading project definition from /apps/sameert/software/approxstrmatch/project
[info] Set current project to approxstrmatch (in buildfile:/apps/sameert/software/approxstrmatch/)
[error] Not a valid command: assembly-merge-strategy
[error] No such setting/task


问:
How to test the connection to a db2 database
I need to test the connection to a db2 database.

With oracle databases I'd execute a 'select * from dual' in order to do this.

But dual is specific for oracle. Is there a similar canonical test sql statement for db2?

答:
```<code>LIST DB DIRECTORY
</code>```

or

```<code>LIST TABLES
</code>```

ContentLicense: CC BY-SA 2.5

Body:
LIST DB DIRECTORY

or

LIST TABLES


问:
Is it possible to use a user input's value in sass?
I am creating a colour palette and i have seen a lot of ways online to it using sass which i am using in the project, however i am taking a user input (hex code) and wish to print them out with different percentage variants - to show the user a lighter/darker version of #ff0000 for example.

Is this possible? I have seen things such as:

```<code>$color: #3cb878;
$light: lighten($color,15%);
$dark: darken($color,15%);
</code>```

And ideally i would like "$color" to be the user input and then i can print multiple percentage variants out.

Thanks!

答: Since SASS has to be compiled to CSS for the browser, you could use a Javascript function to lighten or darken your users inputted color using this link from CSS Tricks.</p>

Body:
I am creating a colour palette and i have seen a lot of ways online to it using sass which i am using in the project, however i am taking a user input (hex code) and wish to print them out with different percentage variants - to show the user a lighter/darker version of #ff0000 for example.

Is this possible? I have seen things such as:

$color: #3cb878;
$light: lighten($color,15%);
$dark: darken($color,15%);

And ideally i would like "$color" to be the user input and then i can print multiple percentage variants out.

Thanks!


问:
What's the difference between discarding a changeset and keep target version when resolving conflicts in Microsoft TFS Source Control
when you are merging your changeset in Microsoft TFS Source Control, your changes may come into a conflict, then if it couldn't become auto-resolved, you have to resolve it by yourself. or you can take source version or keep target version.
another workaround is to discard your changeset.</p>

<p>"keep target version" and "discarding changeset", both of them are saying that the target version is the correct one that will be kept.
So, what's the difference between them exactly? why both of them exist? </p>

答:
The difference is in the subtle way the history is kept. When you "Keep target version" a change ticket is stored with the merge telling it to ignore the differences in the future.

When you "undo" the changes in the merge, no ticket is logged and a future merge between those branches/files will propose to merge those changes again.

You'd perform the second (undo) if you have changes that are not yet ready to merge to the target branch, but were (accidentally) selected as part of the merge action.

You'd perform the first (Take/Keep) if you want that version to become leading and do not want to merge those differences in the future.

Many developers do not understand the difference and issues can occur when you have long-living branches, like dev & main. If people use "keep target" a lot, a merge between dev and main would not show any changes to merge, but a diff between the two may bring a lot of differences to light. In general I guide teams towards undoing the changes vs picking "keep mine" or "take theirs".

Body:
when you are merging your changeset in Microsoft TFS Source Control, your changes may come into a conflict, then if it couldn't become auto-resolved, you have to resolve it by yourself. or you can take source version or keep target version.
another workaround is to discard your changeset.

"keep target version" and "discarding changeset", both of them are saying that the target version is the correct one that will be kept.
So, what's the difference between them exactly? why both of them exist?


问:
Python pandas - extract and replace
I have a Pandas data frame column containing elements similar to the string McNally, King  (XYZ). I would like to keep the last name, first name and remove everything else. Therefore after cleaning McNally, King  (XYZ) should be McNally, King.

I have tried following two functions but not getting the desired result:

```<code>df['name'] = df['name'].str.extract(r'\w+\,\s[A-Z][a-z]+', expand=False)

df['name'] = df['name'].replace({r'\w+\,\s[A-Z][a-z]+' : r'\w+\,\s[A-Z][a-z]+'}, regex=True)
</code>```

Second code replaces the substring with the regex itself, while the first code extracts the names from the string but I want to keep the name and remove everything else followed by the name.

Edit:
Sample data:

```<code>Reyes, Rebecca  L (XYZ)
Derry, Odd     P (XYZ)
Garza, Per-Laura   A (MNP)
Fernandez, Rafael   Carl (XYZ)
</code>```

Expected output:

```<code>Reyes, Rebecca
Derry, Odd
Garza, Per-Laura
Fernandez, Rafael
</code>```

I would like to edit-in-place i.e. modify the existing datafame itself and not creating a new one.

答:
You can try something like this:

```<code>df = pd.DataFrame({'name':['McNally, King  (XYZ)']}, index=[0])
df['name'].str.extract(r'(\w+,\s\w+)')
</code>```

Output:

```<code>0    McNally, King
Name: name, dtype: object
</code>```

Title: Python pandas - extract and replace

Body:
I have a Pandas data frame column containing elements similar to the string McNally, King  (XYZ). I would like to keep the last name, first name and remove everything else. Therefore after cleaning McNally, King  (XYZ) should be McNally, King.

I have tried following two functions but not getting the desired result:

df['name'] = df['name'].str.extract(r'\w+\,\s[A-Z][a-z]+', expand=False)

df['name'] = df['name'].replace({r'\w+\,\s[A-Z][a-z]+' : r'\w+\,\s[A-Z][a-z]+'}, regex=True)

Second code replaces the substring with the regex itself, while the first code extracts the names from the string but I want to keep the name and remove everything else followed by the name.

Edit:
Sample data:

Reyes, Rebecca  L (XYZ)
Derry, Odd     P (XYZ)
Garza, Per-Laura   A (MNP)
Fernandez, Rafael   Carl (XYZ)

Expected output:

Reyes, Rebecca
Derry, Odd
Garza, Per-Laura
Fernandez, Rafael

I would like to edit-in-place i.e. modify the existing datafame itself and not creating a new one.

Body:
You can try something like this:

df = pd.DataFrame({'name':['McNally, King  (XYZ)']}, index=[0])
df['name'].str.extract(r'(\w+,\s\w+)')

Output:

0    McNally, King
Name: name, dtype: object


问:
Vue-toastr and Vue2 how to set global options for toastr?
I'm using vue-toastr on my Laravel 5.5 and Vuejs 2 project.

The toasts are being showednormally, but I want to set some options globally for the toasts, like position...

I can't do this.

In my app.js file I've imported toastr from vue-toastr, required the styles and then Vue.component('vue-toastr', Toastr);.

I've tried this.$refs.toastr.defaultPosition = "toast-bottom-left" on my app.js like the docs say but it gives me an error Cannot read property 'toastr' of undefined

Any help?

答:
As covered in the documentation:

Add component html: for vue 1.x

```<code><vue-toastr v-ref:toastr></vue-toastr>
</code>```

Add component html: for vue 2.x

```<code><vue-toastr ref="toastr"></vue-toastr>
</code>```

Then you can use

```<code>this.$refs.toastr.defaultPosition = "toast-bottom-left"
</code>```

Body:
As covered in the documentation:

Add component html: for vue 1.x

<vue-toastr v-ref:toastr></vue-toastr>

Add component html: for vue 2.x

<vue-toastr ref="toastr"></vue-toastr>

Then you can use

this.$refs.toastr.defaultPosition = "toast-bottom-left"


问:
Chaining string operations on Pandas Series
I recently found out about the str method for Pandas series and it's great! However if I want to chain operations (say, a couple replace and a strip) I need to keep calling str after every operation, making it not the most elegant code.

For example, lets say my column names contain spaces and periods and I want to replace them by underscores. I might also want to strip any leftover underscores. If I wanted to do this using str methods, is there any way of avoiding having to run:

df.columns.str.replace(' ', '_').str.replace('.', '_').str.strip('_')

Thanks!

答:
Why not use a list comprehension?

```<code>import re
df.columns = [re.sub('[\s.]', '_', x).strip('_') for x in df.columns]
</code>```

In a list comp, you're working with the string object directly, without the need to call .str each time.

Body:
Why not use a list comprehension?

import re
df.columns = [re.sub('[\s.]', '_', x).strip('_') for x in df.columns]

In a list comp, you're working with the string object directly, without the need to call .str each time.


问:
IIS 7.5 Express New Virtual Dir
how do i add new virtual directory?

I'm getting error (The type or namespace name 'xxx' could not be found) but the files are all in /bin.

i have tried editing the applicationhost.config like this:

```<code><site name="WebSite1" id="1" serverAutoStart="true">
    <application path="/" applicationPool="Clr2IntegratedAppPool">
        <virtualDirectory path="/" physicalPath="%IIS_SITES_HOME%\WebSite1" />
        <virtualDirectory path="/SubFolderApp" physicalPath="%IIS_SITES_HOME%\WebSite1\SubFolderApp" allowSubDirConfig="true" />
    </application>
    <bindings>
        <binding protocol="http" bindingInformation=":80:localhost" />
    </bindings>
</site>
</code>```

答:
You need to create a child application. Your configuration created child virtual directory. The configuration below turns /SubFolderApp into an application.</p>

```<code><site name="WebSite1" id="1" serverAutoStart="true">
   <application path="/" applicationPool="Clr2IntegratedAppPool">
     <virtualDirectory path="/" physicalPath="%IIS_SITES_HOME%\WebSite1" />
   </application>
   <application path="="/SubFolderApp" applicationPool="Clr2IntegratedAppPool">
     <virtualDirectory path="/" physicalPath="%IIS_SITES_HOME%\WebSite1\SubFolderApp" />
   </application>
    <bindings>
      <binding protocol="http" bindingInformation=":80:localhost" />
   </bindings>
</site>
</code>```

Title: IIS 7.5 Express New Virtual Dir

Body:
how do i add new virtual directory?

I'm getting error (The type or namespace name 'xxx' could not be found) but the files are all in /bin.

i have tried editing the applicationhost.config like this:

<site name="WebSite1" id="1" serverAutoStart="true">
    <application path="/" applicationPool="Clr2IntegratedAppPool">
        <virtualDirectory path="/" physicalPath="%IIS_SITES_HOME%\WebSite1" />
        <virtualDirectory path="/SubFolderApp" physicalPath="%IIS_SITES_HOME%\WebSite1\SubFolderApp" allowSubDirConfig="true" />
    </application>
    <bindings>
        <binding protocol="http" bindingInformation=":80:localhost" />
    </bindings>
</site>

Body:
You need to create a child application. Your configuration created child virtual directory. The configuration below turns /SubFolderApp into an application.

<site name="WebSite1" id="1" serverAutoStart="true">
   <application path="/" applicationPool="Clr2IntegratedAppPool">
     <virtualDirectory path="/" physicalPath="%IIS_SITES_HOME%\WebSite1" />
   </application>
   <application path="="/SubFolderApp" applicationPool="Clr2IntegratedAppPool">
     <virtualDirectory path="/" physicalPath="%IIS_SITES_HOME%\WebSite1\SubFolderApp" />
   </application>
    <bindings>
      <binding protocol="http" bindingInformation=":80:localhost" />
   </bindings>
</site>


问:
"Magnific Popup" and leaving when hovering a div that opens a popup
After closing the popup, the div should be hidden (and when the pop-up is open it really hides), but when the pop-up is closed, it becomes visible.

// Magnific Popup v1.1.0 by Dmitry Semenov
(function(a){typeof define=="function"&&define.amd?define(["jquery"],a):typeof exports=="object"?a(require("jquery")):a(window.jQuery||window.Zepto)})(function(a){var b="Close",c="BeforeClose",d="AfterClose",e="BeforeAppend",f="MarkupParse",g="Open",h="Change",i="mfp",j="."+i,k="mfp-ready",l="mfp-removing",m="mfp-prevent-close",n,o=function(){},p=!!window.jQuery,q,r=a(window),s,t,u,v,w=function(a,b){n.ev.on(i+a+j,b)},x=function(b,c,d,e){var f=document.createElement("div");return f.className="mfp-"+b,d&&(f.innerHTML=d),e?c&&c.appendChild(f):(f=a(f),c&&f.appendTo(c)),f},y=function(b,c){n.ev.triggerHandler(i+b,c),n.st.callbacks&&(b=b.charAt(0).toLowerCase()+b.slice(1),n.st.callbacks[b]&&n.st.callbacks[b].apply(n,a.isArray(c)?c:[c]))},z=function(b){if(b!==v||!n.currTemplate.closeBtn)n.currTemplate.closeBtn=a(n.st.closeMarkup.replace("%title%",n.st.tClose)),v=b;return n.currTemplate.closeBtn},A=function(){a.magnificPopup.instance||(n=new o,n.init(),a.magnificPopup.instance=n)},B=function(){var a=document.createElement("p").style,b=["ms","O","Moz","Webkit"];if(a.transition!==undefined)return!0;while(b.length)if(b.pop()+"Transition"in a)return!0;return!1};o.prototype={constructor:o,init:function(){var b=navigator.appVersion;n.isLowIE=n.isIE8=document.all&&!document.addEventListener,n.isAndroid=/android/gi.test(b),n.isIOS=/iphone|ipad|ipod/gi.test(b),n.supportsTransition=B(),n.probablyMobile=n.isAndroid||n.isIOS||/(Opera Mini)|Kindle|webOS|BlackBerry|(Opera Mobi)|(Windows Phone)|IEMobile/i.test(navigator.userAgent),s=a(document),n.popupsCache={}},open:function(b){var c;if(b.isObj===!1){n.items=b.items.toArray(),n.index=0;var d=b.items,e;for(c=0;c<d.length;c++){e=d[c],e.parsed&&(e=e.el[0]);if(e===b.el[0]){n.index=c;break}}}else n.items=a.isArray(b.items)?b.items:[b.items],n.index=b.index||0;if(n.isOpen){n.updateItemHTML();return}n.types=[],u="",b.mainEl&&b.mainEl.length?n.ev=b.mainEl.eq(0):n.ev=s,b.key?(n.popupsCache[b.key]||(n.popupsCache[b.key]={}),n.currTemplate=n.popupsCache[b.key]):n.currTemplate={},n.st=a.extend(!0,{},a.magnificPopup.defaults,b),n.fixedContentPos=n.st.fixedContentPos==="auto"?!n.probablyMobile:n.st.fixedContentPos,n.st.modal&&(n.st.closeOnContentClick=!1,n.st.closeOnBgClick=!1,n.st.showCloseBtn=!1,n.st.enableEscapeKey=!1),n.bgOverlay||(n.bgOverlay=x("bg").on("click"+j,function(){n.close()}),n.wrap=x("wrap").attr("tabindex",-1).on("click"+j,function(a){n._checkIfClose(a.target)&&n.close()}),n.container=x("container",n.wrap)),n.contentContainer=x("content"),n.st.preloader&&(n.preloader=x("preloader",n.container,n.st.tLoading));var h=a.magnificPopup.modules;for(c=0;c<h.length;c++){var i=h[c];i=i.charAt(0).toUpperCase()+i.slice(1),n["init"+i].call(n)}y("BeforeOpen"),n.st.showCloseBtn&&(n.st.closeBtnInside?(w(f,function(a,b,c,d){c.close_replaceWith=z(d.type)}),u+=" mfp-close-btn-in"):n.wrap.append(z())),n.st.alignTop&&(u+=" mfp-align-top"),n.fixedContentPos?n.wrap.css({overflow:n.st.overflowY,overflowX:"hidden",overflowY:n.st.overflowY}):n.wrap.css({top:r.scrollTop(),position:"absolute"}),(n.st.fixedBgPos===!1||n.st.fixedBgPos==="auto"&&!n.fixedContentPos)&&n.bgOverlay.css({height:s.height(),position:"absolute"}),n.st.enableEscapeKey&&s.on("keyup"+j,function(a){a.keyCode===27&&n.close()}),r.on("resize"+j,function(){n.updateSize()}),n.st.closeOnContentClick||(u+=" mfp-auto-cursor"),u&&n.wrap.addClass(u);var l=n.wH=r.height(),m={};if(n.fixedContentPos&&n._hasScrollBar(l)){var o=n._getScrollbarSize();o&&(m.marginRight=o)}n.fixedContentPos&&(n.isIE7?a("body, html").css("overflow","hidden"):m.overflow="hidden");var p=n.st.mainClass;return n.isIE7&&(p+=" mfp-ie7"),p&&n._addClassToMFP(p),n.updateItemHTML(),y("BuildControls"),a("html").css(m),n.bgOverlay.add(n.wrap).prependTo(n.st.prependTo||a(document.body)),n._lastFocusedEl=document.activeElement,setTimeout(function(){n.content?(n._addClassToMFP(k),n._setFocus()):n.bgOverlay.addClass(k),s.on("focusin"+j,n._onFocusIn)},16),n.isOpen=!0,n.updateSize(l),y(g),b},close:function(){if(!n.isOpen)return;y(c),n.isOpen=!1,n.st.removalDelay&&!n.isLowIE&&n.supportsTransition?(n._addClassToMFP(l),setTimeout(function(){n._close()},n.st.removalDelay)):n._close()},_close:function(){y(b);var c=l+" "+k+" ";n.bgOverlay.detach(),n.wrap.detach(),n.container.empty(),n.st.mainClass&&(c+=n.st.mainClass+" "),n._removeClassFromMFP(c);if(n.fixedContentPos){var e={marginRight:""};n.isIE7?a("body, html").css("overflow",""):e.overflow="",a("html").css(e)}s.off("keyup"+j+" focusin"+j),n.ev.off(j),n.wrap.attr("class","mfp-wrap").removeAttr("style"),n.bgOverlay.attr("class","mfp-bg"),n.container.attr("class","mfp-container"),n.st.showCloseBtn&&(!n.st.closeBtnInside||n.currTemplate[n.currItem.type]===!0)&&n.currTemplate.closeBtn&&n.currTemplate.closeBtn.detach(),n.st.autoFocusLast&&n._lastFocusedEl&&a(n._lastFocusedEl).focus(),n.currItem=null,n.content=null,n.currTemplate=null,n.prevHeight=0,y(d)},updateSize:function(a){if(n.isIOS){var b=document.documentElement.clientWidth/window.innerWidth,c=window.innerHeight*b;n.wrap.css("height",c),n.wH=c}else n.wH=a||r.height();n.fixedContentPos||n.wrap.css("height",n.wH),y("Resize")},updateItemHTML:function(){var b=n.items[n.index];n.contentContainer.detach(),n.content&&n.content.detach(),b.parsed||(b=n.parseEl(n.index));var c=b.type;y("BeforeChange",[n.currItem?n.currItem.type:"",c]),n.currItem=b;if(!n.currTemplate[c]){var d=n.st[c]?n.st[c].markup:!1;y("FirstMarkupParse",d),d?n.currTemplate[c]=a(d):n.currTemplate[c]=!0}t&&t!==b.type&&n.container.removeClass("mfp-"+t+"-holder");var e=n["get"+c.charAt(0).toUpperCase()+c.slice(1)](b,n.currTemplate[c]);n.appendContent(e,c),b.preloaded=!0,y(h,b),t=b.type,n.container.prepend(n.contentContainer),y("AfterChange")},appendContent:function(a,b){n.content=a,a?n.st.showCloseBtn&&n.st.closeBtnInside&&n.currTemplate[b]===!0?n.content.find(".mfp-close").length||n.content.append(z()):n.content=a:n.content="",y(e),n.container.addClass("mfp-"+b+"-holder"),n.contentContainer.append(n.content)},parseEl:function(b){var c=n.items[b],d;c.tagName?c={el:a(c)}:(d=c.type,c={data:c,src:c.src});if(c.el){var e=n.types;for(var f=0;f<e.length;f++)if(c.el.hasClass("mfp-"+e[f])){d=e[f];break}c.src=c.el.attr("data-mfp-src"),c.src||(c.src=c.el.attr("href"))}return c.type=d||n.st.type||"inline",c.index=b,c.parsed=!0,n.items[b]=c,y("ElementParse",c),n.items[b]},addGroup:function(a,b){var c=function(c){c.mfpEl=this,n._openClick(c,a,b)};b||(b={});var d="click.magnificPopup";b.mainEl=a,b.items?(b.isObj=!0,a.off(d).on(d,c)):(b.isObj=!1,b.delegate?a.off(d).on(d,b.delegate,c):(b.items=a,a.off(d).on(d,c)))},_openClick:function(b,c,d){var e=d.midClick!==undefined?d.midClick:a.magnificPopup.defaults.midClick;if(!e&&(b.which===2||b.ctrlKey||b.metaKey||b.altKey||b.shiftKey))return;var f=d.disableOn!==undefined?d.disableOn:a.magnificPopup.defaults.disableOn;if(f)if(a.isFunction(f)){if(!f.call(n))return!0}else if(r.width()<f)return!0;b.type&&(b.preventDefault(),n.isOpen&&b.stopPropagation()),d.el=a(b.mfpEl),d.delegate&&(d.items=c.find(d.delegate)),n.open(d)},updateStatus:function(a,b){if(n.preloader){q!==a&&n.container.removeClass("mfp-s-"+q),!b&&a==="loading"&&(b=n.st.tLoading);var c={status:a,text:b};y("UpdateStatus",c),a=c.status,b=c.text,n.preloader.html(b),n.preloader.find("a").on("click",function(a){a.stopImmediatePropagation()}),n.container.addClass("mfp-s-"+a),q=a}},_checkIfClose:function(b){if(a(b).hasClass(m))return;var c=n.st.closeOnContentClick,d=n.st.closeOnBgClick;if(c&&d)return!0;if(!n.content||a(b).hasClass("mfp-close")||n.preloader&&b===n.preloader[0])return!0;if(b!==n.content[0]&&!a.contains(n.content[0],b)){if(d&&a.contains(document,b))return!0}else if(c)return!0;return!1},_addClassToMFP:function(a){n.bgOverlay.addClass(a),n.wrap.addClass(a)},_removeClassFromMFP:function(a){this.bgOverlay.removeClass(a),n.wrap.removeClass(a)},_hasScrollBar:function(a){return(n.isIE7?s.height():document.body.scrollHeight)>(a||r.height())},_setFocus:function(){(n.st.focus?n.content.find(n.st.focus).eq(0):n.wrap).focus()},_onFocusIn:function(b){if(b.target!==n.wrap[0]&&!a.contains(n.wrap[0],b.target))return n._setFocus(),!1},_parseMarkup:function(b,c,d){var e;d.data&&(c=a.extend(d.data,c)),y(f,[b,c,d]),a.each(c,function(c,d){if(d===undefined||d===!1)return!0;e=c.split("_");if(e.length>1){var f=b.find(j+"-"+e[0]);if(f.length>0){var g=e[1];g==="replaceWith"?f[0]!==d[0]&&f.replaceWith(d):g==="img"?f.is("img")?f.attr("src",d):f.replaceWith(a("").attr("src",d).attr("class",f.attr("class"))):f.attr(e[1],d)}}else b.find(j+"-"+c).html(d)})},_getScrollbarSize:function(){if(n.scrollbarSize===undefined){var a=document.createElement("div");a.style.cssText="width: 99px; height: 99px; overflow: scroll; position: absolute; top: -9999px;",document.body.appendChild(a),n.scrollbarSize=a.offsetWidth-a.clientWidth,document.body.removeChild(a)}return n.scrollbarSize}},a.magnificPopup={instance:null,proto:o.prototype,modules:[],open:function(b,c){return A(),b?b=a.extend(!0,{},b):b={},b.isObj=!0,b.index=c||0,this.instance.open(b)},close:function(){return a.magnificPopup.instance&&a.magnificPopup.instance.close()},registerModule:function(b,c){c.options&&(a.magnificPopup.defaults[b]=c.options),a.extend(this.proto,c.proto),this.modules.push(b)},defaults:{disableOn:0,key:null,midClick:!1,mainClass:"",preloader:!0,focus:"",closeOnContentClick:!1,closeOnBgClick:!0,closeBtnInside:!0,showCloseBtn:!0,enableEscapeKey:!0,modal:!1,alignTop:!1,removalDelay:0,prependTo:null,fixedContentPos:"auto",fixedBgPos:"auto",overflowY:"auto",closeMarkup:'<button title="%title%" type="button" class="mfp-close">×</button>',tClose:"Close (Esc)",tLoading:"Loading...",autoFocusLast:!0}},a.fn.magnificPopup=function(b){A();var c=a(this);if(typeof b=="string")if(b==="open"){var d,e=p?c.data("magnificPopup"):c[0].magnificPopup,f=parseInt(arguments[1],10)||0;e.items?d=e.items[f]:(d=c,e.delegate&&(d=d.find(e.delegate)),d=d.eq(f)),n._openClick({mfpEl:d},c,e)}else n.isOpen&&n[b].apply(n,Array.prototype.slice.call(arguments,1));else b=a.extend(!0,{},b),p?c.data("magnificPopup",b):c[0].magnificPopup=b,n.addGroup(c,b);return c};var C="inline",D,E,F,G=function(){F&&(E.after(F.addClass(D)).detach(),F=null)};a.magnificPopup.registerModule(C,{options:{hiddenClass:"hide",markup:"",tNotFound:"Content not found"},proto:{initInline:function(){n.types.push(C),w(b+"."+C,function(){G()})},getInline:function(b,c){G();if(b.src){var d=n.st.inline,e=a(b.src);if(e.length){var f=e[0].parentNode;f&&f.tagName&&(E||(D=d.hiddenClass,E=x(D),D="mfp-"+D),F=e.after(E).detach().removeClass(D)),n.updateStatus("ready")}else n.updateStatus("error",d.tNotFound),e=a("
");return b.inlineElement=e,e}return n.updateStatus("ready"),n._parseMarkup(c,{},b),c}}});var H,I=function(){return H===undefined&&(H=document.createElement("p").style.MozTransform!==undefined),H};a.magnificPopup.registerModule("zoom",{options:{enabled:!1,easing:"ease-in-out",duration:300,opener:function(a){return a.is("img")?a:a.find("img")}},proto:{initZoom:function(){var a=n.st.zoom,d=".zoom",e;if(!a.enabled||!n.supportsTransition)return;var f=a.duration,g=function(b){var c=b.clone().removeAttr("style").removeAttr("class").addClass("mfp-animated-image"),d="all "+a.duration/1e3+"s "+a.easing,e={position:"fixed",zIndex:9999,left:0,top:0,"-webkit-backface-visibility":"hidden"},f="transition";return e["-webkit-"+f]=e["-moz-"+f]=e["-o-"+f]=e[f]=d,c.css(e),c},h=function(){n.content.css("visibility","visible")},i,j;w("BuildControls"+d,function(){if(n._allowZoom()){clearTimeout(i),n.content.css("visibility","hidden"),e=n._getItemToZoom();if(!e){h();return}j=g(e),j.css(n._getOffset()),n.wrap.append(j),i=setTimeout(function(){j.css(n._getOffset(!0)),i=setTimeout(function(){h(),setTimeout(function(){j.remove(),e=j=null,y("ZoomAnimationEnded")},16)},f)},16)}}),w(c+d,function(){if(n._allowZoom()){clearTimeout(i),n.st.removalDelay=f;if(!e){e=n._getItemToZoom();if(!e)return;j=g(e)}j.css(n._getOffset(!0)),n.wrap.append(j),n.content.css("visibility","hidden"),setTimeout(function(){j.css(n._getOffset())},16)}}),w(b+d,function(){n._allowZoom()&&(h(),j&&j.remove(),e=null)})},_allowZoom:function(){return n.currItem.type==="image"},_getItemToZoom:function(){return n.currItem.hasSize?n.currItem.img:!1},_getOffset:function(b){var c;b?c=n.currItem.img:c=n.st.zoom.opener(n.currItem.el||n.currItem);var d=c.offset(),e=parseInt(c.css("padding-top"),10),f=parseInt(c.css("padding-bottom"),10);d.top-=a(window).scrollTop()-e;var g={width:c.width(),height:(p?c.innerHeight():c[0].offsetHeight)-f-e};return I()?g["-moz-transform"]=g.transform="translate("+d.left+"px,"+d.top+"px)":(g.left=d.left,g.top=d.top),g}}}),A()})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Magnific Popup CSS */

.mfp-bg {
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 1042;
    overflow: hidden;
    position: fixed;
    background: #0b0b0b;
    opacity: 0.8; }

.mfp-wrap {
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 1043;
    position: fixed;
    outline: none !important;
    -webkit-backface-visibility: hidden; }

.mfp-hide {
    display: none !important; }</code>```

<!doctype html>

Click

Popup

```

Point to the area, the blue div appears. Make a click. A pop-up window appears and the blue div disappears. Ok, that's what I need. But when you close the pop-up window, the blue div will reappear. How to fix it?

答:
use the default plugin css.  after that just active the plugin.  then do cuatomize what you need.
here are the repo  http://dimsemenov.com/plugins/magnific-popup/</p>

Body:
After closing the popup, the div should be hidden (and when the pop-up is open it really hides), but when the pop-up is closed, it becomes visible.

// Magnific Popup v1.1.0 by Dmitry Semenov
(function(a){typeof define=="function"&&define.amd?define(["jquery"],a):typeof exports=="object"?a(require("jquery")):a(window.jQuery||window.Zepto)})(function(a){var b="Close",c="BeforeClose",d="AfterClose",e="BeforeAppend",f="MarkupParse",g="Open",h="Change",i="mfp",j="."+i,k="mfp-ready",l="mfp-removing",m="mfp-prevent-close",n,o=function(){},p=!!window.jQuery,q,r=a(window),s,t,u,v,w=function(a,b){n.ev.on(i+a+j,b)},x=function(b,c,d,e){var f=document.createElement("div");return f.className="mfp-"+b,d&&(f.innerHTML=d),e?c&&c.appendChild(f):(f=a(f),c&&f.appendTo(c)),f},y=function(b,c){n.ev.triggerHandler(i+b,c),n.st.callbacks&&(b=b.charAt(0).toLowerCase()+b.slice(1),n.st.callbacks[b]&&n.st.callbacks[b].apply(n,a.isArray(c)?c:[c]))},z=function(b){if(b!==v||!n.currTemplate.closeBtn)n.currTemplate.closeBtn=a(n.st.closeMarkup.replace("%title%",n.st.tClose)),v=b;return n.currTemplate.closeBtn},A=function(){a.magnificPopup.instance||(n=new o,n.init(),a.magnificPopup.instance=n)},B=function(){var a=document.createElement("p").style,b=["ms","O","Moz","Webkit"];if(a.transition!==undefined)return!0;while(b.length)if(b.pop()+"Transition"in a)return!0;return!1};o.prototype={constructor:o,init:function(){var b=navigator.appVersion;n.isLowIE=n.isIE8=document.all&&!document.addEventListener,n.isAndroid=/android/gi.test(b),n.isIOS=/iphone|ipad|ipod/gi.test(b),n.supportsTransition=B(),n.probablyMobile=n.isAndroid||n.isIOS||/(Opera Mini)|Kindle|webOS|BlackBerry|(Opera Mobi)|(Windows Phone)|IEMobile/i.test(navigator.userAgent),s=a(document),n.popupsCache={}},open:function(b){var c;if(b.isObj===!1){n.items=b.items.toArray(),n.index=0;var d=b.items,e;for(c=0;c<d.length;c++){e=d[c],e.parsed&&(e=e.el[0]);if(e===b.el[0]){n.index=c;break}}}else n.items=a.isArray(b.items)?b.items:[b.items],n.index=b.index||0;if(n.isOpen){n.updateItemHTML();return}n.types=[],u="",b.mainEl&&b.mainEl.length?n.ev=b.mainEl.eq(0):n.ev=s,b.key?(n.popupsCache[b.key]||(n.popupsCache[b.key]={}),n.currTemplate=n.popupsCache[b.key]):n.currTemplate={},n.st=a.extend(!0,{},a.magnificPopup.defaults,b),n.fixedContentPos=n.st.fixedContentPos==="auto"?!n.probablyMobile:n.st.fixedContentPos,n.st.modal&&(n.st.closeOnContentClick=!1,n.st.closeOnBgClick=!1,n.st.showCloseBtn=!1,n.st.enableEscapeKey=!1),n.bgOverlay||(n.bgOverlay=x("bg").on("click"+j,function(){n.close()}),n.wrap=x("wrap").attr("tabindex",-1).on("click"+j,function(a){n._checkIfClose(a.target)&&n.close()}),n.container=x("container",n.wrap)),n.contentContainer=x("content"),n.st.preloader&&(n.preloader=x("preloader",n.container,n.st.tLoading));var h=a.magnificPopup.modules;for(c=0;c<h.length;c++){var i=h[c];i=i.charAt(0).toUpperCase()+i.slice(1),n["init"+i].call(n)}y("BeforeOpen"),n.st.showCloseBtn&&(n.st.closeBtnInside?(w(f,function(a,b,c,d){c.close_replaceWith=z(d.type)}),u+=" mfp-close-btn-in"):n.wrap.append(z())),n.st.alignTop&&(u+=" mfp-align-top"),n.fixedContentPos?n.wrap.css({overflow:n.st.overflowY,overflowX:"hidden",overflowY:n.st.overflowY}):n.wrap.css({top:r.scrollTop(),position:"absolute"}),(n.st.fixedBgPos===!1||n.st.fixedBgPos==="auto"&&!n.fixedContentPos)&&n.bgOverlay.css({height:s.height(),position:"absolute"}),n.st.enableEscapeKey&&s.on("keyup"+j,function(a){a.keyCode===27&&n.close()}),r.on("resize"+j,function(){n.updateSize()}),n.st.closeOnContentClick||(u+=" mfp-auto-cursor"),u&&n.wrap.addClass(u);var l=n.wH=r.height(),m={};if(n.fixedContentPos&&n._hasScrollBar(l)){var o=n._getScrollbarSize();o&&(m.marginRight=o)}n.fixedContentPos&&(n.isIE7?a("body, html").css("overflow","hidden"):m.overflow="hidden");var p=n.st.mainClass;return n.isIE7&&(p+=" mfp-ie7"),p&&n._addClassToMFP(p),n.updateItemHTML(),y("BuildControls"),a("html").css(m),n.bgOverlay.add(n.wrap).prependTo(n.st.prependTo||a(document.body)),n._lastFocusedEl=document.activeElement,setTimeout(function(){n.content?(n._addClassToMFP(k),n._setFocus()):n.bgOverlay.addClass(k),s.on("focusin"+j,n._onFocusIn)},16),n.isOpen=!0,n.updateSize(l),y(g),b},close:function(){if(!n.isOpen)return;y(c),n.isOpen=!1,n.st.removalDelay&&!n.isLowIE&&n.supportsTransition?(n._addClassToMFP(l),setTimeout(function(){n._close()},n.st.removalDelay)):n._close()},_close:function(){y(b);var c=l+" "+k+" ";n.bgOverlay.detach(),n.wrap.detach(),n.container.empty(),n.st.mainClass&&(c+=n.st.mainClass+" "),n._removeClassFromMFP(c);if(n.fixedContentPos){var e={marginRight:""};n.isIE7?a("body, html").css("overflow",""):e.overflow="",a("html").css(e)}s.off("keyup"+j+" focusin"+j),n.ev.off(j),n.wrap.attr("class","mfp-wrap").removeAttr("style"),n.bgOverlay.attr("class","mfp-bg"),n.container.attr("class","mfp-container"),n.st.showCloseBtn&&(!n.st.closeBtnInside||n.currTemplate[n.currItem.type]===!0)&&n.currTemplate.closeBtn&&n.currTemplate.closeBtn.detach(),n.st.autoFocusLast&&n._lastFocusedEl&&a(n._lastFocusedEl).focus(),n.currItem=null,n.content=null,n.currTemplate=null,n.prevHeight=0,y(d)},updateSize:function(a){if(n.isIOS){var b=document.documentElement.clientWidth/window.innerWidth,c=window.innerHeight*b;n.wrap.css("height",c),n.wH=c}else n.wH=a||r.height();n.fixedContentPos||n.wrap.css("height",n.wH),y("Resize")},updateItemHTML:function(){var b=n.items[n.index];n.contentContainer.detach(),n.content&&n.content.detach(),b.parsed||(b=n.parseEl(n.index));var c=b.type;y("BeforeChange",[n.currItem?n.currItem.type:"",c]),n.currItem=b;if(!n.currTemplate[c]){var d=n.st[c]?n.st[c].markup:!1;y("FirstMarkupParse",d),d?n.currTemplate[c]=a(d):n.currTemplate[c]=!0}t&&t!==b.type&&n.container.removeClass("mfp-"+t+"-holder");var e=n["get"+c.charAt(0).toUpperCase()+c.slice(1)](b,n.currTemplate[c]);n.appendContent(e,c),b.preloaded=!0,y(h,b),t=b.type,n.container.prepend(n.contentContainer),y("AfterChange")},appendContent:function(a,b){n.content=a,a?n.st.showCloseBtn&&n.st.closeBtnInside&&n.currTemplate[b]===!0?n.content.find(".mfp-close").length||n.content.append(z()):n.content=a:n.content="",y(e),n.container.addClass("mfp-"+b+"-holder"),n.contentContainer.append(n.content)},parseEl:function(b){var c=n.items[b],d;c.tagName?c={el:a(c)}:(d=c.type,c={data:c,src:c.src});if(c.el){var e=n.types;for(var f=0;f<e.length;f++)if(c.el.hasClass("mfp-"+e[f])){d=e[f];break}c.src=c.el.attr("data-mfp-src"),c.src||(c.src=c.el.attr("href"))}return c.type=d||n.st.type||"inline",c.index=b,c.parsed=!0,n.items[b]=c,y("ElementParse",c),n.items[b]},addGroup:function(a,b){var c=function(c){c.mfpEl=this,n._openClick(c,a,b)};b||(b={});var d="click.magnificPopup";b.mainEl=a,b.items?(b.isObj=!0,a.off(d).on(d,c)):(b.isObj=!1,b.delegate?a.off(d).on(d,b.delegate,c):(b.items=a,a.off(d).on(d,c)))},_openClick:function(b,c,d){var e=d.midClick!==undefined?d.midClick:a.magnificPopup.defaults.midClick;if(!e&&(b.which===2||b.ctrlKey||b.metaKey||b.altKey||b.shiftKey))return;var f=d.disableOn!==undefined?d.disableOn:a.magnificPopup.defaults.disableOn;if(f)if(a.isFunction(f)){if(!f.call(n))return!0}else if(r.width()<f)return!0;b.type&&(b.preventDefault(),n.isOpen&&b.stopPropagation()),d.el=a(b.mfpEl),d.delegate&&(d.items=c.find(d.delegate)),n.open(d)},updateStatus:function(a,b){if(n.preloader){q!==a&&n.container.removeClass("mfp-s-"+q),!b&&a==="loading"&&(b=n.st.tLoading);var c={status:a,text:b};y("UpdateStatus",c),a=c.status,b=c.text,n.preloader.html(b),n.preloader.find("a").on("click",function(a){a.stopImmediatePropagation()}),n.container.addClass("mfp-s-"+a),q=a}},_checkIfClose:function(b){if(a(b).hasClass(m))return;var c=n.st.closeOnContentClick,d=n.st.closeOnBgClick;if(c&&d)return!0;if(!n.content||a(b).hasClass("mfp-close")||n.preloader&&b===n.preloader[0])return!0;if(b!==n.content[0]&&!a.contains(n.content[0],b)){if(d&&a.contains(document,b))return!0}else if(c)return!0;return!1},_addClassToMFP:function(a){n.bgOverlay.addClass(a),n.wrap.addClass(a)},_removeClassFromMFP:function(a){this.bgOverlay.removeClass(a),n.wrap.removeClass(a)},_hasScrollBar:function(a){return(n.isIE7?s.height():document.body.scrollHeight)>(a||r.height())},_setFocus:function(){(n.st.focus?n.content.find(n.st.focus).eq(0):n.wrap).focus()},_onFocusIn:function(b){if(b.target!==n.wrap[0]&&!a.contains(n.wrap[0],b.target))return n._setFocus(),!1},_parseMarkup:function(b,c,d){var e;d.data&&(c=a.extend(d.data,c)),y(f,[b,c,d]),a.each(c,function(c,d){if(d===undefined||d===!1)return!0;e=c.split("_");if(e.length>1){var f=b.find(j+"-"+e[0]);if(f.length>0){var g=e[1];g==="replaceWith"?f[0]!==d[0]&&f.replaceWith(d):g==="img"?f.is("img")?f.attr("src",d):f.replaceWith(a("").attr("src",d).attr("class",f.attr("class"))):f.attr(e[1],d)}}else b.find(j+"-"+c).html(d)})},_getScrollbarSize:function(){if(n.scrollbarSize===undefined){var a=document.createElement("div");a.style.cssText="width: 99px; height: 99px; overflow: scroll; position: absolute; top: -9999px;",document.body.appendChild(a),n.scrollbarSize=a.offsetWidth-a.clientWidth,document.body.removeChild(a)}return n.scrollbarSize}},a.magnificPopup={instance:null,proto:o.prototype,modules:[],open:function(b,c){return A(),b?b=a.extend(!0,{},b):b={},b.isObj=!0,b.index=c||0,this.instance.open(b)},close:function(){return a.magnificPopup.instance&&a.magnificPopup.instance.close()},registerModule:function(b,c){c.options&&(a.magnificPopup.defaults[b]=c.options),a.extend(this.proto,c.proto),this.modules.push(b)},defaults:{disableOn:0,key:null,midClick:!1,mainClass:"",preloader:!0,focus:"",closeOnContentClick:!1,closeOnBgClick:!0,closeBtnInside:!0,showCloseBtn:!0,enableEscapeKey:!0,modal:!1,alignTop:!1,removalDelay:0,prependTo:null,fixedContentPos:"auto",fixedBgPos:"auto",overflowY:"auto",closeMarkup:'<button title="%title%" type="button" class="mfp-close">×</button>',tClose:"Close (Esc)",tLoading:"Loading...",autoFocusLast:!0}},a.fn.magnificPopup=function(b){A();var c=a(this);if(typeof b=="string")if(b==="open"){var d,e=p?c.data("magnificPopup"):c[0].magnificPopup,f=parseInt(arguments[1],10)||0;e.items?d=e.items[f]:(d=c,e.delegate&&(d=d.find(e.delegate)),d=d.eq(f)),n._openClick({mfpEl:d},c,e)}else n.isOpen&&n[b].apply(n,Array.prototype.slice.call(arguments,1));else b=a.extend(!0,{},b),p?c.data("magnificPopup",b):c[0].magnificPopup=b,n.addGroup(c,b);return c};var C="inline",D,E,F,G=function(){F&&(E.after(F.addClass(D)).detach(),F=null)};a.magnificPopup.registerModule(C,{options:{hiddenClass:"hide",markup:"",tNotFound:"Content not found"},proto:{initInline:function(){n.types.push(C),w(b+"."+C,function(){G()})},getInline:function(b,c){G();if(b.src){var d=n.st.inline,e=a(b.src);if(e.length){var f=e[0].parentNode;f&&f.tagName&&(E||(D=d.hiddenClass,E=x(D),D="mfp-"+D),F=e.after(E).detach().removeClass(D)),n.updateStatus("ready")}else n.updateStatus("error",d.tNotFound),e=a("
");return b.inlineElement=e,e}return n.updateStatus("ready"),n._parseMarkup(c,{},b),c}}});var H,I=function(){return H===undefined&&(H=document.createElement("p").style.MozTransform!==undefined),H};a.magnificPopup.registerModule("zoom",{options:{enabled:!1,easing:"ease-in-out",duration:300,opener:function(a){return a.is("img")?a:a.find("img")}},proto:{initZoom:function(){var a=n.st.zoom,d=".zoom",e;if(!a.enabled||!n.supportsTransition)return;var f=a.duration,g=function(b){var c=b.clone().removeAttr("style").removeAttr("class").addClass("mfp-animated-image"),d="all "+a.duration/1e3+"s "+a.easing,e={position:"fixed",zIndex:9999,left:0,top:0,"-webkit-backface-visibility":"hidden"},f="transition";return e["-webkit-"+f]=e["-moz-"+f]=e["-o-"+f]=e[f]=d,c.css(e),c},h=function(){n.content.css("visibility","visible")},i,j;w("BuildControls"+d,function(){if(n._allowZoom()){clearTimeout(i),n.content.css("visibility","hidden"),e=n._getItemToZoom();if(!e){h();return}j=g(e),j.css(n._getOffset()),n.wrap.append(j),i=setTimeout(function(){j.css(n._getOffset(!0)),i=setTimeout(function(){h(),setTimeout(function(){j.remove(),e=j=null,y("ZoomAnimationEnded")},16)},f)},16)}}),w(c+d,function(){if(n._allowZoom()){clearTimeout(i),n.st.removalDelay=f;if(!e){e=n._getItemToZoom();if(!e)return;j=g(e)}j.css(n._getOffset(!0)),n.wrap.append(j),n.content.css("visibility","hidden"),setTimeout(function(){j.css(n._getOffset())},16)}}),w(b+d,function(){n._allowZoom()&&(h(),j&&j.remove(),e=null)})},_allowZoom:function(){return n.currItem.type==="image"},_getItemToZoom:function(){return n.currItem.hasSize?n.currItem.img:!1},_getOffset:function(b){var c;b?c=n.currItem.img:c=n.st.zoom.opener(n.currItem.el||n.currItem);var d=c.offset(),e=parseInt(c.css("padding-top"),10),f=parseInt(c.css("padding-bottom"),10);d.top-=a(window).scrollTop()-e;var g={width:c.width(),height:(p?c.innerHeight():c[0].offsetHeight)-f-e};return I()?g["-moz-transform"]=g.transform="translate("+d.left+"px,"+d.top+"px)":(g.left=d.left,g.top=d.top),g}}}),A()})

/* Magnific Popup CSS */

.mfp-bg {
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 1042;
    overflow: hidden;
    position: fixed;
    background: #0b0b0b;
    opacity: 0.8; }

.mfp-wrap {
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 1043;
    position: fixed;
    outline: none !important;
    -webkit-backface-visibility: hidden; }

.mfp-hide {
    display: none !important; }

<!doctype html>

Click

Popup

Point to the area, the blue div appears. Make a click. A pop-up window appears and the blue div disappears. Ok, that's what I need. But when you close the pop-up window, the blue div will reappear. How to fix it?


问:
Can I override a PHP trait property in a consumer class in order to use Doctrine2 annotations?
I'm using traits to implement some Taggable behaviour in a Symfony app, using Doctrine2 for persistence, and annotations to configure that.

The main annoyance I have is that in the trait, my IDE has no idea of the type of $this->tags, and throws up a bunch of warnings. I'm being pretty OCD about getting my code documented here, so that it's really easy for other developers to pick up.

```<code>trait TaggableMethods {
    /** @var \Doctrine\Common\Collections\Collection */
    protected $tags; // <-- Can't seem to define here…
    public function addTag(Tag $tag) {
        $this->tags->add($tag);
    }
    public function removeTag(Tag $tag) {
        $this->tags->removeElement($tag);
    }
    public function getTags() {
        return $this->tags;
    }
}

class TaggableThingA {
    use TaggableMethods;
    /**
     * @var \Doctrine\Common\Collections\Collection
     * @ORM\ManyToMany(targetEntity="Tag")
     * @ORM\JoinTable(name="ThingA__Tag")
     */
    protected $tags; // <--… because PHP complains about this
}

class TaggableThingB {
    use TaggableMethods;
    /**
     * @var \Doctrine\Common\Collections\Collection
     * @ORM\ManyToMany(targetEntity="Tag")
     * @ORM\JoinTable(name="ThingB__Tag")
     */
    protected $tags;
}
</code>```

My problem, so far as I can tell, is that I can't define the $tags property in the trait, as I need to override the annotations.

I can avoid defining $tags at all in TaggableMethods, but to me, this breaks encapsulation, or at least makes the code a little harder to read.

I can configure persistence using Yaml or XML, but all the rest of my entities use annotations.

So I'm looking for a way to avoid the runtime notice that gets generated, which Symfony turns into a ContextErrorException, killing my script during development.

This is probably related to "can we use traits to map manyToOne relationship with doctrine2?" and "Traits - property conflict with parent class"

Also, the behaviour for inherited methods mentioned in  "PHP 5.4: why can classes override trait methods with a different signature?" sounds very close to what I want for properties - can anyone explain why the difference between properties and methods exists?

答: Late, but it might help someone. You can use association or attributes override (annotations @AssociationOverrides, @AttributeOverrides) as described in section 6.4. Overrides.

Body:
I'm using traits to implement some Taggable behaviour in a Symfony app, using Doctrine2 for persistence, and annotations to configure that.

The main annoyance I have is that in the trait, my IDE has no idea of the type of $this->tags, and throws up a bunch of warnings. I'm being pretty OCD about getting my code documented here, so that it's really easy for other developers to pick up.

trait TaggableMethods {
    /** @var \Doctrine\Common\Collections\Collection */
    protected $tags; // <-- Can't seem to define here…
    public function addTag(Tag $tag) {
        $this->tags->add($tag);
    }
    public function removeTag(Tag $tag) {
        $this->tags->removeElement($tag);
    }
    public function getTags() {
        return $this->tags;
    }
}

class TaggableThingA {
    use TaggableMethods;
    /**
     * @var \Doctrine\Common\Collections\Collection
     * @ORM\ManyToMany(targetEntity="Tag")
     * @ORM\JoinTable(name="ThingA__Tag")
     */
    protected $tags; // <--… because PHP complains about this
}

class TaggableThingB {
    use TaggableMethods;
    /**
     * @var \Doctrine\Common\Collections\Collection
     * @ORM\ManyToMany(targetEntity="Tag")
     * @ORM\JoinTable(name="ThingB__Tag")
     */
    protected $tags;
}

My problem, so far as I can tell, is that I can't define the $tags property in the trait, as I need to override the annotations.

I can avoid defining $tags at all in TaggableMethods, but to me, this breaks encapsulation, or at least makes the code a little harder to read.

I can configure persistence using Yaml or XML, but all the rest of my entities use annotations.

So I'm looking for a way to avoid the runtime notice that gets generated, which Symfony turns into a ContextErrorException, killing my script during development.

This is probably related to "can we use traits to map manyToOne relationship with doctrine2?" and "Traits - property conflict with parent class"

Also, the behaviour for inherited methods mentioned in  "PHP 5.4: why can classes override trait methods with a different signature?" sounds very close to what I want for properties - can anyone explain why the difference between properties and methods exists?


问:
Cannot get Xamarin Xaml Intellisense working in VS 2015
I've been trying to get intellisense working for quite some time now, and am unable to see anything outside of

```<code>!
![CDATA[
?
</code>```

Visual Studio 2015 Update 2

Resharper is installed but disabled

Referencing the latest pre-releases of Xamarin Forms (2.3.0.38-pre2)

Xamarin for Visual Studio (4.2.21)

Portable project referencing the proper 2.3.0.38-pre2 targets file from NuGet

Enable XAML Language for Xamarin.Forms

What else am I missing? I feel like it shouldn't be this difficult.

答:
I resolved this issue by doing a simple workaround and here is the
  solution.

Right-click the XAML file in the Solution Explorer and select

Solution 1: "Open With... > Source Code (Text) Editor".

and in another time this also worked for me:

Solution 2: "Open With... > Source Code (Text) Editor with Encoding"

Actually, I found that for me it even worked by simply choose:
Solution 2: "Open With... > Automatic Editor Selector (XML)" and then reopening VS.

I also found that the problem began after editing .xaml file outside of VS, by right-clicking the file and choose "Edit".

Body:
I've been trying to get intellisense working for quite some time now, and am unable to see anything outside of

!
![CDATA[
?

Visual Studio 2015 Update 2

Resharper is installed but disabled

Referencing the latest pre-releases of Xamarin Forms (2.3.0.38-pre2)

Xamarin for Visual Studio (4.2.21)

Portable project referencing the proper 2.3.0.38-pre2 targets file from NuGet

Enable XAML Language for Xamarin.Forms

What else am I missing? I feel like it shouldn't be this difficult.


问:
Combine date and time string into single date with javascript
I have a datepicker returning a date string, and a timepicker returning just a time string.

How should I combine those into a single javascript Date?

I thought I found a solution in Date.js. The examples shows an at( )-method, but I can't find it in the library...

答:
David's example with slight modifications:</p>

```<code>function CombineDateAndTime(date, time) {
    var timeString = time.getHours() + ':' + time.getMinutes() + ':00';
    var ampm = time.getHours() >= 12 ? 'PM' : 'AM';
    var year = date.getFullYear();
    var month = date.getMonth() + 1; // Jan is 0, dec is 11
    var day = date.getDate();
    var dateString = '' + year + '-' + month + '-' + day;
    var datec = dateString + 'T' + timeString;
    var combined = new Date(datec);

    return combined;
};
</code>```

Body:
David's example with slight modifications:

function CombineDateAndTime(date, time) {
    var timeString = time.getHours() + ':' + time.getMinutes() + ':00';
    var ampm = time.getHours() >= 12 ? 'PM' : 'AM';
    var year = date.getFullYear();
    var month = date.getMonth() + 1; // Jan is 0, dec is 11
    var day = date.getDate();
    var dateString = '' + year + '-' + month + '-' + day;
    var datec = dateString + 'T' + timeString;
    var combined = new Date(datec);

    return combined;
};


问:
PHP looking for best way to use 'goto' to skip PHP script
I am looking for the best way to 'skip' a PHP script to pass directly to my HTML code. Here's an example:

```<code><?php
include 'ws/main.php';
include 'ws/database/connection.php';

$error = false;
$routes = getCurrentParameters();

if (!isset($routes[0]) && !$error)
{
    $error = traduction("No promotion entered in the URL");
    goto end;
}
else if (!isset($routes[1]) && !$error)
{
    $error = traduction("No page entered in the URL");
    goto end;
}

if (!$error)
{
    $result = $connection->query("SELECT * FROM promotion WHERE name = '$routes[0]'");
    $promo = $result->fetch_row();

    if (empty($promo) && !$error)
    {
        $error = traduction("The promotion '". $routes[0] ."' do not exist");
        goto end;
    }
    else if (!file_exists("page/" . $routes[1] . ".php"))
    {
        $error = traduction("The page '". $routes[1] ."' do not exist");
        goto end;
    }

    $result = $connection->query("SELECT * FROM traduction WHERE promotion_id = $promo[0]");
    $traduction = $result->fetch_all();
}

end:
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Start CSS import -->
    <link rel='stylesheet' href='<?php echo BASE_PATH ?>assets/css/bootstrap.css' />
    <link rel='stylesheet' href='<?php echo BASE_PATH ?>assets/css/font-awesome.css' />
    <link rel='stylesheet' href='<?php echo BASE_PATH ?>assets/css/animate.css' />
    <link rel='stylesheet' href='<?php echo BASE_PATH ?>assets/css/main.css' />
    <!-- End CSS import -->
</head>
<body>
    <?php if (!$error) // If the app do not catch any error
    {
        include "page/$routes[1].php";
    }
    else // If the app already catch an error
    {
        // Include the error.php page
        include "page/error.php";
    } ?>

    <!-- Start JS import -->
    <script type='application/javascript' src='<?php echo BASE_PATH ?>assets/js/jquery.js'></script>
    <script type='application/javascript' src='<?php echo BASE_PATH ?>libs/js/tether/dist/js/tether.js'></script>
    <script type='application/javascript' src='<?php echo BASE_PATH ?>assets/js/bootstrap.js'></script>
    <script type='application/javascript' src='<?php echo BASE_PATH ?>assets/js/moment.js'></script>
    <script type='application/javascript' src='<?php echo BASE_PATH ?>assets/js/bootbox.js'></script>
    <script type='application/javascript' src='<?php echo BASE_PATH ?>assets/js/sweetalert.js'></script>
    <script type='application/javascript' src='<?php echo BASE_PATH ?>assets/js/main.js'></script>
    <!-- End JS import -->

    <script>
        $(".img").css("background", "url(<?php echo $promo[2]; ?>) no-repeat center center")
    </script>
</body>
</html>
</code>```

So, if you have read all my code, which is not complicated at all, I am just looking for the best way to quit my PHP script, in the top, to go directly to my HTML code when I have an issue in my database or the information just do not match. Currently I use the 'goto' method with a tag 'end:' in the end of the script. I know that 'goto' method isn't optimal at all, so I'm looking for a better way to do it because I'm pretty sure there's already an existing method.

答:
If you put the code you potentially want to run into a function, or as a method in a class, then it's a simple matter to run that code - or choose to return out of it early, without doing anything.</p>

```<code><?php
function doThings($error, $routes) {
{
    $traduction = array();
    if (!isset($routes[0]) && !$error) {
        return $traduction;  // leave the function without doing anything
    }

    // the rest of the checks and actions, to get the database results

    return $traduction;
}

$traduction = doThings($error, $routes);

// loop over the (maybe empty $traduction variable) to output
?>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am looking for the best way to 'skip' a PHP script to pass directly to my HTML code. Here's an example:

<?php
include 'ws/main.php';
include 'ws/database/connection.php';

$error = false;
$routes = getCurrentParameters();

if (!isset($routes[0]) && !$error)
{
    $error = traduction("No promotion entered in the URL");
    goto end;
}
else if (!isset($routes[1]) && !$error)
{
    $error = traduction("No page entered in the URL");
    goto end;
}

if (!$error)
{
    $result = $connection->query("SELECT * FROM promotion WHERE name = '$routes[0]'");
    $promo = $result->fetch_row();

    if (empty($promo) && !$error)
    {
        $error = traduction("The promotion '". $routes[0] ."' do not exist");
        goto end;
    }
    else if (!file_exists("page/" . $routes[1] . ".php"))
    {
        $error = traduction("The page '". $routes[1] ."' do not exist");
        goto end;
    }

    $result = $connection->query("SELECT * FROM traduction WHERE promotion_id = $promo[0]");
    $traduction = $result->fetch_all();
}

end:
?>

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel='stylesheet' href='<?php echo BASE_PATH ?>assets/css/bootstrap.css' />
    <link rel='stylesheet' href='<?php echo BASE_PATH ?>assets/css/font-awesome.css' />
    <link rel='stylesheet' href='<?php echo BASE_PATH ?>assets/css/animate.css' />
    <link rel='stylesheet' href='<?php echo BASE_PATH ?>assets/css/main.css' />

    <?php if (!$error) // If the app do not catch any error
    {
        include "page/$routes[1].php";
    }
    else // If the app already catch an error
    {
        // Include the error.php page
        include "page/error.php";
    } ?>

So, if you have read all my code, which is not complicated at all, I am just looking for the best way to quit my PHP script, in the top, to go directly to my HTML code when I have an issue in my database or the information just do not match. Currently I use the 'goto' method with a tag 'end:' in the end of the script. I know that 'goto' method isn't optimal at all, so I'm looking for a better way to do it because I'm pretty sure there's already an existing method.

Body:
If you put the code you potentially want to run into a function, or as a method in a class, then it's a simple matter to run that code - or choose to return out of it early, without doing anything.

<?php
function doThings($error, $routes) {
{
    $traduction = array();
    if (!isset($routes[0]) && !$error) {
        return $traduction;  // leave the function without doing anything
    }

    // the rest of the checks and actions, to get the database results

    return $traduction;
}

$traduction = doThings($error, $routes);

// loop over the (maybe empty $traduction variable) to output
?>


问:
XSLT equivalent for JSON
Is there an XSLT equivalent for JSON? Something to allow me to do transformations on JSON like XSLT does to XML.</p>

答:
It may be possible to use XSLT with JSON.
Verson 3 of XPath(3.1) XSLT(3.0) and XQuery(3.1) supports JSON in some way.
This seems to be available in the commercial version of Saxon, and might at some point be included in the HE version.
https://www.saxonica.com/html/documentation/functions/fn/parse-json.html

-

What I would expect from an alternative solution:

I would want to be able input JSON to fetch a matching set of data, and output JSON or TEXT.

Access arbitrary properties and evaluate the values

Support for conditional logic

I would want the transformation scripts to be external from the tool, text based, and preferably a commonly used language.

Potential alternative?

I wonder if SQL could be a suitable alternative.
https://learn.microsoft.com/en-us/sql/relational-databases/json/json-data-sql-server

It would be nice if the alternative tool could handle JSON and XML
https://learn.microsoft.com/en-us/sql/relational-databases/xml/openxml-sql-server

I have not yet tried to convert the XSLT scripts I use to SQL, or fully evaluated this option yet, but I hope to look into it more soon.  Just some thoughts so far.

Title: XSLT equivalent for JSON