问:
How to group nearby contours in OpenCV Python? - Zebra Crossing detection
I want to detect the zebra crossing lines. I have tried to find out the co-ordinates of zebra crossing line in the image using contour but it gives the output for the distinct white boxes (only white lines in the zebra crossing). But I need the co-ordinates of the entire zebra crossing.

Please let me know the way to group the contours or suggest me another method to detect zebra crossing.

Input image

Output image obtained

Expected output

```<code>import cv2
import numpy as np
image = cv2.imread('d.jpg',-1)
paper = cv2.resize(image,(500,500))
ret, thresh_gray = cv2.threshold(cv2.cvtColor(paper, cv2.COLOR_BGR2GRAY),
                        200, 255, cv2.THRESH_BINARY)
image, contours, hier = cv2.findContours(thresh_gray, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
for c in contours:
    rect = cv2.minAreaRect(c)
    box = cv2.boxPoints(rect)
    # convert all coordinates floating point values to int
    box = np.int0(box)
    cv2.drawContours(paper, [box], 0, (0, 255, 0),1)
cv2.imshow('paper', paper)
cv2.imwrite('paper.jpg',paper)
cv2.waitKey(0)
</code>```

答:
You can closing morphological operation for closing the gaps.

I cat suggest the following stages:

Find contours in thresh_gray.

Erase contours with very small area (noise).

Erase contours with low aspect ratio (assume zebra line must be long and narrow.

Use morphologyEx to perform closing morphological operation - the closing merges close components.

Find contours again in the image after erasing and closing.

At the last stage, ignore small contours.

Here is a working code sample:

```<code>import cv2
import numpy as np

image = cv2.imread('d.jpg', -1)
paper = cv2.resize(image, (500,500))
ret, thresh_gray = cv2.threshold(cv2.cvtColor(paper, cv2.COLOR_BGR2GRAY), 200, 255, cv2.THRESH_BINARY)
image, contours, hier = cv2.findContours(thresh_gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

# Erase small contours, and contours which small aspect ratio (close to a square)
for c in contours:
    area = cv2.contourArea(c)

    # Fill very small contours with zero (erase small contours).
    if area < 10:
        cv2.fillPoly(thresh_gray, pts=[c], color=0)
        continue

    # https://stackoverflow.com/questions/52247821/find-width-and-height-of-rotatedrect
    rect = cv2.minAreaRect(c)
    (x, y), (w, h), angle = rect
    aspect_ratio = max(w, h) / min(w, h)

    # Assume zebra line must be long and narrow (long part must be at lease 1.5 times the narrow part).
    if (aspect_ratio < 1.5):
        cv2.fillPoly(thresh_gray, pts=[c], color=0)
        continue

# Use "close" morphological operation to close the gaps between contours
# https://stackoverflow.com/questions/18339988/implementing-imcloseim-se-in-opencv
thresh_gray = cv2.morphologyEx(thresh_gray, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (51,51)));

# Find contours in thresh_gray after closing the gaps
image, contours, hier = cv2.findContours(thresh_gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

for c in contours:
    area = cv2.contourArea(c)

    # Small contours are ignored.
    if area < 500:
        cv2.fillPoly(thresh_gray, pts=[c], color=0)
        continue

    rect = cv2.minAreaRect(c)
    box = cv2.boxPoints(rect)
    # convert all coordinates floating point values to int
    box = np.int0(box)
    cv2.drawContours(paper, [box], 0, (0, 255, 0),1)

cv2.imshow('paper', paper)
cv2.imwrite('paper.jpg', paper)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

thresh_gray before erasing small and squared contours:

thresh_gray after erasing small and squared contours:

thresh_gray after close operation:

Final result:

Remark:

I have some doubts about the benefit of using morphological operation for closing the gaps.

It might be better using a smart logic based on geometry instead.

Body:
I want to detect the zebra crossing lines. I have tried to find out the co-ordinates of zebra crossing line in the image using contour but it gives the output for the distinct white boxes (only white lines in the zebra crossing). But I need the co-ordinates of the entire zebra crossing.

Please let me know the way to group the contours or suggest me another method to detect zebra crossing.

Input image

Output image obtained

Expected output

import cv2
import numpy as np
image = cv2.imread('d.jpg',-1)
paper = cv2.resize(image,(500,500))
ret, thresh_gray = cv2.threshold(cv2.cvtColor(paper, cv2.COLOR_BGR2GRAY),
                        200, 255, cv2.THRESH_BINARY)
image, contours, hier = cv2.findContours(thresh_gray, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
for c in contours:
    rect = cv2.minAreaRect(c)
    box = cv2.boxPoints(rect)
    # convert all coordinates floating point values to int
    box = np.int0(box)
    cv2.drawContours(paper, [box], 0, (0, 255, 0),1)
cv2.imshow('paper', paper)
cv2.imwrite('paper.jpg',paper)
cv2.waitKey(0)

Body:
You can closing morphological operation for closing the gaps.

I cat suggest the following stages:

Find contours in thresh_gray.

Erase contours with very small area (noise).

Erase contours with low aspect ratio (assume zebra line must be long and narrow.

Use morphologyEx to perform closing morphological operation - the closing merges close components.

Find contours again in the image after erasing and closing.

At the last stage, ignore small contours.

Here is a working code sample:

import cv2
import numpy as np

image = cv2.imread('d.jpg', -1)
paper = cv2.resize(image, (500,500))
ret, thresh_gray = cv2.threshold(cv2.cvtColor(paper, cv2.COLOR_BGR2GRAY), 200, 255, cv2.THRESH_BINARY)
image, contours, hier = cv2.findContours(thresh_gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

# Erase small contours, and contours which small aspect ratio (close to a square)
for c in contours:
    area = cv2.contourArea(c)

    # Fill very small contours with zero (erase small contours).
    if area < 10:
        cv2.fillPoly(thresh_gray, pts=[c], color=0)
        continue

    # https://stackoverflow.com/questions/52247821/find-width-and-height-of-rotatedrect
    rect = cv2.minAreaRect(c)
    (x, y), (w, h), angle = rect
    aspect_ratio = max(w, h) / min(w, h)

    # Assume zebra line must be long and narrow (long part must be at lease 1.5 times the narrow part).
    if (aspect_ratio < 1.5):
        cv2.fillPoly(thresh_gray, pts=[c], color=0)
        continue

# Use "close" morphological operation to close the gaps between contours
# https://stackoverflow.com/questions/18339988/implementing-imcloseim-se-in-opencv
thresh_gray = cv2.morphologyEx(thresh_gray, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (51,51)));

# Find contours in thresh_gray after closing the gaps
image, contours, hier = cv2.findContours(thresh_gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

for c in contours:
    area = cv2.contourArea(c)

    # Small contours are ignored.
    if area < 500:
        cv2.fillPoly(thresh_gray, pts=[c], color=0)
        continue

    rect = cv2.minAreaRect(c)
    box = cv2.boxPoints(rect)
    # convert all coordinates floating point values to int
    box = np.int0(box)
    cv2.drawContours(paper, [box], 0, (0, 255, 0),1)

cv2.imshow('paper', paper)
cv2.imwrite('paper.jpg', paper)
cv2.waitKey(0)
cv2.destroyAllWindows()

thresh_gray before erasing small and squared contours:

thresh_gray after erasing small and squared contours:

thresh_gray after close operation:

Final result:

Remark:

I have some doubts about the benefit of using morphological operation for closing the gaps.

It might be better using a smart logic based on geometry instead.


来源: stackexchange

问:
App Forces Close . SMS Broadcast Receiver
I'm new to Android Studio. when i run this on a single activity it runs okay but when i have a multiple activities it forces to close.

The error

```
<em> 02-12 00:18:42.578 5092-5092/com.example.driveassist E/AndroidRuntime: FATAL EXCEPTION: main
        Process: com.example.driveassist, PID: 5092
        java.lang.RuntimeException: Error receiving broadcast Intent { act=android.provider.Telephony.SMS_RECEIVED flg=0x8000010 (has extras) } in com.example.driveassist.firstPage$1@30b6fb57
            at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:876)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
         Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
            at com.example.driveassist.firstPage$1.onReceive(firstPage.java:77)
            at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:866)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
</em>```

my activity codes are

```<code>import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.speech.tts.TextToSpeech;
import android.telephony.SmsMessage;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.ToggleButton;

public class firstPage extends AppCompatActivity {
    private Button button,btbutton,acbutton;
    private final int CHECK_CODE = 0x1;
    private final int LONG_DURATION = 2000;
    private final int SHORT_DURATION = 1200;

    private Speaker speaker;

    private ToggleButton toggle;
    private CompoundButton.OnCheckedChangeListener toggleListener;

    private TextView smsText;
    private TextView smsSender;

    private BroadcastReceiver smsReceiver;
    private String address;

    private void checkTTS(){
        Intent check = new Intent();
        check.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
        startActivityForResult(check, CHECK_CODE);
    }
    @SuppressLint("MissingSuperCall")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == CHECK_CODE){
            if(resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS){
                speaker = new Speaker(this);
            }else {
                Intent install = new Intent();
                install.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                startActivity(install);
            }
        }
    }
    private void initializeSMSReceiver(){
        smsReceiver = new BroadcastReceiver(){
            @Override
            public void onReceive(Context context, Intent intent) {

                Bundle bundle = intent.getExtras();
                if(bundle!=null){
                    Object[] pdus = (Object[])bundle.get("pdus");
                    for(int i=0;i<pdus.length;i++){
                        byte[] pdu = (byte[])pdus[i];
                        SmsMessage message = SmsMessage.createFromPdu((byte[]) pdus[0]);
                        String text = message.getDisplayMessageBody();
                        address = message.getOriginatingAddress();
                        String sender = getContactName(message.getOriginatingAddress());
                        speaker.pause(LONG_DURATION);
                        speaker.speak("You have a new message from" + sender + "!");
                        speaker.pause(SHORT_DURATION);
                        speaker.speak(text);
                        smsSender.setText("Message from " + sender);
                        smsText.setText(text);

                    }
                }

            }
        };
    }
    private String getContactName(String phone){
        Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone));
        String projection[] = new String[]{ContactsContract.Data.DISPLAY_NAME};
        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
        if(cursor.moveToFirst()){
            return cursor.getString(0);
        }else {
            return address;
        }
    }

    private void registerSMSReceiver() {
        IntentFilter intentFilter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
        registerReceiver(smsReceiver, intentFilter);
    }

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

        toggle = (ToggleButton)findViewById(R.id.speechToggle);
        //smsText = (TextView)findViewById(R.id.sms_text);
        smsSender = (TextView)findViewById(R.id.senderView);

        toggleListener = new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton view, boolean isChecked) {
                if(isChecked){
                    speaker.allow(true);
                    speaker.speak(getString(R.string.start_speaking));
                }else{
                    speaker.speak(getString(R.string.stop_speaking));
                    speaker.allow(false);
                }
            }
        };
        toggle.setOnCheckedChangeListener(toggleListener);

        checkTTS();
        initializeSMSReceiver();
        registerSMSReceiver();

    button =(Button) findViewById(R.id.settingsButton);
            button.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View V) {
                    openActivity3();

                }
            });
            btbutton =(Button) findViewById(R.id.btsettingsButton);
            btbutton.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View V) {
                    btActivity();

                }
            });
            acbutton = (Button) findViewById(R.id.acceptButton);
            acbutton.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View V) {
                    readActivity();

                }
            });
        }
        public void openActivity3() {
            Intent intent = new Intent(this,editMessage.class);
            startActivity(intent);
        }
        public void btActivity() {
            Intent intent1 = new Intent(this,btConnectivity.class);
            startActivity(intent1);
        }
        public void readActivity() {
            Intent intent2 = new Intent(this,readMessage.class);
            startActivity(intent2);
        }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(smsReceiver);
        speaker.destroy();
    }

    }
</code>```

答:
Following error message means that dereference to the TextView type reference which was null occurred to try call setText method. It caused error message when you receive Broadcast intent.

```<code>     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at com.example.driveassist.firstPage$1.onReceive(firstPage.java:77)
</code>```

And there's one concerned point in your onReceive implementation.
onReceive
 -> smsText.setText(text); <- smsText hasn't allocated. because of the line comment

onCreate
 -> //smsText = (TextView)findViewById(R.id.sms_text);

ContentLicense: CC BY-SA 4.0

Body:
I'm new to Android Studio. when i run this on a single activity it runs okay but when i have a multiple activities it forces to close.

The error

 02-12 00:18:42.578 5092-5092/com.example.driveassist E/AndroidRuntime: FATAL EXCEPTION: main
        Process: com.example.driveassist, PID: 5092
        java.lang.RuntimeException: Error receiving broadcast Intent { act=android.provider.Telephony.SMS_RECEIVED flg=0x8000010 (has extras) } in com.example.driveassist.firstPage$1@30b6fb57
            at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:876)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
         Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
            at com.example.driveassist.firstPage$1.onReceive(firstPage.java:77)
            at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:866)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

my activity codes are

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.speech.tts.TextToSpeech;
import android.telephony.SmsMessage;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.ToggleButton;

public class firstPage extends AppCompatActivity {
    private Button button,btbutton,acbutton;
    private final int CHECK_CODE = 0x1;
    private final int LONG_DURATION = 2000;
    private final int SHORT_DURATION = 1200;

    private Speaker speaker;

    private ToggleButton toggle;
    private CompoundButton.OnCheckedChangeListener toggleListener;

    private TextView smsText;
    private TextView smsSender;

    private BroadcastReceiver smsReceiver;
    private String address;

    private void checkTTS(){
        Intent check = new Intent();
        check.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
        startActivityForResult(check, CHECK_CODE);
    }
    @SuppressLint("MissingSuperCall")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == CHECK_CODE){
            if(resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS){
                speaker = new Speaker(this);
            }else {
                Intent install = new Intent();
                install.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                startActivity(install);
            }
        }
    }
    private void initializeSMSReceiver(){
        smsReceiver = new BroadcastReceiver(){
            @Override
            public void onReceive(Context context, Intent intent) {

                Bundle bundle = intent.getExtras();
                if(bundle!=null){
                    Object[] pdus = (Object[])bundle.get("pdus");
                    for(int i=0;i<pdus.length;i++){
                        byte[] pdu = (byte[])pdus[i];
                        SmsMessage message = SmsMessage.createFromPdu((byte[]) pdus[0]);
                        String text = message.getDisplayMessageBody();
                        address = message.getOriginatingAddress();
                        String sender = getContactName(message.getOriginatingAddress());
                        speaker.pause(LONG_DURATION);
                        speaker.speak("You have a new message from" + sender + "!");
                        speaker.pause(SHORT_DURATION);
                        speaker.speak(text);
                        smsSender.setText("Message from " + sender);
                        smsText.setText(text);

                    }
                }

            }
        };
    }
    private String getContactName(String phone){
        Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone));
        String projection[] = new String[]{ContactsContract.Data.DISPLAY_NAME};
        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
        if(cursor.moveToFirst()){
            return cursor.getString(0);
        }else {
            return address;
        }
    }

    private void registerSMSReceiver() {
        IntentFilter intentFilter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
        registerReceiver(smsReceiver, intentFilter);
    }

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

        toggle = (ToggleButton)findViewById(R.id.speechToggle);
        //smsText = (TextView)findViewById(R.id.sms_text);
        smsSender = (TextView)findViewById(R.id.senderView);

        toggleListener = new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton view, boolean isChecked) {
                if(isChecked){
                    speaker.allow(true);
                    speaker.speak(getString(R.string.start_speaking));
                }else{
                    speaker.speak(getString(R.string.stop_speaking));
                    speaker.allow(false);
                }
            }
        };
        toggle.setOnCheckedChangeListener(toggleListener);

        checkTTS();
        initializeSMSReceiver();
        registerSMSReceiver();

    button =(Button) findViewById(R.id.settingsButton);
            button.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View V) {
                    openActivity3();

                }
            });
            btbutton =(Button) findViewById(R.id.btsettingsButton);
            btbutton.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View V) {
                    btActivity();

                }
            });
            acbutton = (Button) findViewById(R.id.acceptButton);
            acbutton.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View V) {
                    readActivity();

                }
            });
        }
        public void openActivity3() {
            Intent intent = new Intent(this,editMessage.class);
            startActivity(intent);
        }
        public void btActivity() {
            Intent intent1 = new Intent(this,btConnectivity.class);
            startActivity(intent1);
        }
        public void readActivity() {
            Intent intent2 = new Intent(this,readMessage.class);
            startActivity(intent2);
        }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(smsReceiver);
        speaker.destroy();
    }

    }

Body:
Following error message means that dereference to the TextView type reference which was null occurred to try call setText method. It caused error message when you receive Broadcast intent.

     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at com.example.driveassist.firstPage$1.onReceive(firstPage.java:77)

And there's one concerned point in your onReceive implementation.
onReceive
 -> smsText.setText(text); <- smsText hasn't allocated. because of the line comment

onCreate
 -> //smsText = (TextView)findViewById(R.id.sms_text);


问:
Why include when you can require in PHP?
What is the point of attempting to include or include_once a library in PHP if you often have to use require or require_once instead (as they're usually critically important)?

答:
The documentation at http://tr.php.net/manual/en/function.include.php starts with:

The include() statement includes and
  evaluates the specified file.

The documentation below also applies
  to require().

And the documentation at http://tr.php.net/manual/en/function.require.php says:

require() is identical to include()
  except upon failure it will also
  produce a fatal E_COMPILE_ERROR level
  error. In other words, it will halt
  the script whereas include() only
  emits a warning (E_WARNING) which
  allows the script to continue.

See the include() documentation for
  how this works.

I think that's enough :)

ContentLicense: CC BY-SA 3.0


问:
window.scrollTo() in react components?
Where do I have to put the window.scrollTo(0,0) call in a react component?

I tried to put it directly into render and also tried componentDidUpdate (to wait till everything is rendered), but somehow the scrollbars always stay at the same position.

-- Edit --

The problem was CSS height/overflow of the window and body.

See: https://stackoverflow.com/a/18573599/1016383

答: Another scenario could be that the application is not set up to have the window handle its scrolling. It could be a 'widget' where the window is static and an inner element handles the scrolling. A good way to test this is to enter window.scrollTo(0,0) right there in your console. If your window doesn't pop to the top there, you'll need to seek another solution. Likely you'll need to get the element that is doing the actual scrolling and handle it with Element.scrollTo(0,0)

Title: window.scrollTo() in react components?


问:
Overflowing :: Using flexbox
I know there has been a lot of questions and answers about how to control the overflow of a parent container using flexbox. I couldn't find a solution to this problem so here is another question about it.

What I want
The part where the problem is, is commented in the HTML.

What I get

Here is the code. You might have to copy and paste the code in...:(

html {
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Helvetica, Arial, sans-serif;
}

html,
body {
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  max-height: 100%;
  -webkit-box-flex: 1;
  -ms-flex: 1;
  flex: 1;
  overflow: hidden;
}

body {
  -webkit-box-flex: 1;
  -ms-flex: 1 0 auto;
  flex: 1 0 auto;
}

#voolvern_main .voolvern_grid {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-flex: 1;
  -ms-flex: 1;
  flex: 1;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -ms-flex-direction: column;
  flex-direction: column;
}

img {
  height: auto;
  max-width: 100%;
  vertical-align: middle;
}

.voolvern_gflex {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
}

a {
  text-decoration: none;
  height: -webkit-fit-content;
  height: -moz-fit-content;
  height: fit-content;
}

.voolvern_grid .voolvern_gridflex {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
}

#voolvern_main {
  -webkit-box-flex: 1;
  -ms-flex: 1;
  flex: 1;
}

@media (min-width: 40rem) {
  #voolvern_pcard_section.voolvern_stack_two .voolvern_item {
    width: 50%;
  }
}

@media (min-width: 56rem) {
  #voolvern_pcard_section.voolvern_stack_two .voolvern_item {
    width: 32.99999%;
  }
}

#voolvern_main>#voolvern_mainaside.voolvern_aside {
  -webkit-box-flex: 1;
  -ms-flex: 1 1 1rem;
  flex: 1 1 1rem;
}

#voolvern_main>#voolvern_rightaside.voolvern_aside {
  width: 32%;
}

#voolvern_main>.voolvern_aside>.voolvern_uid {
  width: 100%;
}

.voolvern_stackhandler>.voolvern_stackpad {
  padding-right: 1.2rem;
  padding-left: 1.2rem;
}

.voolvern_group.voolvern_nuid {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: justify;
  -ms-flex-pack: justify;
  justify-content: space-between;
}

#voolvern_toolbar>.voolvern_group {
  padding-top: 1.7rem;
  padding-bottom: 1.7rem;
}

#voolvern_toolbar>.voolvern_group.voolvern_nuid>.voolvern_nitem .voolvern_span {
  padding-top: .8rem;
  padding-bottom: .8rem;
  padding-right: 1rem;
  padding-left: 1rem;
  border-radius: 10%;
}

#voolvern_toolbar>.voolvern_group.voolvern_nuid>.voolvern_nitem .voolvern_span:hover {
  background: lightgray;
}

.voolvern_stackpad>.voolvern_header>.voolvern_group {
  height: 3.5rem;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <script src="https://kit.fontawesome.com/db35900820.js">
  </script>
  <link rel="stylesheet" href="https://kit-free.fontawesome.com/releases/latest/css/free.min.css" media="all">
  <link rel="stylesheet" href="https://kit-free.fontawesome.com/releases/latest/css/free-v4-font-face.min.css" media="all">
  <link rel="stylesheet" href="https://kit-free.fontawesome.com/releases/latest/css/free-v4-shims.min.css" media="all">
  <link rel="stylesheet" href="https://kit-free.fontawesome.com/releases/latest/css/free.min.css" media="all">
  <title>vvnfinal</title>
  <link rel="icon" href="https://cdn.dribbble.com/users/1097/screenshots/168079/newv2.png">
</head>

<body class="voolvern_grid">
  <main id="voolvern_main" class="voolvern_gridflex" style="flex: 1rem">
    <aside id="voolvern_mainaside" class="voolvern_aside voolvern_gridflex">
      <section class="voolvern_uid voolvern_stackhandler" style=" flex-direction: column; display: flex">
        <!-- begin:: header -->
        <div class="voolvern_stackpad">
          <section id="voolvern_mainasideheader" class="voolvern_header">
            <div class="voolvern_group voolvern_nuid">
              <span>left</span>
              <span>left</span>
            </div>
          </section>
        </div>
        <!-- end:: header -->
        <div style="flex: 1; border-bottom: .01rem solid lightgray">
          <section style="overflow-y: scroll;">
            <!-- here is the div that when givin a height of 40rem+ it cuzes the <section> to push down all the contents after it,
I want the <section> to stay put and is scrollable when that happens but I can't seem to figure that out.

 -->
            <div style="height: 40rem">content</div>
          </section>
        </div>
        <!-- begin:: toolbar -->
        <div class="voolvern_stackpad">
          <section id="voolvern_toolbar">
            <span class="voolvern_group voolvern_nuid">
              <!-- begin:: toolbar items -->
              <div class="voolvern_nitem">

                  <span class="voolvern_span">
                    <i class="far fa-lightbulb" aria-hidden="true">
                    </i>
                  </span>

        </div>
        <div class="voolvern_nitem">

            <span class="voolvern_span">
                    <i class="fab fa-hubspot" aria-hidden="true">
                    </i>
                  </span>

        </div>
        <div class="voolvern_nitem">

            <span class="voolvern_span">
                    <i class="fas fa-shopping-bag" aria-hidden="true">
                    </i>
                  </span>

        </div>
        <div class="voolvern_nitem">

            <span class="voolvern_span">
                    <i class="fas fa-globe-americas" aria-hidden="true">
                    </i>
                  </span>

        </div>
        <div class="voolvern_nitem">

            <span class="voolvern_span">
                    <i class="fas fa-hands-helping" aria-hidden="true">
                    </i>
                  </span>

        </div>
        <div class="voolvern_nitem">

            <span class="voolvern_span">
                    <i class="fab fa-ioxhost" aria-hidden="true">
                    </i>
                  </span>

        </div>
        <!-- end:: toolbar itemns-->
        </span>
        </section>
        </div>
        <!-- end:: toolbar -->
      </section>
    </aside>
    <aside id="voolvern_rightaside" class="voolvern_aside voolvern_nuid">
      <section class="voolvern_uid voolvern_stackhandler" style="overflow-y: scroll">
        <!-- begin:: header -->
        <div class="voolvern_stackpad">
          <section id="voolvern_rightasideheader" class="voolvern_header">
            <div class="voolvern_group"> content header </div>
          </section>
        </div>
        <!-- end:: header -->
      </section>
    </aside>
  </main>
</body>

</html></code>```

This whole site will be built using flexbox
Meaning I use:

```<code>display: flex
flex: 1
flex-direction: column
</code>```

To get the full height from elements.

I have spent 2 months trying to figure this problem out.
I would greatly appreciate it if we can solve this problem swiftly.
Thank you!

答:
To make the overflow work correctly you need to position the element you want to do the overflow absolutely. I had the same issue and searched a long time to find this solution. Looks like this is a common behavior when using flex layout.

Here is the relevant change:

```<code><div style="flex: 1; border-bottom: .01rem solid lightgray; position: relative;">
    <section style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; overflow-y: scroll;">
       <div style="height: 40rem">content</div>
    </section>
</div>
</code>```

And the changes=d snippet where you can see it work.

html {
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Helvetica, Arial, sans-serif;
}

html,
body {
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  max-height: 100%;
  -webkit-box-flex: 1;
  -ms-flex: 1;
  flex: 1;
  overflow: hidden;
}

body {
  -webkit-box-flex: 1;
  -ms-flex: 1 0 auto;
  flex: 1 0 auto;
}

#voolvern_main .voolvern_grid {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-flex: 1;
  -ms-flex: 1;
  flex: 1;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -ms-flex-direction: column;
  flex-direction: column;
}

img {
  height: auto;
  max-width: 100%;
  vertical-align: middle;
}

.voolvern_gflex {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
}

a {
  text-decoration: none;
  height: -webkit-fit-content;
  height: -moz-fit-content;
  height: fit-content;
}

.voolvern_grid .voolvern_gridflex {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
}

#voolvern_main {
  -webkit-box-flex: 1;
  -ms-flex: 1;
  flex: 1;
}

@media (min-width: 40rem) {
  #voolvern_pcard_section.voolvern_stack_two .voolvern_item {
    width: 50%;
  }
}

@media (min-width: 56rem) {
  #voolvern_pcard_section.voolvern_stack_two .voolvern_item {
    width: 32.99999%;
  }
}

#voolvern_main>#voolvern_mainaside.voolvern_aside {
  -webkit-box-flex: 1;
  -ms-flex: 1 1 1rem;
  flex: 1 1 1rem;
}

#voolvern_main>#voolvern_rightaside.voolvern_aside {
  width: 32%;
}

#voolvern_main>.voolvern_aside>.voolvern_uid {
  width: 100%;
}

.voolvern_stackhandler>.voolvern_stackpad {
  padding-right: 1.2rem;
  padding-left: 1.2rem;
}

.voolvern_group.voolvern_nuid {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: justify;
  -ms-flex-pack: justify;
  justify-content: space-between;
}

#voolvern_toolbar>.voolvern_group {
  padding-top: 1.7rem;
  padding-bottom: 1.7rem;
}

#voolvern_toolbar>.voolvern_group.voolvern_nuid>.voolvern_nitem .voolvern_span {
  padding-top: .8rem;
  padding-bottom: .8rem;
  padding-right: 1rem;
  padding-left: 1rem;
  border-radius: 10%;
}

#voolvern_toolbar>.voolvern_group.voolvern_nuid>.voolvern_nitem .voolvern_span:hover {
  background: lightgray;
}

.voolvern_stackpad>.voolvern_header>.voolvern_group {
  height: 3.5rem;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <script src="https://kit.fontawesome.com/db35900820.js">
  </script>
  <link rel="stylesheet" href="https://kit-free.fontawesome.com/releases/latest/css/free.min.css" media="all">
  <link rel="stylesheet" href="https://kit-free.fontawesome.com/releases/latest/css/free-v4-font-face.min.css" media="all">
  <link rel="stylesheet" href="https://kit-free.fontawesome.com/releases/latest/css/free-v4-shims.min.css" media="all">
  <link rel="stylesheet" href="https://kit-free.fontawesome.com/releases/latest/css/free.min.css" media="all">
  <title>vvnfinal</title>
  <link rel="icon" href="https://cdn.dribbble.com/users/1097/screenshots/168079/newv2.png">
</head>

<body class="voolvern_grid">
  <main id="voolvern_main" class="voolvern_gridflex" style="flex: 1rem">
    <aside id="voolvern_mainaside" class="voolvern_aside voolvern_gridflex">
      <section class="voolvern_uid voolvern_stackhandler" style=" flex-direction: column; display: flex">
        <!-- begin:: header -->
        <div class="voolvern_stackpad">
          <section id="voolvern_mainasideheader" class="voolvern_header">
            <div class="voolvern_group voolvern_nuid">
              <span>left</span>
              <span>left</span>
            </div>
          </section>
        </div>
        <!-- end:: header -->
        <div style="flex: 1; border-bottom: .01rem solid lightgray; position: relative;">
          <section style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; overflow-y: scroll;">
            <!-- here is the div that when givin a height of 40rem+ it cuzes the <section> to push down all the contents after it,
I want the <section> to stay put and is scrollable when that happens but I can't seem to figure that out.

 -->
            <div style="height: 40rem">content</div>
          </section>
        </div>
        <!-- begin:: toolbar -->
        <div class="voolvern_stackpad">
          <section id="voolvern_toolbar">
            <span class="voolvern_group voolvern_nuid">
              <!-- begin:: toolbar items -->
              <div class="voolvern_nitem">

                  <span class="voolvern_span">
                    <i class="far fa-lightbulb" aria-hidden="true">
                    </i>
                  </span>

        </div>
        <div class="voolvern_nitem">

            <span class="voolvern_span">
                    <i class="fab fa-hubspot" aria-hidden="true">
                    </i>
                  </span>

        </div>
        <div class="voolvern_nitem">

            <span class="voolvern_span">
                    <i class="fas fa-shopping-bag" aria-hidden="true">
                    </i>
                  </span>

        </div>
        <div class="voolvern_nitem">

            <span class="voolvern_span">
                    <i class="fas fa-globe-americas" aria-hidden="true">
                    </i>
                  </span>

        </div>
        <div class="voolvern_nitem">

            <span class="voolvern_span">
                    <i class="fas fa-hands-helping" aria-hidden="true">
                    </i>
                  </span>

        </div>
        <div class="voolvern_nitem">

            <span class="voolvern_span">
                    <i class="fab fa-ioxhost" aria-hidden="true">
                    </i>
                  </span>

        </div>
        <!-- end:: toolbar itemns-->
        </span>
        </section>
        </div>
        <!-- end:: toolbar -->
      </section>
    </aside>
    <aside id="voolvern_rightaside" class="voolvern_aside voolvern_nuid">
      <section class="voolvern_uid voolvern_stackhandler" style="overflow-y: scroll">
        <!-- begin:: header -->
        <div class="voolvern_stackpad">
          <section id="voolvern_rightasideheader" class="voolvern_header">
            <div class="voolvern_group"> content header </div>
          </section>
        </div>
        <!-- end:: header -->
      </section>
    </aside>
  </main>
</body>

</html></code>```

Title: Overflowing :: Using flexbox

Body:
I know there has been a lot of questions and answers about how to control the overflow of a parent container using flexbox. I couldn't find a solution to this problem so here is another question about it.

What I want
The part where the problem is, is commented in the HTML.

What I get

Here is the code. You might have to copy and paste the code in...:(

html {
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Helvetica, Arial, sans-serif;
}

html,
body {
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  max-height: 100%;
  -webkit-box-flex: 1;
  -ms-flex: 1;
  flex: 1;
  overflow: hidden;
}

body {
  -webkit-box-flex: 1;
  -ms-flex: 1 0 auto;
  flex: 1 0 auto;
}

#voolvern_main .voolvern_grid {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-flex: 1;
  -ms-flex: 1;
  flex: 1;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -ms-flex-direction: column;
  flex-direction: column;
}

img {
  height: auto;
  max-width: 100%;
  vertical-align: middle;
}

.voolvern_gflex {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
}

a {
  text-decoration: none;
  height: -webkit-fit-content;
  height: -moz-fit-content;
  height: fit-content;
}

.voolvern_grid .voolvern_gridflex {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
}

#voolvern_main {
  -webkit-box-flex: 1;
  -ms-flex: 1;
  flex: 1;
}

@media (min-width: 40rem) {
  #voolvern_pcard_section.voolvern_stack_two .voolvern_item {
    width: 50%;
  }
}

@media (min-width: 56rem) {
  #voolvern_pcard_section.voolvern_stack_two .voolvern_item {
    width: 32.99999%;
  }
}

#voolvern_main>#voolvern_mainaside.voolvern_aside {
  -webkit-box-flex: 1;
  -ms-flex: 1 1 1rem;
  flex: 1 1 1rem;
}

#voolvern_main>#voolvern_rightaside.voolvern_aside {
  width: 32%;
}

#voolvern_main>.voolvern_aside>.voolvern_uid {
  width: 100%;
}

.voolvern_stackhandler>.voolvern_stackpad {
  padding-right: 1.2rem;
  padding-left: 1.2rem;
}

.voolvern_group.voolvern_nuid {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: justify;
  -ms-flex-pack: justify;
  justify-content: space-between;
}

#voolvern_toolbar>.voolvern_group {
  padding-top: 1.7rem;
  padding-bottom: 1.7rem;
}

#voolvern_toolbar>.voolvern_group.voolvern_nuid>.voolvern_nitem .voolvern_span {
  padding-top: .8rem;
  padding-bottom: .8rem;
  padding-right: 1rem;
  padding-left: 1rem;
  border-radius: 10%;
}

#voolvern_toolbar>.voolvern_group.voolvern_nuid>.voolvern_nitem .voolvern_span:hover {
  background: lightgray;
}

.voolvern_stackpad>.voolvern_header>.voolvern_group {
  height: 3.5rem;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">

  <link rel="stylesheet" href="https://kit-free.fontawesome.com/releases/latest/css/free.min.css" media="all">
  <link rel="stylesheet" href="https://kit-free.fontawesome.com/releases/latest/css/free-v4-font-face.min.css" media="all">
  <link rel="stylesheet" href="https://kit-free.fontawesome.com/releases/latest/css/free-v4-shims.min.css" media="all">
  <link rel="stylesheet" href="https://kit-free.fontawesome.com/releases/latest/css/free.min.css" media="all">
  <title>vvnfinal</title>
  <link rel="icon" href="https://cdn.dribbble.com/users/1097/screenshots/168079/newv2.png">

              left
              left

content

 content header

This whole site will be built using flexbox
Meaning I use:

display: flex
flex: 1
flex-direction: column

To get the full height from elements.

I have spent 2 months trying to figure this problem out.
I would greatly appreciate it if we can solve this problem swiftly.
Thank you!

Body:
To make the overflow work correctly you need to position the element you want to do the overflow absolutely. I had the same issue and searched a long time to find this solution. Looks like this is a common behavior when using flex layout.

Here is the relevant change:

<div style="flex: 1; border-bottom: .01rem solid lightgray; position: relative;">
    <section style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; overflow-y: scroll;">
       <div style="height: 40rem">content</div>
    </section>
</div>

And the changes=d snippet where you can see it work.

html {
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Helvetica, Arial, sans-serif;
}

html,
body {
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  max-height: 100%;
  -webkit-box-flex: 1;
  -ms-flex: 1;
  flex: 1;
  overflow: hidden;
}

body {
  -webkit-box-flex: 1;
  -ms-flex: 1 0 auto;
  flex: 1 0 auto;
}

#voolvern_main .voolvern_grid {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-flex: 1;
  -ms-flex: 1;
  flex: 1;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -ms-flex-direction: column;
  flex-direction: column;
}

img {
  height: auto;
  max-width: 100%;
  vertical-align: middle;
}

.voolvern_gflex {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
}

a {
  text-decoration: none;
  height: -webkit-fit-content;
  height: -moz-fit-content;
  height: fit-content;
}

.voolvern_grid .voolvern_gridflex {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
}

#voolvern_main {
  -webkit-box-flex: 1;
  -ms-flex: 1;
  flex: 1;
}

@media (min-width: 40rem) {
  #voolvern_pcard_section.voolvern_stack_two .voolvern_item {
    width: 50%;
  }
}

@media (min-width: 56rem) {
  #voolvern_pcard_section.voolvern_stack_two .voolvern_item {
    width: 32.99999%;
  }
}

#voolvern_main>#voolvern_mainaside.voolvern_aside {
  -webkit-box-flex: 1;
  -ms-flex: 1 1 1rem;
  flex: 1 1 1rem;
}

#voolvern_main>#voolvern_rightaside.voolvern_aside {
  width: 32%;
}

#voolvern_main>.voolvern_aside>.voolvern_uid {
  width: 100%;
}

.voolvern_stackhandler>.voolvern_stackpad {
  padding-right: 1.2rem;
  padding-left: 1.2rem;
}

.voolvern_group.voolvern_nuid {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: justify;
  -ms-flex-pack: justify;
  justify-content: space-between;
}

#voolvern_toolbar>.voolvern_group {
  padding-top: 1.7rem;
  padding-bottom: 1.7rem;
}

#voolvern_toolbar>.voolvern_group.voolvern_nuid>.voolvern_nitem .voolvern_span {
  padding-top: .8rem;
  padding-bottom: .8rem;
  padding-right: 1rem;
  padding-left: 1rem;
  border-radius: 10%;
}

#voolvern_toolbar>.voolvern_group.voolvern_nuid>.voolvern_nitem .voolvern_span:hover {
  background: lightgray;
}

.voolvern_stackpad>.voolvern_header>.voolvern_group {
  height: 3.5rem;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
}

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <script src="https://kit.fontawesome.com/db35900820.js">
  </script>
  <link rel="stylesheet" href="https://kit-free.fontawesome.com/releases/latest/css/free.min.css" media="all">
  <link rel="stylesheet" href="https://kit-free.fontawesome.com/releases/latest/css/free-v4-font-face.min.css" media="all">
  <link rel="stylesheet" href="https://kit-free.fontawesome.com/releases/latest/css/free-v4-shims.min.css" media="all">
  <link rel="stylesheet" href="https://kit-free.fontawesome.com/releases/latest/css/free.min.css" media="all">
  <title>vvnfinal</title>
  <link rel="icon" href="https://cdn.dribbble.com/users/1097/screenshots/168079/newv2.png">
</head>

<body class="voolvern_grid">
  <main id="voolvern_main" class="voolvern_gridflex" style="flex: 1rem">
    <aside id="voolvern_mainaside" class="voolvern_aside voolvern_gridflex">
      <section class="voolvern_uid voolvern_stackhandler" style=" flex-direction: column; display: flex">
        <!-- begin:: header -->
        <div class="voolvern_stackpad">
          <section id="voolvern_mainasideheader" class="voolvern_header">
            <div class="voolvern_group voolvern_nuid">
              <span>left</span>
              <span>left</span>
            </div>
          </section>
        </div>
        <!-- end:: header -->
        <div style="flex: 1; border-bottom: .01rem solid lightgray; position: relative;">
          <section style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; overflow-y: scroll;">
            <!-- here is the div that when givin a height of 40rem+ it cuzes the <section> to push down all the contents after it,
I want the <section> to stay put and is scrollable when that happens but I can't seem to figure that out.

 -->
            <div style="height: 40rem">content</div>
          </section>
        </div>
        <!-- begin:: toolbar -->
        <div class="voolvern_stackpad">
          <section id="voolvern_toolbar">
            <span class="voolvern_group voolvern_nuid">
              <!-- begin:: toolbar items -->
              <div class="voolvern_nitem">
                <a href="/Projects">
                  <span class="voolvern_span">
                    <i class="far fa-lightbulb" aria-hidden="true">
                    </i>
                  </span>
            </a>
        </div>
        <div class="voolvern_nitem">
          <a href="/Subsidiaries" class="">
            <span class="voolvern_span">
                    <i class="fab fa-hubspot" aria-hidden="true">
                    </i>
                  </span>
          </a>
        </div>
        <div class="voolvern_nitem">
          <a href="/Discover" class="">
            <span class="voolvern_span">
                    <i class="fas fa-shopping-bag" aria-hidden="true">
                    </i>
                  </span>
          </a>
        </div>
        <div class="voolvern_nitem">
          <a href="/Discover" class="">
            <span class="voolvern_span">
                    <i class="fas fa-globe-americas" aria-hidden="true">
                    </i>
                  </span>
          </a>
        </div>
        <div class="voolvern_nitem">
          <a href="/Support" class="">
            <span class="voolvern_span">
                    <i class="fas fa-hands-helping" aria-hidden="true">
                    </i>
                  </span>
          </a>
        </div>
        <div class="voolvern_nitem">
          <a href="/Support" class="">
            <span class="voolvern_span">
                    <i class="fab fa-ioxhost" aria-hidden="true">
                    </i>
                  </span>
          </a>
        </div>
        <!-- end:: toolbar itemns-->
        </span>
        </section>
        </div>
        <!-- end:: toolbar -->
      </section>
    </aside>
    <aside id="voolvern_rightaside" class="voolvern_aside voolvern_nuid">
      <section class="voolvern_uid voolvern_stackhandler" style="overflow-y: scroll">
        <!-- begin:: header -->
        <div class="voolvern_stackpad">
          <section id="voolvern_rightasideheader" class="voolvern_header">
            <div class="voolvern_group"> content header </div>
          </section>
        </div>
        <!-- end:: header -->
      </section>
    </aside>
  </main>
</body>

</html>


问:
Python regular expressions word bounaries
Hello I have a text string like this below and I am trying to use regular expressions to extract the Total Sales quantity which can be found right after the new line after the Total Sales\n43 for example 43 would the total sales. I am using the following command but I want to drop the Total Sales and the \n and just keep the quantity.  I am wondering how I might go about this or will I need to do additional processing.  Thanks

```<code>'\ufeffSacramento Association of REALTORS®\nSingle Family Home Sales by ZIP CODE\nJanuary 2020\nZip
 Code\nCurrent Month\nLast Month\nLast Year\nYear-to-Date\nTotal Sales\n43\nREO
 Sales\n0\n45\n40\n43\nMedian Sales Price\n$417,000\n$0\n$410,000\n$400,000\n$417,000\nAverage
 Price/Square Foot\n$268\nShort Sales\n0\n$253\n$239\nN/A\nAverage Sq Ft of
 Property\n1,769\n$0\n1,746\n1,843\nN/A\nTotal Listing Inventory
 *\n69\nConventional\n43\n65\n90\nN/A\nTotal Listing Median Price
 ∞\n$612,475\nSales\n$417,000\n$574,900\n$547,475\nN/A\nTotal Sales\n29\nREO
 **strong text**Sales\n0\n37\n16\n29\nMedian Sales Price\n$369,000
</code>```

I am using a command like this:

```<code> total_sales = re.findall(r'\bTotal Sales\n\d{2}',data)
</code>```

which returns:

```<code> ['Total Sales\n43',
 'Total Sales\n29',
 'Total Sales\n29',
 'Total Sales\n32',
 'Total Sales\n30',
 'Total Sales\n52',
</code>```

答: Use positive look behind:(?<=Total Sales\n)\d{2}. This way it checks if the Total Sales\n string is preceding the pattern \d{2}. And only capture that.

Body:
Hello I have a text string like this below and I am trying to use regular expressions to extract the Total Sales quantity which can be found right after the new line after the Total Sales\n43 for example 43 would the total sales. I am using the following command but I want to drop the Total Sales and the \n and just keep the quantity.  I am wondering how I might go about this or will I need to do additional processing.  Thanks

'\ufeffSacramento Association of REALTORS®\nSingle Family Home Sales by ZIP CODE\nJanuary 2020\nZip
 Code\nCurrent Month\nLast Month\nLast Year\nYear-to-Date\nTotal Sales\n43\nREO
 Sales\n0\n45\n40\n43\nMedian Sales Price\n$417,000\n$0\n$410,000\n$400,000\n$417,000\nAverage
 Price/Square Foot\n$268\nShort Sales\n0\n$253\n$239\nN/A\nAverage Sq Ft of
 Property\n1,769\n$0\n1,746\n1,843\nN/A\nTotal Listing Inventory
 *\n69\nConventional\n43\n65\n90\nN/A\nTotal Listing Median Price
 ∞\n$612,475\nSales\n$417,000\n$574,900\n$547,475\nN/A\nTotal Sales\n29\nREO
 **strong text**Sales\n0\n37\n16\n29\nMedian Sales Price\n$369,000

I am using a command like this:

 total_sales = re.findall(r'\bTotal Sales\n\d{2}',data)

which returns:

 ['Total Sales\n43',
 'Total Sales\n29',
 'Total Sales\n29',
 'Total Sales\n32',
 'Total Sales\n30',
 'Total Sales\n52',


问:
Select all non-null column names per row in spark
Suppose I have a dataframe that looks like this:

```<code>+-----+-----+-----+-----+
|  A  |  B  |  C  |  D  |
+-----+-----+-----+-----+
|  Y  |null |  Y  |null |
|null |  N  |  N  |null |
|  N  |  Y  |null |  N  |
+-----+-----+-----+-----+
</code>```

I want to add a new column that is a concatenation of the names of all non-null columns for each row.

So, for the example above, it would add a new column

```<code>+--------+
|non-null|
+--------+
| A, C   |
| B, C   |
| A, B, D|
+--------+
</code>```

Is there any easy way to do this? I've tried looking for an anti-coalesce, something that would, if not null, use the supplied name. For example, if there was an anti-coalesce:

```<code>df.withColumn("non-null", antiCoalesce("A", "A,") + antiCoalesce("B", "B,") + antiCoalesce("C", "C,") + antiCoalesce("D", "D"))
</code>```

Alas, there is no such function, but it demonstrates what I am looking for.

答:
In SQL, you can express this using concat_ws():

```<code>select concat_ws(',',
                 (case when A is not null then 'A' end),
                 (case when B is not null then 'B' end),
                 (case when C is not null then 'C' end),
                 (case when D is not null then 'D' end)
                )
</code>```

Body:
Suppose I have a dataframe that looks like this:

+-----+-----+-----+-----+
|  A  |  B  |  C  |  D  |
+-----+-----+-----+-----+
|  Y  |null |  Y  |null |
|null |  N  |  N  |null |
|  N  |  Y  |null |  N  |
+-----+-----+-----+-----+

I want to add a new column that is a concatenation of the names of all non-null columns for each row.

So, for the example above, it would add a new column

+--------+
|non-null|
+--------+
| A, C   |
| B, C   |
| A, B, D|
+--------+

Is there any easy way to do this? I've tried looking for an anti-coalesce, something that would, if not null, use the supplied name. For example, if there was an anti-coalesce:

df.withColumn("non-null", antiCoalesce("A", "A,") + antiCoalesce("B", "B,") + antiCoalesce("C", "C,") + antiCoalesce("D", "D"))

Alas, there is no such function, but it demonstrates what I am looking for.

Body:
In SQL, you can express this using concat_ws():

select concat_ws(',',
                 (case when A is not null then 'A' end),
                 (case when B is not null then 'B' end),
                 (case when C is not null then 'C' end),
                 (case when D is not null then 'D' end)
                )


问:
pure function, why there is no optimisation?
I tried recent versions of gcc (9.2.1) and clang (9.0.1) for such code:

```<code>//pure.cpp
int square (int x) __attribute__ ((pure));

int square (int x)
{
        return  x * x;
}

//test.cpp
#include <stdio.h>

int square (int x) __attribute__ ((pure));

int main(int argc, char *argv[])
{
        const int same = argc;
        printf("result: %d\n", square(same));
        printf("result2: %d\n", square(same));
}
</code>```

and compile it like this:

```<code>g++ -ggdb -Ofast -c test.cpp
g++ -ggdb -Ofast -c pure.cpp
g++ -ggdb -Ofast -o test test.o pure.o
</code>```

as result I see:

```<code>    1043:       e8 58 01 00 00          callq  11a0 <_Z6squarei>
    1048:       48 8d 3d b5 0f 00 00    lea    0xfb5(%rip),%rdi        # 2004 <_IO_stdin_used+0x4>
    104f:       89 c6                   mov    %eax,%esi
    1051:       31 c0                   xor    %eax,%eax
    1053:       e8 d8 ff ff ff          callq  1030 <printf@plt>
        printf("result2: %d\n", square(same));
    1058:       89 ef                   mov    %ebp,%edi
    105a:       e8 41 01 00 00          callq  11a0 <_Z6squarei>
    105f:       48 8d 3d aa 0f 00 00    lea    0xfaa(%rip),%rdi        # 2010 <_IO_stdin_used+0x10>
    1066:       89 c6                   mov    %eax,%esi
    1068:       31 c0                   xor    %eax,%eax
    106a:       e8 c1 ff ff ff          callq  1030 <printf@plt>
</code>```

as you can see there are two calls of _Z6squarei,
but why? I marked function as pure, and use the same argument,
why gcc and clang can not remove the second call?

答:
The problem is that while square() is marked pure, printf() isn't. So the compiler is not free to assume that all state is the same after a call to printf(), and so square() itself might read different state and thus produce different output. However, it should be fine if you call square() twice without any other function call inbetween:

```<code>int main(int argc, char *argv[])
{
        const int same = argc;
        int x = square(same);
        int y = square(same);
        printf("result: %d\n", x);
        printf("result2: %d\n", y);
}
</code>```

As eerorika mentioned, __attribute__((const)) will work because it adds the further restriction that square() may not read any state except its inputs. See this question about the difference between pure and const.

Body:
I tried recent versions of gcc (9.2.1) and clang (9.0.1) for such code:

//pure.cpp
int square (int x) __attribute__ ((pure));

int square (int x)
{
        return  x * x;
}

//test.cpp
#include <stdio.h>

int square (int x) __attribute__ ((pure));

int main(int argc, char *argv[])
{
        const int same = argc;
        printf("result: %d\n", square(same));
        printf("result2: %d\n", square(same));
}

and compile it like this:

g++ -ggdb -Ofast -c test.cpp
g++ -ggdb -Ofast -c pure.cpp
g++ -ggdb -Ofast -o test test.o pure.o

as result I see:

    1043:       e8 58 01 00 00          callq  11a0 <_Z6squarei>
    1048:       48 8d 3d b5 0f 00 00    lea    0xfb5(%rip),%rdi        # 2004 <_IO_stdin_used+0x4>
    104f:       89 c6                   mov    %eax,%esi
    1051:       31 c0                   xor    %eax,%eax
    1053:       e8 d8 ff ff ff          callq  1030 <printf@plt>
        printf("result2: %d\n", square(same));
    1058:       89 ef                   mov    %ebp,%edi
    105a:       e8 41 01 00 00          callq  11a0 <_Z6squarei>
    105f:       48 8d 3d aa 0f 00 00    lea    0xfaa(%rip),%rdi        # 2010 <_IO_stdin_used+0x10>
    1066:       89 c6                   mov    %eax,%esi
    1068:       31 c0                   xor    %eax,%eax
    106a:       e8 c1 ff ff ff          callq  1030 <printf@plt>

as you can see there are two calls of _Z6squarei,
but why? I marked function as pure, and use the same argument,
why gcc and clang can not remove the second call?

Body:
The problem is that while square() is marked pure, printf() isn't. So the compiler is not free to assume that all state is the same after a call to printf(), and so square() itself might read different state and thus produce different output. However, it should be fine if you call square() twice without any other function call inbetween:

int main(int argc, char *argv[])
{
        const int same = argc;
        int x = square(same);
        int y = square(same);
        printf("result: %d\n", x);
        printf("result2: %d\n", y);
}

As eerorika mentioned, __attribute__((const)) will work because it adds the further restriction that square() may not read any state except its inputs. See this question about the difference between pure and const.


问:
Should I choose asyncio over gevents to achieve parallel processing in Python3.x?
The task is to run multiple UNIX grep commands on log files using subprocess module at the same time. Running these grep commands synchronously is time consuming and hence want to parallelize the same.

Grep commands that I want to run in parallel:

```<code>grep "start" /var/log/application/start.log.gz
grep "end" /var/log/application/end.log.gz
grep "proceed" /var/log/application/proceed.log.gz
</code>```

Should I choose to use asyncio or opt for gevents?

答:
Q : Should I choose to use asyncio or opt for gevents?

Well, better neither one. Why to pay the extra costs three times (?) if can have the parallel run it?

If there exists an indeed reasonable motivation for such tasks to get launched but ALAP and concurrently ( i.e. under one common shared "ceiling" for disk-I/O and mem-I/O throughput ), yet with minimum overhead add-on costs - measure them, before downvoting without having the hard facts in hand ( right, python process-based execution comes at a huge --not anything near a few [us]-- add-on costs of process-instantiation, the worse in Windows-class O/S, where a full copy of the whole python interpreter state, incl. its all variables, objects and all their memory-rich data-structures, was first to get re-created for each sub-process (do read the multiprocessing documentation details on process-based parallelism and about additional consistency risks, for which fork instantiation method started to be considered unsafe on O/S that permit it ( not all do in 2020-Q1 ) )

Better try using rather but one process with the just-enough, right-designed, smart and well-tuned tool for doing the very that at once, in parallel, the gnu parallel ( best start with reading the man parallel for all the ready-to use parallel job-submission options configurables )

Example :

Grep commands that I want to run in parallel:

Python can launch but this and handle the log and outputs accordingly, as needed

```<code>  parallel --jobs 3           \
           --halt now,fail=1   \
           --joblog LastRUN.log \
      grep {} /var/log/application/{}.log.gz ::: start proceed end
</code>```

will result in equally processed

```<code>grep "start"   /var/log/application/start.log.gz
grep "end"     /var/log/application/end.log.gz
grep "proceed" /var/log/application/proceed.log.gz
</code>```

( plus may serve it with more comfort on how to handle failed cases, logged outputs etc. )

Body:
The task is to run multiple UNIX grep commands on log files using subprocess module at the same time. Running these grep commands synchronously is time consuming and hence want to parallelize the same.

Grep commands that I want to run in parallel:

grep "start" /var/log/application/start.log.gz
grep "end" /var/log/application/end.log.gz
grep "proceed" /var/log/application/proceed.log.gz

Should I choose to use asyncio or opt for gevents?

Body:
Q : Should I choose to use asyncio or opt for gevents?

Well, better neither one. Why to pay the extra costs three times (?) if can have the parallel run it?

If there exists an indeed reasonable motivation for such tasks to get launched but ALAP and concurrently ( i.e. under one common shared "ceiling" for disk-I/O and mem-I/O throughput ), yet with minimum overhead add-on costs - measure them, before downvoting without having the hard facts in hand ( right, python process-based execution comes at a huge --not anything near a few [us]-- add-on costs of process-instantiation, the worse in Windows-class O/S, where a full copy of the whole python interpreter state, incl. its all variables, objects and all their memory-rich data-structures, was first to get re-created for each sub-process (do read the multiprocessing documentation details on process-based parallelism and about additional consistency risks, for which fork instantiation method started to be considered unsafe on O/S that permit it ( not all do in 2020-Q1 ) )

Better try using rather but one process with the just-enough, right-designed, smart and well-tuned tool for doing the very that at once, in parallel, the gnu parallel ( best start with reading the man parallel for all the ready-to use parallel job-submission options configurables )

Example :

Grep commands that I want to run in parallel:

Python can launch but this and handle the log and outputs accordingly, as needed

  parallel --jobs 3           \
           --halt now,fail=1   \
           --joblog LastRUN.log \
      grep {} /var/log/application/{}.log.gz ::: start proceed end

will result in equally processed

grep "start"   /var/log/application/start.log.gz
grep "end"     /var/log/application/end.log.gz
grep "proceed" /var/log/application/proceed.log.gz

( plus may serve it with more comfort on how to handle failed cases, logged outputs etc. )


问:
Which way is faster when stripping part of string in JavaScript
I need to strip part of JWT token and I am courious which one is faster, or less complex internally.

Example input string:

```<code>const input = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOjMsInR5cGUiOjAsImlhdCI6MTU4MTk3NDk1MCwiZXhwIjoxNTgxOTc4NTUwfQ.oEwxI51kVjB6jJUY2N5Ct6-hO0GUCUonolPbryUo-lI"
</code>```

Which one of those methods is faster?

const output =  input.split('.').slice(2,3).join('.');
```

<pre class="lang-js prettyprint-override"><code>const output =  input.replace("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.","");
</code>```

const output =  //REGEX replace
```

I not found any informations about speeds of those methods and I am not exactly master in making tests :D

答:
For things like this, measuring execution time never makes sense, however, using string functions will most likely outperform both of your examples

const input = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOjMsInR5cGUiOjAsImlhdCI6MTU4MTk3NDk1MCwiZXhwIjoxNTgxOTc4NTUwfQ.oEwxI51kVjB6jJUY2N5Ct6-hO0GUCUonolPbryUo-lI";

console.log(input.substr(input.indexOf('.') + 1));```

Body:
I need to strip part of JWT token and I am courious which one is faster, or less complex internally.

Example input string:

const input = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOjMsInR5cGUiOjAsImlhdCI6MTU4MTk3NDk1MCwiZXhwIjoxNTgxOTc4NTUwfQ.oEwxI51kVjB6jJUY2N5Ct6-hO0GUCUonolPbryUo-lI"

Which one of those methods is faster?

const output =  input.split('.').slice(2,3).join('.');

const output =  input.replace("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.","");

const output =  //REGEX replace

I not found any informations about speeds of those methods and I am not exactly master in making tests :D


问:
How to skip iterations of a for-in loop (Swift 3)
Is it possible to skip iterations of a for-in loop in Swift 3?

I want to do something like this:

```<code>for index in 0..<100 {
    if someCondition(index) {
        index = index + 3 //Skip iterations here
    }
}
</code>```

答:
Continue-statement will only skip once, which is not what was asked for.

A while-loop will work, but if you prefer not to use one:

```<code>var skipToIndex = 0

for index in 0...100 {

    if index < skipToIndex {
        continue
    }

    if someCondition {
        skipToIndex = index + 3 //Skip three iterations
    }
}
</code>```

Body:
Is it possible to skip iterations of a for-in loop in Swift 3?

I want to do something like this:

for index in 0..<100 {
    if someCondition(index) {
        index = index + 3 //Skip iterations here
    }
}

Body:
Continue-statement will only skip once, which is not what was asked for.

A while-loop will work, but if you prefer not to use one:

var skipToIndex = 0

for index in 0...100 {

    if index < skipToIndex {
        continue
    }

    if someCondition {
        skipToIndex = index + 3 //Skip three iterations
    }
}


问:
Footer is displaying in middle of screen instead of bottom in Internet Explorer 11
In IE11, footer is displayed at middle of screen rather than on bottom. I am using below CSS which was working file until we upgraded the browser to IE11.

```<code>#footer {
    clear: both;
    height:45px;
    position: absolute;
    bottom: 0;
    left: 0;
    border: none;
    width: 100%;
}
</code>```

Note:- My page has a Tab views & we are using Layout template in MVC. Please suggest some solution.

答:
It may now be less relevant as IE seems to be less and less popular, but the only thing IE properly recognizes as far as vertical positioning is concerned is div. So what seems to have helped in my case is brute-forcing all elements, including the footer, into its own div:</p>

```<code><div style={{position: "sticky", top: "0px", zIndex: "10"}} >
    <Nav />
</div>
<div>
    <C {...props} {...cProps} />
</div>
<div style={{marginTop: "20px"}}>
    <Footer />
</div>
</code>```

Body:
In IE11, footer is displayed at middle of screen rather than on bottom. I am using below CSS which was working file until we upgraded the browser to IE11.

#footer {
    clear: both;
    height:45px;
    position: absolute;
    bottom: 0;
    left: 0;
    border: none;
    width: 100%;
}

Note:- My page has a Tab views & we are using Layout template in MVC. Please suggest some solution.

Body:
It may now be less relevant as IE seems to be less and less popular, but the only thing IE properly recognizes as far as vertical positioning is concerned is div. So what seems to have helped in my case is brute-forcing all elements, including the footer, into its own div:

<div style={{position: "sticky", top: "0px", zIndex: "10"}} >
    <Nav />
</div>
<div>
    <C {...props} {...cProps} />
</div>
<div style={{marginTop: "20px"}}>
    <Footer />
</div>


问:
What's the jquery syntax for click function of submit button
my form has a submit button that's been defined this way:

```<code><input type="submit" name="submit-reg" value="Register" class="submit button">
</code>```

What is the syntax to call the button's jquery click() function?
I've tried:

```<code>$('#submit-reg').click(function()...
</code>```

But it's not working.

答:
```<code>$('.submit').click(function() {
  alert('Button clicked');
});

or

 use id="submit-reg"  # is use for id
</code>```

demo

http://jsfiddle.net/Uuqt8/1/

Body:
my form has a submit button that's been defined this way:

<input type="submit" name="submit-reg" value="Register" class="submit button">

What is the syntax to call the button's jquery click() function?
I've tried:

$('#submit-reg').click(function()...

But it's not working.

Body:
$('.submit').click(function() {
  alert('Button clicked');
});

or

 use id="submit-reg"  # is use for id

demo

http://jsfiddle.net/Uuqt8/1/


问:
adding JWT token in request in reactive way in webflux
I am using WebClient to call Rest API Which are secured by JWT token.
//To get Token

```<code>JwtToken token = client.post()
                .uri("")
                .body(BodyInserters.fromFormData("username", "XXX")
                        .with("password", "XXXXX"))
                .retrieve()
                .bodyToFlux(JwtToken.class)
                .onErrorMap(e -> new Exception("Error While getting Token", e))
                .blockLast();
</code>```

//Call secure API

```<code> WebClient client = consorsWebClientBuilder
                .defaultHeaders(token.bearer())
                .build();

              client
                .get()
                .uri(someURI)
                .retrieve()
                .bodyToMono(String.class)
</code>```

i am calling  Block in reactive chain, so web flux is not happy and saying

block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-client-epoll-12

How can i add token in reactive way ?
Note, I Can create Filter but still in filter also i need to call Block

答:
you can use the doOnSuccess

```<code>client.post()
      .uri("")
      .body(BodyInserters.fromFormData("username", "XXX")
                    .with("password", "XXXXX"))
      .retrieve()
      .bodyToFlux(JwtToken.class)
      .onErrorMap(e -> new Exception("Error While getting Token", e))
      .doOnSuccess(jwtToken -> {
                client.header(HttpHeaders.AUTHORIZATION, "bearer " + jwtToken)
                      .get()
                      ...
      })
</code>```

Body:
I am using WebClient to call Rest API Which are secured by JWT token.
//To get Token

JwtToken token = client.post()
                .uri("")
                .body(BodyInserters.fromFormData("username", "XXX")
                        .with("password", "XXXXX"))
                .retrieve()
                .bodyToFlux(JwtToken.class)
                .onErrorMap(e -> new Exception("Error While getting Token", e))
                .blockLast();

//Call secure API

 WebClient client = consorsWebClientBuilder
                .defaultHeaders(token.bearer())
                .build();

              client
                .get()
                .uri(someURI)
                .retrieve()
                .bodyToMono(String.class)

i am calling  Block in reactive chain, so web flux is not happy and saying

block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-client-epoll-12

How can i add token in reactive way ?
Note, I Can create Filter but still in filter also i need to call Block

Body:
you can use the doOnSuccess

client.post()
      .uri("")
      .body(BodyInserters.fromFormData("username", "XXX")
                    .with("password", "XXXXX"))
      .retrieve()
      .bodyToFlux(JwtToken.class)
      .onErrorMap(e -> new Exception("Error While getting Token", e))
      .doOnSuccess(jwtToken -> {
                client.header(HttpHeaders.AUTHORIZATION, "bearer " + jwtToken)
                      .get()
                      ...
      })


问:
ng-select prevent special characters on typeahead
Using the ng-select library, is is possible to prevent special characters from being processed? Something akin to this solution.

I've tried multiple approaches, but it seems like whatever the typeahead value is isn't exposed and can't be modified.

Is there any workaround to this? Even firing a .next() on the typeahead subject doesn't change what's shown on the view.

答:
If i understand you want to block special characters from being typed and you don't want to see them at all.

Answer :

Yes you can prevent special characters from being processed by using keypress event handler as shown below.

HTML :

```<code><ng-select name="languages" (keypress)="blockSpecialChars($event)" placeholder="languages" [items]="suggestionsList" [typeahead]="typeahead" [(ngModel)]="currentValue" >
</code>```

That's what you want : (keypress)="blockSpecialChars($event)"

Add into your Typescript :

```<code>  blockSpecialChars(event) {
      var k;
      k = event.charCode;
      return((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 || k == 32 || (k >= 48 && k <= 57));
  }
</code>```

If you want to allow some special characters and you don't know what is there charCode. check it here : KeyCode info

Body:
If i understand you want to block special characters from being typed and you don't want to see them at all.

Answer :

Yes you can prevent special characters from being processed by using keypress event handler as shown below.

HTML :

<ng-select name="languages" (keypress)="blockSpecialChars($event)" placeholder="languages" [items]="suggestionsList" [typeahead]="typeahead" [(ngModel)]="currentValue" >

That's what you want : (keypress)="blockSpecialChars($event)"

Add into your Typescript :

  blockSpecialChars(event) {
      var k;
      k = event.charCode;
      return((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 || k == 32 || (k >= 48 && k <= 57));
  }

If you want to allow some special characters and you don't know what is there charCode. check it here : KeyCode info


答:
This will work for you:</p>

```<code>re.findall(r'\bTotal Sales\n(\d*)',data)
</code>```

Title: Python regular expressions word bounaries

Body:
Hello I have a text string like this below and I am trying to use regular expressions to extract the Total Sales quantity which can be found right after the new line after the Total Sales\n43 for example 43 would the total sales. I am using the following command but I want to drop the Total Sales and the \n and just keep the quantity.  I am wondering how I might go about this or will I need to do additional processing.  Thanks

'\ufeffSacramento Association of REALTORS®\nSingle Family Home Sales by ZIP CODE\nJanuary 2020\nZip
 Code\nCurrent Month\nLast Month\nLast Year\nYear-to-Date\nTotal Sales\n43\nREO
 Sales\n0\n45\n40\n43\nMedian Sales Price\n$417,000\n$0\n$410,000\n$400,000\n$417,000\nAverage
 Price/Square Foot\n$268\nShort Sales\n0\n$253\n$239\nN/A\nAverage Sq Ft of
 Property\n1,769\n$0\n1,746\n1,843\nN/A\nTotal Listing Inventory
 *\n69\nConventional\n43\n65\n90\nN/A\nTotal Listing Median Price
 ∞\n$612,475\nSales\n$417,000\n$574,900\n$547,475\nN/A\nTotal Sales\n29\nREO
 **strong text**Sales\n0\n37\n16\n29\nMedian Sales Price\n$369,000

I am using a command like this:

 total_sales = re.findall(r'\bTotal Sales\n\d{2}',data)

which returns:

 ['Total Sales\n43',
 'Total Sales\n29',
 'Total Sales\n29',
 'Total Sales\n32',
 'Total Sales\n30',
 'Total Sales\n52',

Body:
This will work for you:

re.findall(r'\bTotal Sales\n(\d*)',data)


问:
jQuery change input type
Trying to change input type attribute from password to text.

```<code>$('.form').find('input:password').attr({type:"text"});
</code>```

Why this doesn't work?

答:
```<code>    //Get current input object
    var oldInput = $('foo');
    //Clone a new input object from it
    var newInput = oldInput.clone();
    //Set the new object's type property
    newInput.prop('type','text');
    //Replace the old input object with the new one.
    oldInput.replaceWith(newInput);
</code>```

ContentLicense: CC BY-SA 2.5

Title: jQuery change input type

Body:
Trying to change input type attribute from password to text.

$('.form').find('input:password').attr({type:"text"});

Why this doesn't work?


问:
Cannot deploy to heroku because cannot find file
I use heroku to deploy my react app. It used to work fine but now when I run the command

git push heroku master

I see the following error:

```<code>remote: Browserslist: caniuse-lite is outdated. Please run next command `npm update`
remote:        Failed to compile.
remote:
remote:        ./src/service/TodoService.js
remote:        Cannot find file './constants' in './src/service'.
</code>```

I spent more than an hour trying to figure out the cause. Tried answers from this and this. They did not help me.
I decided to check the file that caused the build fail in my github repository and I found that its name was different from the name on my computer.

Here is the github:

And this is the file on my computer:

Seems like Github did not notice that I renamed this file

答:
Finally I found a solution. I used the answer from here.
Basically you need to rename the file that causes build failure so git can track it.

git mv Constants.js constants.js

Then commit, push and make sure that the name on github is corrent. After that you should be able to successfully deploy to heroku

Body:
I use heroku to deploy my react app. It used to work fine but now when I run the command

git push heroku master

I see the following error:

remote: Browserslist: caniuse-lite is outdated. Please run next command `npm update`
remote:        Failed to compile.
remote:
remote:        ./src/service/TodoService.js
remote:        Cannot find file './constants' in './src/service'.

I spent more than an hour trying to figure out the cause. Tried answers from this and this. They did not help me.
I decided to check the file that caused the build fail in my github repository and I found that its name was different from the name on my computer.

Here is the github:

And this is the file on my computer:

Seems like Github did not notice that I renamed this file


问:
where and how to put a picture closing button in my html page
I am stuck. I have a site where people can check my lists, and can click on a code and see a larger picture in a window that opens after. I'd like this larger picture to have a closing option (an "X") somewhere up right. And can not find the place in my HTML page to do it.

Is there anyone who can help me?

Thanks! Tomas http://www.patentesantiguas.com.ar/galeria/repetidas.html

答:
check  this  if you want to use vanilla JavaScript

https://www.cssscript.com/mini-lightbox-popup-with-vanilla-javascript/

or if you want to use jquery  use this easy to implement

https://dimsemenov.com/plugins/magnific-popup/documentation.html


问:
Selected value on a DropDownList inside of a repeater
I'm adding a dropdwonlist inside of my repeater. Now I need to set a selected value for my dropdownlist.. but I'm not being very successful..

```<code>private void PhysicianSource()
{
    DataSet ds = new DataSet();
    DataTable dt = ds.Tables.Add("Source");
    dt.Columns.Add("ID", Type.GetType("System.String"));
    dt.Columns.Add("Desc", Type.GetType("System.String"));

    Provider oProvider = new Provider();
    List<ProviderLabel> lstprovider = oProvider.RetrievePhysicianList();
    foreach (ProviderLabel item in lstprovider)
    {
        DataRow dr = dt.NewRow();
        dr[0] = item.ProviderCode.ID.ToString();
        dr[1] = item.Name.ToString();
        dt.Rows.Add(dr);
    }

    drpPhysicianCode.DataSource = ds;
    drpPhysicianCode.DataMember = "Source";
    drpPhysicianCode.DataTextField = "ID";
    drpPhysicianCode.DataValueField = "ID";
    drpPhysicianCode.DataBind();
}
</code>```

asp.net

```<code><asp:Repeater ID="rptrPatientList" runat="server" >
    <HeaderTemplate></HeaderTemplate>
    <ItemTemplate>
        <tr>
            <td class="style2">
            <asp:DropDownList  ID="DropDownList1"
                DataTextField="ID" runat="server"
                DataValueField="Desc"
                SelectedValue='<%# Eval("Code") %>'
                DataSource="ds">
            </asp:DropDownList>
            </td>

            </td>
        </tr>
</code>```

nothing happens on my codes.. help me guys I'm just a beginner on this.. thank you very much..

答:
```<code>//Declare Class Scoped DataSet and DataTable variables
DataSet ds;
DataTable dt;

//Bind repeater and DataSource method
private void PhysicianSource()
{
    ds = new DataSet();
    dt = ds.Tables.Add("Source");
    dt.Columns.Add("ID", Type.GetType("System.String"));
    dt.Columns.Add("Desc", Type.GetType("System.String"));

    Provider oProvider = new Provider();
    List<ProviderLabel> lstprovider = oProvider.RetrievePhysicianList();
    foreach (ProviderLabel item in lstprovider)
    {
        DataRow dr = dt.NewRow();
        dr[0] = item.ProviderCode.ID.ToString();
        dr[1] = item.Name.ToString();
        dt.Rows.Add(dr);
    }

    drpPhysicianCode.DataSource = ds;
    drpPhysicianCode.DataMember = "Source";
    drpPhysicianCode.DataTextField = "ID";
    drpPhysicianCode.DataValueField = "ID";
    drpPhysicianCode.DataBind();
}

//Repeater Item Data Bound event in which we would find Controls to be bound
//and set DataSource and SelectedValue
protected void rptrPatientList_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        DropDownList DropDownList1 = e.Item.FindControl("DropDownList1") as DropDownList;
        if (DropDownList1 != null)
        {
           DropDownList1.DataSource = dt;
           DropDownList1.DataBind();

           DropDownList1.SelectedValue = // DataBinder Eval 'Code' //;
        }
    }
}

<asp:Repeater ID="rptrPatientList" runat="server" OnItemDataBound="rptrPatientList_ItemDataBound">
    <HeaderTemplate></HeaderTemplate>
    <ItemTemplate>
        <tr>
            <td class="style2">
            <asp:DropDownList  ID="DropDownList1"
                DataTextField="ID" runat="server"
                DataValueField="Desc"
                SelectedValue='<%# Eval("Code") %>'
                DataSource="ds">
            </asp:DropDownList>
            </td>

            </td>
        </tr>
</code>```

Body:
I'm adding a dropdwonlist inside of my repeater. Now I need to set a selected value for my dropdownlist.. but I'm not being very successful..

private void PhysicianSource()
{
    DataSet ds = new DataSet();
    DataTable dt = ds.Tables.Add("Source");
    dt.Columns.Add("ID", Type.GetType("System.String"));
    dt.Columns.Add("Desc", Type.GetType("System.String"));

    Provider oProvider = new Provider();
    List<ProviderLabel> lstprovider = oProvider.RetrievePhysicianList();
    foreach (ProviderLabel item in lstprovider)
    {
        DataRow dr = dt.NewRow();
        dr[0] = item.ProviderCode.ID.ToString();
        dr[1] = item.Name.ToString();
        dt.Rows.Add(dr);
    }

    drpPhysicianCode.DataSource = ds;
    drpPhysicianCode.DataMember = "Source";
    drpPhysicianCode.DataTextField = "ID";
    drpPhysicianCode.DataValueField = "ID";
    drpPhysicianCode.DataBind();
}

asp.net

<asp:Repeater ID="rptrPatientList" runat="server" >
    <HeaderTemplate></HeaderTemplate>
    <ItemTemplate>

            <asp:DropDownList  ID="DropDownList1"
                DataTextField="ID" runat="server"
                DataValueField="Desc"
                SelectedValue='<%# Eval("Code") %>'
                DataSource="ds">
            </asp:DropDownList>

nothing happens on my codes.. help me guys I'm just a beginner on this.. thank you very much..


答: It's case sensitive. Make sure to keep your naming consistent. </p>

Title: Cannot deploy to heroku because cannot find file


问:
C++, Postgres , libpqxx huge query
I have to execute an SQL query to Postgres by the following code. The query returns a huge number of rows (40M or more) and has 4 integer fields: When I use a workstation with 32Gb everything works but on a 16Gb workstation the query is very slow (due to swapping I guess). Is there any way to tell the C++ to load rows at batches, without waiting the entire dataset? With Java I never had these issues before, due to the probably better JDBC driver.

```<code>try {
        work W(*Conn);
        result r = W.exec(sql[sqlLoad]);
        W.commit();

        for (int rownum = 0; rownum < r.size(); ++rownum) {
            const result::tuple row = r[rownum];
            vid1 = row[0].as<int>();
            vid2 = row[1].as<int>();
            vid3 = row[2].as<int>();
            .....

    } catch (const std::exception &e) {
        std::cerr << e.what() << std::endl;
    }
</code>```

I am using PostgreSQL 9.3 and there I see this http://www.postgresql.org/docs/9.3/static/libpq-single-row-mode.html, but I do not how to use it on my C++ code. Your help will be appreciated.

EDIT: This query runs only once, for creating the necessary main memory data structures. As such, tt cannot be optimized. Also, pgAdminIII could easily fetch those rows, in under one minute on the same (or with smaller RAM) PCs. Also, Java could easily handle twice the number of rows (with Statent.setFetchSize() http://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#setFetchSize%28int%29)  So, it is really an issue for the libpqxx library and not an application issue. Is there a way to enforce this functionality in C++, without explicitly setting limits / offsets manually?

答:
Cursors are a good place to start.  Here's another cursor example, using a do-while()

```<code>     const std::conStr("user=" + opt::dbUser + " password=" + opt::dbPasswd + " host=" + opt::dbHost + " dbname=" + opt::dbName);

      pqxx::connection conn(connStr);
      pqxx::work txn(conn);
      std::string selectString = "SELECT id, name FROM table_name WHERE condition";

      pqxx::stateless_cursor<pqxx::cursor_base::read_only, pqxx::cursor_base::owned>
      cursor(txn, selectString, "myCursor", false);

      //cursor variables
      size_t idx = 0;       //starting location
      size_t step = 10000;  //number of rows for each chunk
      pqxx::result result;
      do{
        //get next cursor chunk and update the index
        result = cursor.retrieve( idx, idx + step );
        idx += step;

        size_t records = result.size();
        cout << idx << ": records pulled = " << records << endl;

        for( pqxx::result::const_iterator row : result ){
          //iterate over cursor rows
        }
      }
      while( result.size() == step ); //if the result.size() != step, we're on our last loop
      cout << "Done!" << endl;
</code>```

I'm iterating over approximately 33 million rows in my application.  In addition to using a cursor, I used the following approach:

Split the data into smaller chunks.  For me, that was using bounding
boxes to grab data in a given area.

Construct a query to grab that
chunk, and use a cursor to iterate over it.

Store the chunks on the
heap and free them once you're done processing the data from a given
chunk.

I know this is a very late answer to your question, but I hope this might help someone!

Title: C++, Postgres , libpqxx huge query

Body:
I have to execute an SQL query to Postgres by the following code. The query returns a huge number of rows (40M or more) and has 4 integer fields: When I use a workstation with 32Gb everything works but on a 16Gb workstation the query is very slow (due to swapping I guess). Is there any way to tell the C++ to load rows at batches, without waiting the entire dataset? With Java I never had these issues before, due to the probably better JDBC driver.

try {
        work W(*Conn);
        result r = W.exec(sql[sqlLoad]);
        W.commit();

        for (int rownum = 0; rownum < r.size(); ++rownum) {
            const result::tuple row = r[rownum];
            vid1 = row[0].as<int>();
            vid2 = row[1].as<int>();
            vid3 = row[2].as<int>();
            .....

    } catch (const std::exception &e) {
        std::cerr << e.what() << std::endl;
    }

I am using PostgreSQL 9.3 and there I see this http://www.postgresql.org/docs/9.3/static/libpq-single-row-mode.html, but I do not how to use it on my C++ code. Your help will be appreciated.

EDIT: This query runs only once, for creating the necessary main memory data structures. As such, tt cannot be optimized. Also, pgAdminIII could easily fetch those rows, in under one minute on the same (or with smaller RAM) PCs. Also, Java could easily handle twice the number of rows (with Statent.setFetchSize() http://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#setFetchSize%28int%29)  So, it is really an issue for the libpqxx library and not an application issue. Is there a way to enforce this functionality in C++, without explicitly setting limits / offsets manually?

Body:
Cursors are a good place to start.  Here's another cursor example, using a do-while()

     const std::conStr("user=" + opt::dbUser + " password=" + opt::dbPasswd + " host=" + opt::dbHost + " dbname=" + opt::dbName);

      pqxx::connection conn(connStr);
      pqxx::work txn(conn);
      std::string selectString = "SELECT id, name FROM table_name WHERE condition";

      pqxx::stateless_cursor<pqxx::cursor_base::read_only, pqxx::cursor_base::owned>
      cursor(txn, selectString, "myCursor", false);

      //cursor variables
      size_t idx = 0;       //starting location
      size_t step = 10000;  //number of rows for each chunk
      pqxx::result result;
      do{
        //get next cursor chunk and update the index
        result = cursor.retrieve( idx, idx + step );
        idx += step;

        size_t records = result.size();
        cout << idx << ": records pulled = " << records << endl;

        for( pqxx::result::const_iterator row : result ){
          //iterate over cursor rows
        }
      }
      while( result.size() == step ); //if the result.size() != step, we're on our last loop
      cout << "Done!" << endl;

I'm iterating over approximately 33 million rows in my application.  In addition to using a cursor, I used the following approach:

Split the data into smaller chunks.  For me, that was using bounding
boxes to grab data in a given area.

Construct a query to grab that
chunk, and use a cursor to iterate over it.

Store the chunks on the
heap and free them once you're done processing the data from a given
chunk.

I know this is a very late answer to your question, but I hope this might help someone!


问:
Swagger client generation with Spring REST Docs
I have seen this Spring REST Docs - video

We are doing Spring boot projects and are using springfox library for generating the Swagger-ui and swagger documentation as outlined here

We like what Spring Rest docs can do for generating REST API documentation and the fact that we don't have to add swagger annotations like @ApiResponse or @ApiOperation in our Controller code. And also the fact that the documentation now lives with the code.

But if go with Spring Rest docs, we will miss out on the Swagger-UI that gets automatically generated for our API (when we use swagger integration).

Is it possible for Spring REST docs to generate a test UI like Swagger UI.

答:
This project generates an OpenAPI specification from Spring REST Docs.

https://github.com/ePages-de/restdocs-api-spec