问:
Capture face in webcam and display real time to flask
Basically I have three file which is app.py camera.py and gallery.html. I attach my code for your reference.

app.py

```<code>from flask import Flask, Response, json, render_template
from werkzeug.utils import secure_filename
from flask import request
from os import path, getcwd
import time
import os

app = Flask(__name__)
import cv2
from camera import VideoCamera

app.config['file_allowed'] = ['image/png', 'image/jpeg']
app.config['train_img'] = path.join(getcwd(), 'train_img')

def gen(camera):
    while True:
        frame = camera.get_frame()
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')

@app.route('/video_feed')
def video_feed():
    return Response(gen(VideoCamera()),
                    mimetype='multipart/x-mixed-replace; boundary=frame')

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/gallery')
def get_gallery():
   images = os.listdir(os.path.join(app.static_folder, "capture_image"))
   return render_template('gallery.html', images=images)
app.run()
</code>```

camera.py

```<code>import cv2
import face_recognition
from PIL import Image
import os
import time

dir_path = "C:/tutorial/face_recognition/venv/src4/capture_image"

class VideoCamera(object):
    def __init__(self):
        self.video = cv2.VideoCapture(0)

    def get_frame(self):
        success, frame = self.video.read()
        small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
        rgb_small_frame = small_frame[:, :, ::-1]
        face_locations = face_recognition.face_locations(rgb_small_frame,number_of_times_to_upsample=2)

        for face_location in face_locations:
            top, right, bottom, left = face_location

            face_image = rgb_small_frame[top:bottom, left:right]
            pil_image = Image.fromarray(face_image)
            File_Formatted = ("%s" % (top)) + ".jpg"
            file_path = os.path.join( dir_path, File_Formatted)
            pil_image.save(file_path)

        ret, jpeg = cv2.imencode('.jpg', frame)
        return jpeg.tobytes()
</code>```

gallery.html

```<code><section class="row">
  {% for image in images %}
    <section class="col-md-4 col-sm-6" style="background-color: green;">
      <img src="{{ url_for('static', filename='capture_image/' + image) }}">
    </section>
  {% endfor %}
</section>
</code>```

This what i have done so far, the webcam will capture the face in webcam and save in folder. Then send the image to gallery.html. Currently, i am want to display the image real time in html templete without refresh when the face is captured it will automatically display in html gallery.html dynamically or real time.For your information i am using flask,python and openCV

My question is how i can display the face capture real time without refresh. When new face captured it will automatically display in gallery.html?

Hope someone can regarding on this matter.Thank you

答:
OKAY. The first thing is to download this module : webcamJS . This is the javascript module that will allow you to capture photos from the client side. Test it to familiarize yourself with it (there are many alternatives, but in my opinion it is one of the simplest solutions).

But I'm nice, I still put a minimal code to show you how to use it:

You configure your HTML page and add the following div (do not blame me for the structure of the code, I know it's not pretty, all this hodgepodge between html and javascript, but it works):

```<code><div id="my_photo_booth">
    <div id="my_camera"></div>

        <script src="{{url_for('static',filename='js/webcam.min.js')}}"></script>
        <script src="{{url_for('static',filename='audio/shutter.mp3')}}"></script>
        <script src="{{url_for('static',filename='audio/shutter.ogg')}}"></script>

        <!-- Configure a few settings and attach camera -->
        <script language="JavaScript">
            Webcam.set({
                // live preview size
                width: 320,
                height: 240,

                // device capture size
                dest_width: 640,
                dest_height: 480,

                // final cropped size
                crop_width: 480,
                crop_height: 480,

                // format and quality
                image_format: 'jpeg',
                jpeg_quality: 90,

                // flip horizontal (mirror mode)
                flip_horiz: true
            });
            Webcam.attach( '#my_camera' );
        </script>

        <br>
        <div id="results" style="display:none">
            <!-- Your captured image will appear here... -->
        </div>

        <!-- A button for taking snaps -->
        <form>
            <div id="pre_take_buttons">
                <!-- This button is shown before the user takes a snapshot -->
                <input type=button class="btn btn-success btn-squared" value="CAPTURE" onClick="preview_snapshot()">
            </div>

            <div id="post_take_buttons" style="display:none">
                <!-- These buttons are shown after a snapshot is taken -->
                <input type=button class="btn btn-danger btn-squared responsive-width" value="< AGAIN" onClick="cancel_preview()">
                <input type=button class="btn btn-success btn-squared responsive-width" value="SAVE >" onClick="save_photo()" style="font-weight:bold;">
            </div>
        </form>

</div>
</code>```

A bit of javascript to manipulate the photo capture and send the photo to the server:

```<code><script language="JavaScript">
    // preload shutter audio clip
    var shutter = new Audio();
    shutter.autoplay = false;
    shutter.src = navigator.userAgent.match(/Firefox/) ? '/static/audio/shutter.ogg' : '/static/audio/shutter.mp3';

    function preview_snapshot() {
        // play sound effect
        try { shutter.currentTime = 0; } catch(e) {;} // fails in IE
        shutter.play();

        // freeze camera so user can preview current frame
        Webcam.freeze();

        // swap button sets
        document.getElementById('pre_take_buttons').style.display = 'none';
        document.getElementById('post_take_buttons').style.display = '';
    }

    function cancel_preview() {
        // cancel preview freeze and return to live camera view
        Webcam.unfreeze();

        // swap buttons back to first set
        document.getElementById('pre_take_buttons').style.display = '';
        document.getElementById('post_take_buttons').style.display = 'none';
    }

    function save_photo() {
        // actually snap photo (from preview freeze).
        Webcam.snap( function(data_uri) {
            // display results in page
            console.log(data_uri);

            // shut down camera, stop capturing
            Webcam.reset();

            $.getJSON($SCRIPT_ROOT + '/_photo_cap', {
                photo_cap: data_uri,
            },function(data){
                var response = data.response;
            });

        } );
    }
</script>
</code>```

Obviously this code you add it to the bottom of your html code.

I hope you'll manage with all this. But the interesting part here is the save_photo() function. In this function, I get the data uri from the photo and send it to flask via ajax (Check this link to see how to use jquery / ajax to send data to flask).

On the flask side:

```<code>import base64

@bp.route('/photo')
def photo():
    return render_template('photo.html')

@bp.route('/_photo_cap')
def photo_cap():
    photo_base64 = request.args.get('photo_cap')
    header, encoded = photo_base64.split(",", 1)
    binary_data = base64.b64decode(encoded)
    image_name = "photo.jpeg"

    with open(os.path.join("app/static/images/captures",image_name), "wb") as f:
        f.write(binary_data)
    //facial recognition operations
    response = 'your response'

    return jsonify(response=response)
</code>```

Here there are two routes, one to render the photo capture page, and another to receive the data uri sent via ajax.

Basically what happens in the second route is that I get the data uri, I convert it to base64 and I store it on my disk. Then that's where you intervene. You do your facial recognition operations, then you return a response to your page.

Body:
Basically I have three file which is app.py camera.py and gallery.html. I attach my code for your reference.

app.py

from flask import Flask, Response, json, render_template
from werkzeug.utils import secure_filename
from flask import request
from os import path, getcwd
import time
import os

app = Flask(__name__)
import cv2
from camera import VideoCamera

app.config['file_allowed'] = ['image/png', 'image/jpeg']
app.config['train_img'] = path.join(getcwd(), 'train_img')

def gen(camera):
    while True:
        frame = camera.get_frame()
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')

@app.route('/video_feed')
def video_feed():
    return Response(gen(VideoCamera()),
                    mimetype='multipart/x-mixed-replace; boundary=frame')

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/gallery')
def get_gallery():
   images = os.listdir(os.path.join(app.static_folder, "capture_image"))
   return render_template('gallery.html', images=images)
app.run()

camera.py

import cv2
import face_recognition
from PIL import Image
import os
import time

dir_path = "C:/tutorial/face_recognition/venv/src4/capture_image"

class VideoCamera(object):
    def __init__(self):
        self.video = cv2.VideoCapture(0)

    def get_frame(self):
        success, frame = self.video.read()
        small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
        rgb_small_frame = small_frame[:, :, ::-1]
        face_locations = face_recognition.face_locations(rgb_small_frame,number_of_times_to_upsample=2)

        for face_location in face_locations:
            top, right, bottom, left = face_location

            face_image = rgb_small_frame[top:bottom, left:right]
            pil_image = Image.fromarray(face_image)
            File_Formatted = ("%s" % (top)) + ".jpg"
            file_path = os.path.join( dir_path, File_Formatted)
            pil_image.save(file_path)

        ret, jpeg = cv2.imencode('.jpg', frame)
        return jpeg.tobytes()

gallery.html

  {% for image in images %}

  {% endfor %}

This what i have done so far, the webcam will capture the face in webcam and save in folder. Then send the image to gallery.html. Currently, i am want to display the image real time in html templete without refresh when the face is captured it will automatically display in html gallery.html dynamically or real time.For your information i am using flask,python and openCV

My question is how i can display the face capture real time without refresh. When new face captured it will automatically display in gallery.html?

Hope someone can regarding on this matter.Thank you

Body:
OKAY. The first thing is to download this module : webcamJS . This is the javascript module that will allow you to capture photos from the client side. Test it to familiarize yourself with it (there are many alternatives, but in my opinion it is one of the simplest solutions).

But I'm nice, I still put a minimal code to show you how to use it:

You configure your HTML page and add the following div (do not blame me for the structure of the code, I know it's not pretty, all this hodgepodge between html and javascript, but it works):

<div id="my_photo_booth">
    <div id="my_camera"></div>

        <script src="{{url_for('static',filename='js/webcam.min.js')}}"></script>
        <script src="{{url_for('static',filename='audio/shutter.mp3')}}"></script>
        <script src="{{url_for('static',filename='audio/shutter.ogg')}}"></script>

        <!-- Configure a few settings and attach camera -->
        <script language="JavaScript">
            Webcam.set({
                // live preview size
                width: 320,
                height: 240,

                // device capture size
                dest_width: 640,
                dest_height: 480,

                // final cropped size
                crop_width: 480,
                crop_height: 480,

                // format and quality
                image_format: 'jpeg',
                jpeg_quality: 90,

                // flip horizontal (mirror mode)
                flip_horiz: true
            });
            Webcam.attach( '#my_camera' );
        </script>

        <br>
        <div id="results" style="display:none">
            <!-- Your captured image will appear here... -->
        </div>

        <!-- A button for taking snaps -->
        <form>
            <div id="pre_take_buttons">
                <!-- This button is shown before the user takes a snapshot -->
                <input type=button class="btn btn-success btn-squared" value="CAPTURE" onClick="preview_snapshot()">
            </div>

            <div id="post_take_buttons" style="display:none">
                <!-- These buttons are shown after a snapshot is taken -->
                <input type=button class="btn btn-danger btn-squared responsive-width" value="&lt; AGAIN" onClick="cancel_preview()">
                <input type=button class="btn btn-success btn-squared responsive-width" value="SAVE &gt;" onClick="save_photo()" style="font-weight:bold;">
            </div>
        </form>

</div>

A bit of javascript to manipulate the photo capture and send the photo to the server:

<script language="JavaScript">
    // preload shutter audio clip
    var shutter = new Audio();
    shutter.autoplay = false;
    shutter.src = navigator.userAgent.match(/Firefox/) ? '/static/audio/shutter.ogg' : '/static/audio/shutter.mp3';

    function preview_snapshot() {
        // play sound effect
        try { shutter.currentTime = 0; } catch(e) {;} // fails in IE
        shutter.play();

        // freeze camera so user can preview current frame
        Webcam.freeze();

        // swap button sets
        document.getElementById('pre_take_buttons').style.display = 'none';
        document.getElementById('post_take_buttons').style.display = '';
    }

    function cancel_preview() {
        // cancel preview freeze and return to live camera view
        Webcam.unfreeze();

        // swap buttons back to first set
        document.getElementById('pre_take_buttons').style.display = '';
        document.getElementById('post_take_buttons').style.display = 'none';
    }

    function save_photo() {
        // actually snap photo (from preview freeze).
        Webcam.snap( function(data_uri) {
            // display results in page
            console.log(data_uri);

            // shut down camera, stop capturing
            Webcam.reset();

            $.getJSON($SCRIPT_ROOT + '/_photo_cap', {
                photo_cap: data_uri,
            },function(data){
                var response = data.response;
            });

        } );
    }
</script>

Obviously this code you add it to the bottom of your html code.

I hope you'll manage with all this. But the interesting part here is the save_photo() function. In this function, I get the data uri from the photo and send it to flask via ajax (Check this link to see how to use jquery / ajax to send data to flask).

On the flask side:

import base64

@bp.route('/photo')
def photo():
    return render_template('photo.html')

@bp.route('/_photo_cap')
def photo_cap():
    photo_base64 = request.args.get('photo_cap')
    header, encoded = photo_base64.split(",", 1)
    binary_data = base64.b64decode(encoded)
    image_name = "photo.jpeg"

    with open(os.path.join("app/static/images/captures",image_name), "wb") as f:
        f.write(binary_data)
    //facial recognition operations
    response = 'your response'

    return jsonify(response=response)

Here there are two routes, one to render the photo capture page, and another to receive the data uri sent via ajax.

Basically what happens in the second route is that I get the data uri, I convert it to base64 and I store it on my disk. Then that's where you intervene. You do your facial recognition operations, then you return a response to your page.


来源: stackexchange

问:
Receive text message using J2ME
I am trying to make a J2ME application to SEND and RECEIVE text messages. I'm done with the sending part of it but I am not able to receive any message..

Below is what I tried in order to receive text message;

```<code>    try {
        MessageConnection conn = (MessageConnection) Connector.open("sms://:50001");
        conn.setMessageListener(new MessageListener() {
            public void notifyIncomingMessage(MessageConnection conn) {
                try {
                    Message msg;
                    msg = conn.receive();
                    if (msg instanceof TextMessage) {
                        TextMessage tmsg = (TextMessage) msg;
                        stringItem.setText("Msg: " + tmsg.getPayloadText());
                        System.out.println(tmsg.getPayloadText());
                    }
                    // else if(msg instanceof BinaryMessage) {
                    // .....
                    // } else {
                    // ......
                    // }
                } catch (IOException ex) {
                    ex.printStackTrace();
                } finally {
                    try {
                        conn.close();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        });
    } catch (Exception e1) {
        System.out.println(e1);
    }
</code>```

But this is not working...No errors are showing up either...what is that I am doing wrong?...Can we receive message using J2ME?

The code for sending a message: (UPDATED)

```<code>MessageConnection conn = (MessageConnection) Connector.open("sms://:50001");
TextMessage tmsg = (TextMessage) conn.newMessage(MessageConnection.TEXT_MESSAGE);
tmsg.setPayloadText(message);
tmsg.setAddress("sms://" + number);
conn.send();
</code>```

I have both the send and receive functions in two different forms. What I did is to install and start the application in two different mobiles, send a message from one mobile to the other and receive in the other.

The message is sent and received successfully, but not in the application. The message goes to the inbox of the other mobile.

What can I do?

答:
try 5000 port no.

some phone have this port as sms listener

ContentLicense: CC BY-SA 3.0

Title: Receive text message using J2ME

Body:
I am trying to make a J2ME application to SEND and RECEIVE text messages. I'm done with the sending part of it but I am not able to receive any message..

Below is what I tried in order to receive text message;

    try {
        MessageConnection conn = (MessageConnection) Connector.open("sms://:50001");
        conn.setMessageListener(new MessageListener() {
            public void notifyIncomingMessage(MessageConnection conn) {
                try {
                    Message msg;
                    msg = conn.receive();
                    if (msg instanceof TextMessage) {
                        TextMessage tmsg = (TextMessage) msg;
                        stringItem.setText("Msg: " + tmsg.getPayloadText());
                        System.out.println(tmsg.getPayloadText());
                    }
                    // else if(msg instanceof BinaryMessage) {
                    // .....
                    // } else {
                    // ......
                    // }
                } catch (IOException ex) {
                    ex.printStackTrace();
                } finally {
                    try {
                        conn.close();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        });
    } catch (Exception e1) {
        System.out.println(e1);
    }

But this is not working...No errors are showing up either...what is that I am doing wrong?...Can we receive message using J2ME?

The code for sending a message: (UPDATED)

MessageConnection conn = (MessageConnection) Connector.open("sms://:50001");
TextMessage tmsg = (TextMessage) conn.newMessage(MessageConnection.TEXT_MESSAGE);
tmsg.setPayloadText(message);
tmsg.setAddress("sms://" + number);
conn.send();

I have both the send and receive functions in two different forms. What I did is to install and start the application in two different mobiles, send a message from one mobile to the other and receive in the other.

The message is sent and received successfully, but not in the application. The message goes to the inbox of the other mobile.

What can I do?


问:
IntelliJ Cannot Import sbt Project
I have upgraded IntelliJ to version CE 2017.3 from a CE 2017.2.5, and now I cannot build my sbt project. The build gets stuck on the first step:

```<code>"Build: sync
  MyProjName: syncing...
   dump project structure from sbt"
</code>```

I have deleted the .idea directory and the the MyProjName/project/target directory. I did an sbt build from the command line, which worked.
Then I started IntelliJ again and tried to import MyProjName/build.sbt as a project. I have also logged out/in. Did this several times. The import never progresses past this step.

I work behind a firewall, but I have checked my proxy settings, and they are correct and unchanged from the previous version (if this matters).

How can I troubleshoot / fix this?

The sbt version is 0.13.6. Scala plugin 2017.3.10.

From the log:

```<code>IDE: IntelliJ IDEA (build #IC-173.3727.127, 27 Nov 2017 09:32)
OS: Windows 7 (6.1, amd64)
JRE: 1.8.0_152-release-1024-b6 (JetBrains s.r.o)
JVM: 25.152-b6 (OpenJDK 64-Bit Server VM)
</code>```

答:
Open a terminal inside IDEA by pressing Alt F12 or use sbt shell

Run sbt - if it is first time it will take some time.

Run clean

Run compile - it will download dependencies you have in your project.

Close IDEA project (File -> Close Project) and open it again.

Note: if it asks to import in the right-bottom of the screen activate Enable auto-import, if you don't like to keep it enabled (like me) press Import, cancel the syncronyzation and then Refresh sbt project again. When you try to use import in the middle of a sync it gets stuck with dump project structure from sbt message.

The Refresh sbt project is located at this corner of the Build Sync window - highlighted below:

Title: IntelliJ Cannot Import sbt Project

Body:
I have upgraded IntelliJ to version CE 2017.3 from a CE 2017.2.5, and now I cannot build my sbt project. The build gets stuck on the first step:

"Build: sync
  MyProjName: syncing...
   dump project structure from sbt"

I have deleted the .idea directory and the the MyProjName/project/target directory. I did an sbt build from the command line, which worked.
Then I started IntelliJ again and tried to import MyProjName/build.sbt as a project. I have also logged out/in. Did this several times. The import never progresses past this step.

I work behind a firewall, but I have checked my proxy settings, and they are correct and unchanged from the previous version (if this matters).

How can I troubleshoot / fix this?

The sbt version is 0.13.6. Scala plugin 2017.3.10.

From the log:

IDE: IntelliJ IDEA (build #IC-173.3727.127, 27 Nov 2017 09:32)
OS: Windows 7 (6.1, amd64)
JRE: 1.8.0_152-release-1024-b6 (JetBrains s.r.o)
JVM: 25.152-b6 (OpenJDK 64-Bit Server VM)

ContentLicense: CC BY-SA 4.0


问:
Angular 7 import primitive extensions from an angular library
So I wrote my own primitive extensions and it works well. I use them on several projects and now it's time to centralize my work in a library.

Angular library first attempt

So far so good, the services and components are working well. Now I import my extensions like in the other apps:

extensions.ts

interface String {
    someFunction(this: string): boolean;
}

String.prototype.someFunction= function (this: string): boolean {
    return !this;
};
```

<p>and in my <strong>my-lib.module.ts</strong></p>

<pre class="lang-js prettyprint-override"><code>import './path/to/my/extensions';
</code>```

public-api.ts:

export * from './lib/core/extensions';
```

<p>Then I create a package of my library with <strong>npm pack</strong> and install it in my app with <strong>npm install /absolute/path/to/my-lib</strong>. Once my library is installed, i check if everything is ok.</p>

<p>Everything is ok except the extensions. How can I use <strong>my-lib/extensions</strong> in the projects that import my library?</p>

<p>If I try in my <strong>app.module.ts</strong></p>

<pre class="lang-js prettyprint-override"><code>import 'my-lib/extensions';
</code>```

I have an error:

```<code>Failed to compile.

./src/app/app.module.ts
Module not found: Error: Can't resolve 'my-lib/extensions' in 'C:\Angular\MyApp\src\app'
</code>```

Any idea? I'm kinda lost
(we assume that all the path are correct)

答:
If my-lib is not under your app folder, you need to include it in your tsconfig.json file...</p>

```<code>"include": [
    "path/to/my-lib"
]
</code>```

Body:
So I wrote my own primitive extensions and it works well. I use them on several projects and now it's time to centralize my work in a library.

Angular library first attempt

So far so good, the services and components are working well. Now I import my extensions like in the other apps:

extensions.ts

interface String {
    someFunction(this: string): boolean;
}

String.prototype.someFunction= function (this: string): boolean {
    return !this;
};

and in my my-lib.module.ts

import './path/to/my/extensions';

public-api.ts:

export * from './lib/core/extensions';

Then I create a package of my library with npm pack and install it in my app with npm install /absolute/path/to/my-lib. Once my library is installed, i check if everything is ok.

Everything is ok except the extensions. How can I use my-lib/extensions in the projects that import my library?

If I try in my app.module.ts

import 'my-lib/extensions';

I have an error:

Failed to compile.

./src/app/app.module.ts
Module not found: Error: Can't resolve 'my-lib/extensions' in 'C:\Angular\MyApp\src\app'

Any idea? I'm kinda lost
(we assume that all the path are correct)

Body:
If my-lib is not under your app folder, you need to include it in your tsconfig.json file...

"include": [
    "path/to/my-lib"
]


问:
Transforming two column data in rows to multiple columns in R using tidyr
I'm trying to calculate differences between products and users to use in a recommendation system.

Data is in two column with multiple rows, need to be transformed into rows as users and columns as products.

I tried cast function from reshape package with no success.

```<code>library(dplyr)
library(reshape2)
library(tidyr)
library(reshape)
data <- tibble("customerId" = c(1,2,3,4,1,1), productId = c(10,11,12,10,11,10))
</code>```

I want to transform it to this format:

```<code>   10    11    12
1   1     1     0
2   0     1     0
3   0     0     1
4   1     0     0
</code>```

My main problem right now is at the time we have duplicate record, it should be counted only once, so we have 0-1 values.

答:
An option would be spread to 'wide' format after creating a column of 1s'

```<code>library(tidyverse)
data %>%
  mutate(n = 1) %>%
  spread(productId, n, fill = 0) %>%
  column_to_rownames('customerId')
#  10 11 12
#1  1  1  0
#2  0  1  0
#3  0  0  1
#4  1  0  0
</code>```

Body:
I'm trying to calculate differences between products and users to use in a recommendation system.

Data is in two column with multiple rows, need to be transformed into rows as users and columns as products.

I tried cast function from reshape package with no success.

library(dplyr)
library(reshape2)
library(tidyr)
library(reshape)
data <- tibble("customerId" = c(1,2,3,4,1,1), productId = c(10,11,12,10,11,10))

I want to transform it to this format:

   10    11    12
1   1     1     0
2   0     1     0
3   0     0     1
4   1     0     0

My main problem right now is at the time we have duplicate record, it should be counted only once, so we have 0-1 values.

Body:
An option would be spread to 'wide' format after creating a column of 1s'

library(tidyverse)
data %>%
  mutate(n = 1) %>%
  spread(productId, n, fill = 0) %>%
  column_to_rownames('customerId')
#  10 11 12
#1  1  1  0
#2  0  1  0
#3  0  0  1
#4  1  0  0


问:
Creating string permutations to vary between O and 0
Lets say i have a string that varies in size and is "OOOO". I need the below code to also return "O0O0, 0O0O, 0OO0, O00O, O000, OO00, OOO0". Basically all possible variations of O replaced with 0. What's the best way to do this? Currently it only returns "0OOO, 00OO, 000O, 0000"</p>

```<code>Public Function ParseOs(ByVal PlayerName As String) As String()
    Dim NameChar As Char
    Dim OCount As Integer
    Dim OCountTwo As Integer

    For i = 0 To PlayerName.Length - 1
        NameChar = PlayerName.Chars(i)
        If NameChar = "O" Then
            OCount += 1
        End If
    Next

    Dim NewPlayerName() As String = New String(OCount - 1) {}

    For y = 0 To PlayerName.Length - 1
        NameChar = PlayerName.Chars(y)
        If NameChar = "O" Then
            NewPlayerName(OCountTwo) = PlayerName.Remove(y, 1).Insert(y, "0")
            PlayerName = NewPlayerName(OCountTwo)
            OCountTwo += 1
        End If
    Next

    Return NewPlayerName
End Function
</code>```

答:
One way to do this is via recursion:

```<code>Public Iterator Function ParseOs(ByVal PlayerName As String) As IEnumerable(Of String)
   Dim i as Integer = PlayerName.IndexOf("O")
   If i = -1 Then
       Yield Return PlayerName
       Yield Break
   End If

   'Keep everything (if anything) *before* the O
   Dim base As String = PlayerName.SubString(0, i)

   Dim permutations As IEnumerable(Of String) = New String() {""}
   If PlayerName.Length > i Then
       'Recurse to find all the variations for everything *after* the O
       permutations = ParseOs(PlayerName.SubString(i+1))
   End If

   For Each permutation As String in permutations
        Yield Return base & "O" & permutation
        Yield Return base & "0" & permutation
   Next
End Function
</code>```

If you are sure the inputs will always be all Os, you can simplify further:

```<code>Public Iterator Function ParseOs(ByVal PlayerName As String) As IEnumerable(Of String)
   Dim permutations As IEnumerable(Of String) = New String() {""}
   If PlayerName.Length > 1 Then
       permutations = ParseOs(PlayerName.SubString(1))
   End If

   For Each permutation As String in permutations
        Yield Return "O" & permutation
        Yield Return "0" & permutation
   Next
End Function
</code>```

You can make these more efficient by breaking it into two functions, where the recursive part deals with character arrays rather than strings. And then you can further make that more efficient by converting the arrays to use Span<Char>, so you don't have to allocate a new array for each recursive call.

Body:
Lets say i have a string that varies in size and is "OOOO". I need the below code to also return "O0O0, 0O0O, 0OO0, O00O, O000, OO00, OOO0". Basically all possible variations of O replaced with 0. What's the best way to do this? Currently it only returns "0OOO, 00OO, 000O, 0000"

Public Function ParseOs(ByVal PlayerName As String) As String()
    Dim NameChar As Char
    Dim OCount As Integer
    Dim OCountTwo As Integer

    For i = 0 To PlayerName.Length - 1
        NameChar = PlayerName.Chars(i)
        If NameChar = "O" Then
            OCount += 1
        End If
    Next

    Dim NewPlayerName() As String = New String(OCount - 1) {}

    For y = 0 To PlayerName.Length - 1
        NameChar = PlayerName.Chars(y)
        If NameChar = "O" Then
            NewPlayerName(OCountTwo) = PlayerName.Remove(y, 1).Insert(y, "0")
            PlayerName = NewPlayerName(OCountTwo)
            OCountTwo += 1
        End If
    Next

    Return NewPlayerName
End Function

Body:
One way to do this is via recursion:

Public Iterator Function ParseOs(ByVal PlayerName As String) As IEnumerable(Of String)
   Dim i as Integer = PlayerName.IndexOf("O")
   If i = -1 Then
       Yield Return PlayerName
       Yield Break
   End If

   'Keep everything (if anything) *before* the O
   Dim base As String = PlayerName.SubString(0, i)

   Dim permutations As IEnumerable(Of String) = New String() {""}
   If PlayerName.Length > i Then
       'Recurse to find all the variations for everything *after* the O
       permutations = ParseOs(PlayerName.SubString(i+1))
   End If

   For Each permutation As String in permutations
        Yield Return base & "O" & permutation
        Yield Return base & "0" & permutation
   Next
End Function

If you are sure the inputs will always be all Os, you can simplify further:

Public Iterator Function ParseOs(ByVal PlayerName As String) As IEnumerable(Of String)
   Dim permutations As IEnumerable(Of String) = New String() {""}
   If PlayerName.Length > 1 Then
       permutations = ParseOs(PlayerName.SubString(1))
   End If

   For Each permutation As String in permutations
        Yield Return "O" & permutation
        Yield Return "0" & permutation
   Next
End Function

You can make these more efficient by breaking it into two functions, where the recursive part deals with character arrays rather than strings. And then you can further make that more efficient by converting the arrays to use Span<Char>, so you don't have to allocate a new array for each recursive call.


问:
No known class method for selector in objectiveC class found written in swift class
I have written one class function in one swift class then trying to access the same from one objectiveC class getting No known class method for selector 'myMethodName'. I have also done <code>#import "ProjectName-Swift.h"</code> . It was working properly with Xcode below 10.1 . Please help me at the earliest. Thanks in advance. </p>

```<code>import UIKit

typealias LoginCompletionHandler = (_: Bool) -> Void

class SCLoginViewController: UIViewController {

    var myLoginCompletionBlock: LoginCompletionHandler? = nil
    // MARK: - View Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    //PRAGMA:- Class Methods
    class func showOnNavigation(navigationController:UINavigationController, completionBlock:@escaping LoginCompletionHandler) {
        let vc = SCLoginViewController.init(nibName: "SCLoginViewController", bundle: nil)
        vc.myLoginCompletionBlock = completionBlock
        navigationController.pushViewController(vc, animated: true)
    }

}

#import "LoginOptionVC.h"
#import "Project-Swift.h"

@interface LoginOptionVC () <>

@end

@implementation LoginOptionVC

- (instancetype)initWithBarButtonType:(BarButtonType)btnType showClubLogo:(BOOL)showLogo onCompletion:(CompletionHandler) completionBlock {

    self = [[ClubLoginOptionVC alloc]initWithNibName:@"ClubLoginOptionVC" bundle:nil];

    if (self) {
        self.myCompletionBlock = completionBlock;
    }

    return self;
}

#pragma mark - View LifeCycle
- (void)viewDidLoad {
    [super viewDidLoad];
- (IBAction)clickLogin:(id)sender {
    [SCLoginViewController showOnNavigationWithNavigationController:self.navigationController completionBlock:^(BOOL isSuccess) {
        if (isSuccess) {
            NSLog(@"logged in ");
        }

        if (self.myCompletionBlock) {
            self.myCompletionBlock(isSuccess);
        }
    }];
}
}
</code>```

答:
Addition to Scriptable's answer. If you want to expose all function to Objective-C in a class. Then add @objcMembers attribute.

```<code>@objcMembers class MyController: UIViewController {
   class func showOnNavigation(navigationController:UINavigationController, completionBlock:@escaping LoginCompletionHandler) {

   }
}
</code>```

By way of adding @objcMembers attribute in a class, you no need to add @objc attribute in functions.

Body:
I have written one class function in one swift class then trying to access the same from one objectiveC class getting No known class method for selector 'myMethodName'. I have also done #import "ProjectName-Swift.h" . It was working properly with Xcode below 10.1 . Please help me at the earliest. Thanks in advance.

import UIKit

typealias LoginCompletionHandler = (_: Bool) -> Void

class SCLoginViewController: UIViewController {

    var myLoginCompletionBlock: LoginCompletionHandler? = nil
    // MARK: - View Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    //PRAGMA:- Class Methods
    class func showOnNavigation(navigationController:UINavigationController, completionBlock:@escaping LoginCompletionHandler) {
        let vc = SCLoginViewController.init(nibName: "SCLoginViewController", bundle: nil)
        vc.myLoginCompletionBlock = completionBlock
        navigationController.pushViewController(vc, animated: true)
    }

}

#import "LoginOptionVC.h"
#import "Project-Swift.h"

@interface LoginOptionVC () <>

@end

@implementation LoginOptionVC

- (instancetype)initWithBarButtonType:(BarButtonType)btnType showClubLogo:(BOOL)showLogo onCompletion:(CompletionHandler) completionBlock {

    self = [[ClubLoginOptionVC alloc]initWithNibName:@"ClubLoginOptionVC" bundle:nil];

    if (self) {
        self.myCompletionBlock = completionBlock;
    }

    return self;
}

#pragma mark - View LifeCycle
- (void)viewDidLoad {
    [super viewDidLoad];
- (IBAction)clickLogin:(id)sender {
    [SCLoginViewController showOnNavigationWithNavigationController:self.navigationController completionBlock:^(BOOL isSuccess) {
        if (isSuccess) {
            NSLog(@"logged in ");
        }

        if (self.myCompletionBlock) {
            self.myCompletionBlock(isSuccess);
        }
    }];
}
}

Body:
Addition to Scriptable's answer. If you want to expose all function to Objective-C in a class. Then add @objcMembers attribute.

@objcMembers class MyController: UIViewController {
   class func showOnNavigation(navigationController:UINavigationController, completionBlock:@escaping LoginCompletionHandler) {

   }
}

By way of adding @objcMembers attribute in a class, you no need to add @objc attribute in functions.


问:
Append dataframe with column names alone to another dataframe with data
I have 2 dataframes as below.

Dataframe 1 (with only column names and no data):

```<code>Name   Age   Gender
</code>```

0 rows * 3 columns

Dataframe 2 (has data with over 1000 rows):

```<code>level_1   level_2    level_3
AAA       26         M
BBB       19         F
CCC       24         F
</code>```

1000 rows * 3 columns

I have to append both the above dataframes.

Expected Output

Dataframe 1

```<code>Name   Age   Gender
AAA    26    M
BBB    19    F
CCC    24    F
</code>```

What i tried so far:

```<code>dataframe_1 = dataframe_1.append(dataframe_2,ignore_index = True)
</code>```

which gave me the below output:

```<code>Name   Age   Gender   level_1   level_2   level_3
NaN    NaN   NaN      AAA       26        M
NaN    NaN   NaN      BBB       19        F
NaN    NaN   NaN      CCC       24        F
</code>```

1000 rows * 6 columns

答:
Need same columns names for correct alignment of columns between both DataFrames, so set columns names by from another DataFrame:

```<code>dataframe_2.columns = dataframe_1.columns
dataframe_1 = dataframe_1.append(dataframe_2,ignore_index = True)
</code>```

Another solution:

```<code>dataframe_1 = pd.concat([dataframe_1, dataframe_2],ignore_index = True)
</code>```

```<code>print (dataframe_1)
  Name Age Gender
0  AAA  26      M
1  BBB  19      F
2  CCC  24      F
</code>```

Body:
I have 2 dataframes as below.

Dataframe 1 (with only column names and no data):

Name   Age   Gender

0 rows * 3 columns

Dataframe 2 (has data with over 1000 rows):

level_1   level_2    level_3
AAA       26         M
BBB       19         F
CCC       24         F

1000 rows * 3 columns

I have to append both the above dataframes.

Expected Output

Dataframe 1

Name   Age   Gender
AAA    26    M
BBB    19    F
CCC    24    F

What i tried so far:

dataframe_1 = dataframe_1.append(dataframe_2,ignore_index = True)

which gave me the below output:

Name   Age   Gender   level_1   level_2   level_3
NaN    NaN   NaN      AAA       26        M
NaN    NaN   NaN      BBB       19        F
NaN    NaN   NaN      CCC       24        F

1000 rows * 6 columns

Body:
Need same columns names for correct alignment of columns between both DataFrames, so set columns names by from another DataFrame:

dataframe_2.columns = dataframe_1.columns
dataframe_1 = dataframe_1.append(dataframe_2,ignore_index = True)

Another solution:

dataframe_1 = pd.concat([dataframe_1, dataframe_2],ignore_index = True)

print (dataframe_1)
  Name Age Gender
0  AAA  26      M
1  BBB  19      F
2  CCC  24      F


问:
How to properly highlight selected item on RecyclerView?
I am trying to use a RecyclerView as a horizontal ListView. I am trying to figure out how to highlight the selected item. When I click on one of the items, it gets selected and it is highlighted properly but when I click on another one, the second one gets highlighted with the older one.

Here is my onClick function:

```<code>@Override
public void onClick(View view) {

    if(selectedListItem!=null){
        Log.d(TAG, "selectedListItem " + getPosition() + " " + item);
        selectedListItem.setBackgroundColor(Color.RED);
    }
    Log.d(TAG, "onClick " + getPosition() + " " + item);
    viewHolderListener.onIndexChanged(getPosition());
    selectedPosition = getPosition();
    view.setBackgroundColor(Color.CYAN);
    selectedListItem = view;
}
</code>```

Here is the onBindViewHolder:

```<code>@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
    viewHolder.setItem(fruitsData[position]);
    if(selectedPosition == position)
        viewHolder.itemView.setBackgroundColor(Color.CYAN);
    else
        viewHolder.itemView.setBackgroundColor(Color.RED);

}
</code>```

答:
Make selector:

```<code> <?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/Green_10" android:state_activated="true" />
    <item android:drawable="@color/Transparent" />
</selector>
</code>```

Set it as background at your list item layout

```<code>   <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:background="@drawable/selector_attentions_list_item"
        android:layout_width="match_parent"
        android:layout_height="64dp">
</code>```

In your adapter add OnClickListener to the view (onBind method)

```<code> @Suppress("UNCHECKED_CAST")
    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        fun bindItems(item: T) {
            initItemView(itemView, item)
            itemView.tag = item
            if (isClickable) {
                itemView.setOnClickListener(onClickListener)
            }
        }
    }
</code>```

In the onClick event activate the view:

```<code> fun onItemClicked(view: View){
        view.isActivated = true
    }
</code>```

Body:
I am trying to use a RecyclerView as a horizontal ListView. I am trying to figure out how to highlight the selected item. When I click on one of the items, it gets selected and it is highlighted properly but when I click on another one, the second one gets highlighted with the older one.

Here is my onClick function:

@Override
public void onClick(View view) {

    if(selectedListItem!=null){
        Log.d(TAG, "selectedListItem " + getPosition() + " " + item);
        selectedListItem.setBackgroundColor(Color.RED);
    }
    Log.d(TAG, "onClick " + getPosition() + " " + item);
    viewHolderListener.onIndexChanged(getPosition());
    selectedPosition = getPosition();
    view.setBackgroundColor(Color.CYAN);
    selectedListItem = view;
}

Here is the onBindViewHolder:

@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
    viewHolder.setItem(fruitsData[position]);
    if(selectedPosition == position)
        viewHolder.itemView.setBackgroundColor(Color.CYAN);
    else
        viewHolder.itemView.setBackgroundColor(Color.RED);

}

Body:
Make selector:

 <?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/Green_10" android:state_activated="true" />
    <item android:drawable="@color/Transparent" />
</selector>

Set it as background at your list item layout

   <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:background="@drawable/selector_attentions_list_item"
        android:layout_width="match_parent"
        android:layout_height="64dp">

In your adapter add OnClickListener to the view (onBind method)

 @Suppress("UNCHECKED_CAST")
    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        fun bindItems(item: T) {
            initItemView(itemView, item)
            itemView.tag = item
            if (isClickable) {
                itemView.setOnClickListener(onClickListener)
            }
        }
    }

In the onClick event activate the view:

 fun onItemClicked(view: View){
        view.isActivated = true
    }


问:
What are the often misunderstood concepts in C++?
What are the often misunderstood concepts in c++?</p>

答:
C++ is not a typical object oriented language.

Don't believe me? look at the STL, way more templates than objects.

It's almost impossible to use Java/C# ways of writing object oriented code; it simply doesn't work.

In Java/C# programming, there's alot of newing, lots of utility objects that implement some single cohesive functionality.

In C++, any object newed must be deleted, but there's always the problem of who owns the object

As a result, objects tend to be created on the stack

But when you do that, you have to copy them around all the time if you're going to pass them around to other functions/objects, thus wasting a lot of performance that is said to be achieved with the unmanaged environment of C++

Upon realizing that, you have to think about other ways of organizing your code

You might end up doing things the procedural way, or using metaprogramming idioms like smart pointers

At this point, you've realized that OO in C++ cannot be used the same way as it is used in Java/C#

Q.E.D.

If you insist on doing oop with pointers, you'll usually have large (gigantic!) classes, with clearly defined ownership relationships between objects to avoid memory leaks. And then even if you do that, you're already too far from the Java/C# idiom of oop.

Actually I made up the term "object-oriented", and I can tell you I did not have C++ in mind.

  -- Alan Kay (click the link, it's a video, the quote is at 10:33)

Although from a purist point of view (e.g. Alan Kay), even Java and C# fall short of true oop

OwnerDisplayName: rajKumar

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: starblue

OwnerDisplayName: hasen j

LastEditorDisplayName: hasen j


问:
Preg_match(_all) can't collect some data from Google
I'm creating a tool for my websites to see what position they are in Google on different keywords.

Now, I want to collect this part of their sourcecode:

```<code><a href="http://www.test.com/" class=l onmousedown="return clk(this.href,'','','','1','','0CBoQFjAA')">Linktitle in Google!</a>
</code>```

The problem is that the preg_match OR preg_match_all function doesn't match "onmousedown" or "this.href" or the ,'1' part of the link. And that is exactly the part i need...

Does anyone has an idea why this is, and more important.. how to solve this???

The code I use is obvious.. i even tried to use "/onmousedown/" or "/\'1\'/" but it didn't help.

Thank you very much!!!!

答:
Use this code to parse the anchor tag of google search result

```<code>function parseAnchor($strAnchor)
{
//$strAnchor = "<a onmousedown=\"return clk(this.href,'','','','2','','0CBwQFjAB')\" class=\"l\" href=\"http://php.net/manual/en/function.strpos.php\"><em>PHP</em>: strpos - Manual</a>";

$str_parts = explode(" ",$strAnchor);
$start_index = stripos($str_parts[4],"\"");
$length = strrpos($str_parts[4],"\"") - $start_index;
$link = substr($str_parts[4],$start_index+1,$length-1); //will print the link
print $link;

//Now get postion
$onmousedown_parts = explode(",",$str_parts[2]);

$position = trim($onmousedown_parts[4],"\'");
print "<br>$position"; //will print position
}
</code>```

Try this to parse HTML page

```<code>http://simplehtmldom.sourceforge.net/
</code>```

Body:
I'm creating a tool for my websites to see what position they are in Google on different keywords.

Now, I want to collect this part of their sourcecode:

Linktitle in Google!

The problem is that the preg_match OR preg_match_all function doesn't match "onmousedown" or "this.href" or the ,'1' part of the link. And that is exactly the part i need...

Does anyone has an idea why this is, and more important.. how to solve this???

The code I use is obvious.. i even tried to use "/onmousedown/" or "/\'1\'/" but it didn't help.

Thank you very much!!!!

Body:
Use this code to parse the anchor tag of google search result

function parseAnchor($strAnchor)
{
//$strAnchor = "<a onmousedown=\"return clk(this.href,'','','','2','','0CBwQFjAB')\" class=\"l\" href=\"http://php.net/manual/en/function.strpos.php\"><em>PHP</em>: strpos - Manual</a>";

$str_parts = explode(" ",$strAnchor);
$start_index = stripos($str_parts[4],"\"");
$length = strrpos($str_parts[4],"\"") - $start_index;
$link = substr($str_parts[4],$start_index+1,$length-1); //will print the link
print $link;

//Now get postion
$onmousedown_parts = explode(",",$str_parts[2]);

$position = trim($onmousedown_parts[4],"\'");
print "<br>$position"; //will print position
}

Try this to parse HTML page

http://simplehtmldom.sourceforge.net/


问:
How can I retry using DefaultHttpRequestRetryHandler(HTTPClient) when SocketException occurs during SSL communication on java 11?
How should I implement it to be able to retry SSL communication using httpclient on  java11?

Is it better to override DefaultHttpRequestRetryHandler as shown below?
 Is there a more better way?

  public class HttpRequestRetryHandler extends DefaultHttpRequestRetryHandler {

    @Override
    public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
      IOException cause = exception;
      if (exception instanceof SSLException) {
        if (exception.getCause() != null && exception.getCause() instanceof IOException) {
          cause = (IOException) exception.getCause();
        }
      }
      return super.retryRequest(cause, executionCount, context);
    }
  }
```

<p>In Java 11, SocketException is not retried , because SocketException is wrapped with SSLException.</p>

<p>I read the following content.</p>

<ul>
<li>https://bugs.openjdk.java.net/browse/JDK-8214339</li>
<li><p>http://hg.openjdk.java.net/jdk-updates/jdk11u/rev/18b4acfaaa97</p>

```if ((cause != null) && (cause instanceof IOException)) {
    ssle = new SSLException(reason);
}
```</li>
<li><p>https://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html <br>
DefaultHttpRequestRetryHandler does not retry when an SSLException occurs.</p></li>
</ul>

<p>When using java11, the following error occurs randomly with a probability of less than 0.01%.</p>

<pre class="lang-java prettyprint-override"><code>javax.net.ssl.SSLException: Connection reset
    at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:127)
    at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:321)
    at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:264)
    at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:259)
    at java.base/sun.security.ssl.SSLSocketImpl.handleException(SSLSocketImpl.java:1314)
    at java.base/sun.security.ssl.SSLSocketImpl$AppInputStream.read(SSLSocketImpl.java:839)
    at org.apache.http.impl.io.SessionInputBufferImpl.streamRead(SessionInputBufferImpl.java:137)
    at org.apache.http.impl.io.SessionInputBufferImpl.fillBuffer(SessionInputBufferImpl.java:153)
    at org.apache.http.impl.io.SessionInputBufferImpl.readLine(SessionInputBufferImpl.java:280)
    at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:138)
    at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:56)
    at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:259)
    at org.apache.http.impl.DefaultBHttpClientConnection.receiveResponseHeader(DefaultBHttpClientConnection.java:163)
    at org.apache.http.impl.conn.CPoolProxy.receiveResponseHeader(CPoolProxy.java:157)
    at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:273)
    at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:125)
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:272)
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:186)
    at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
    at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)
    at org.springframework.http.client.HttpComponentsClientHttpRequest.executeInternal(HttpComponentsClientHttpRequest.java:87)
    at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
    at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:735)
    ... 81 common frames omitted
    Suppressed: java.net.SocketException: Broken pipe (Write failed)
        at java.base/java.net.SocketOutputStream.socketWrite0(Native Method)
        at java.base/java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:110)
        at java.base/java.net.SocketOutputStream.write(SocketOutputStream.java:150)
        at java.base/sun.security.ssl.SSLSocketOutputRecord.encodeAlert(SSLSocketOutputRecord.java:81)
        at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:352)
        ... 106 common frames omitted
Caused by: java.net.SocketException: Connection reset
    at java.base/java.net.SocketInputStream.read(SocketInputStream.java:186)
    at java.base/java.net.SocketInputStream.read(SocketInputStream.java:140)
    at java.base/sun.security.ssl.SSLSocketInputRecord.read(SSLSocketInputRecord.java:448)
    at java.base/sun.security.ssl.SSLSocketInputRecord.bytesInCompletePacket(SSLSocketInputRecord.java:68)
    at java.base/sun.security.ssl.SSLSocketImpl.readApplicationRecord(SSLSocketImpl.java:1104)
    at java.base/sun.security.ssl.SSLSocketImpl$AppInputStream.read(SSLSocketImpl.java:823)
    ... 102 common frames omitted
</code>```

答:
I made HttpRequestRetryHandler class.

  public class HttpRequestRetryHandler extends DefaultHttpRequestRetryHandler {

    @Override
    public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
      IOException cause = exception;
      if (exception instanceof SSLException) {
        if (exception.getCause() != null && exception.getCause() instanceof IOException) {
          cause = (IOException) exception.getCause();
        }
      }
      return super.retryRequest(cause, executionCount, context);
    }
  }
```

<p>And it set as HttpClientBuilder.</p>

```CloseableHttpClient httpclient = HttpClients.custom()
        .setRetryHandler(new HttpRequestRetryHandler())
        .build();
```

Conclusion

The SSL communication quality is the same as when using java8.

The underlying problem in the server or network still exists, but the impact of java11 has been resolved.

Body:
How should I implement it to be able to retry SSL communication using httpclient on  java11?

Is it better to override DefaultHttpRequestRetryHandler as shown below?
 Is there a more better way?

  public class HttpRequestRetryHandler extends DefaultHttpRequestRetryHandler {

    @Override
    public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
      IOException cause = exception;
      if (exception instanceof SSLException) {
        if (exception.getCause() != null && exception.getCause() instanceof IOException) {
          cause = (IOException) exception.getCause();
        }
      }
      return super.retryRequest(cause, executionCount, context);
    }
  }

In Java 11, SocketException is not retried , because SocketException is wrapped with SSLException.

I read the following content.

https://bugs.openjdk.java.net/browse/JDK-8214339

http://hg.openjdk.java.net/jdk-updates/jdk11u/rev/18b4acfaaa97

if ((cause != null) && (cause instanceof IOException)) {
    ssle = new SSLException(reason);
}

https://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html

DefaultHttpRequestRetryHandler does not retry when an SSLException occurs.

When using java11, the following error occurs randomly with a probability of less than 0.01%.

javax.net.ssl.SSLException: Connection reset
    at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:127)
    at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:321)
    at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:264)
    at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:259)
    at java.base/sun.security.ssl.SSLSocketImpl.handleException(SSLSocketImpl.java:1314)
    at java.base/sun.security.ssl.SSLSocketImpl$AppInputStream.read(SSLSocketImpl.java:839)
    at org.apache.http.impl.io.SessionInputBufferImpl.streamRead(SessionInputBufferImpl.java:137)
    at org.apache.http.impl.io.SessionInputBufferImpl.fillBuffer(SessionInputBufferImpl.java:153)
    at org.apache.http.impl.io.SessionInputBufferImpl.readLine(SessionInputBufferImpl.java:280)
    at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:138)
    at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:56)
    at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:259)
    at org.apache.http.impl.DefaultBHttpClientConnection.receiveResponseHeader(DefaultBHttpClientConnection.java:163)
    at org.apache.http.impl.conn.CPoolProxy.receiveResponseHeader(CPoolProxy.java:157)
    at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:273)
    at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:125)
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:272)
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:186)
    at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
    at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)
    at org.springframework.http.client.HttpComponentsClientHttpRequest.executeInternal(HttpComponentsClientHttpRequest.java:87)
    at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
    at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:735)
    ... 81 common frames omitted
    Suppressed: java.net.SocketException: Broken pipe (Write failed)
        at java.base/java.net.SocketOutputStream.socketWrite0(Native Method)
        at java.base/java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:110)
        at java.base/java.net.SocketOutputStream.write(SocketOutputStream.java:150)
        at java.base/sun.security.ssl.SSLSocketOutputRecord.encodeAlert(SSLSocketOutputRecord.java:81)
        at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:352)
        ... 106 common frames omitted
Caused by: java.net.SocketException: Connection reset
    at java.base/java.net.SocketInputStream.read(SocketInputStream.java:186)
    at java.base/java.net.SocketInputStream.read(SocketInputStream.java:140)
    at java.base/sun.security.ssl.SSLSocketInputRecord.read(SSLSocketInputRecord.java:448)
    at java.base/sun.security.ssl.SSLSocketInputRecord.bytesInCompletePacket(SSLSocketInputRecord.java:68)
    at java.base/sun.security.ssl.SSLSocketImpl.readApplicationRecord(SSLSocketImpl.java:1104)
    at java.base/sun.security.ssl.SSLSocketImpl$AppInputStream.read(SSLSocketImpl.java:823)
    ... 102 common frames omitted

Body:
I made HttpRequestRetryHandler class.

  public class HttpRequestRetryHandler extends DefaultHttpRequestRetryHandler {

    @Override
    public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
      IOException cause = exception;
      if (exception instanceof SSLException) {
        if (exception.getCause() != null && exception.getCause() instanceof IOException) {
          cause = (IOException) exception.getCause();
        }
      }
      return super.retryRequest(cause, executionCount, context);
    }
  }

And it set as HttpClientBuilder.

CloseableHttpClient httpclient = HttpClients.custom()
        .setRetryHandler(new HttpRequestRetryHandler())
        .build();

Conclusion

The SSL communication quality is the same as when using java8.

The underlying problem in the server or network still exists, but the impact of java11 has been resolved.


问:
Java Swing Timer; Create a loop; count to 4 Twice
With the code below, the timer counts 4 seconds, and if it reaches 1,
'Hello World!' Get's printed.

How can i make it so that the, timer counts to 4 TWICE and print
Hello World only at the first count 1.

How do i do this?

```<code>    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Calendar;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import java.awt.Color;
    import java.awt.Toolkit;

class clockExample1 extends JFrame {

    private JTextField _textfield1;

    public clockExample1() {

        _textfield1 = new JTextField(5);
        _textfield1.setEditable(false);
        JPanel panel1 = new JPanel();
        panel1.setLayout(new FlowLayout());
        panel1.add(_textfield1);
        JButton button1 = new JButton("click here");

        this.setContentPane(panel1);
        this.setTitle("Text Clock 1");
        this.pack();
        this.setLocationRelativeTo(null);
        this.setResizable(true);
        panel1.add(button1);

        ClockListener cl = new ClockListener();
        Timer t = new Timer(1000, cl);
        t.start();

            }

class ClockListener implements ActionListener {

    int count = 0;

    public void actionPerformed(ActionEvent e) {

        int fakeSecond = (count++ % 4) + 1;
        if (fakeSecond == 1) {  System.out.println( "Hello, World!" );

 }
        Calendar now = Calendar.getInstance();
        int h = now.get(Calendar.HOUR_OF_DAY);
        int m = now.get(Calendar.MINUTE);
        int s = now.get(Calendar.SECOND);
        _textfield1.setText("" + fakeSecond + "");

    }

}

    public static void main(String[] args) {
        JFrame clock = new clockExample1();
        clock.setVisible(true);
    }

}
</code>```

答:
Just have an Aletrnativecounter, as i had did in the following</p>

```<code>import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Calendar;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import java.awt.Color;
    import java.awt.Toolkit;

    class clockExample1 extends JFrame {

    private JTextField _textfield1;

    public clockExample1() {
        System.out.println("Flow Here"+"2");
        _textfield1 = new JTextField(5);
        _textfield1.setEditable(false);
        JPanel panel1 = new JPanel();
        panel1.setLayout(new FlowLayout());
        panel1.add(_textfield1);
        JButton button1 = new JButton("click here");

        this.setContentPane(panel1);
        this.setTitle("Text Clock 1");
        this.pack();
        this.setLocationRelativeTo(null);
        this.setResizable(true);
        panel1.add(button1);

        System.out.println("Flow Here"+"3");
        ClockListener cl = new ClockListener();
        Timer t = new Timer(1000, cl);
        t.start();

            }

    class ClockListener implements ActionListener {

    int count = 0, alternativecounter=0;

    public void actionPerformed(ActionEvent e) {
        System.out.println("Flow Here"+"4");
        int fakeSecond = (count++ % 4) + 1;

        if (fakeSecond == 1) {
            alternativecounter+=1;
            System.out.println("alternativecounter"+alternativecounter);
            if(alternativecounter==2)
            {

                alternativecounter=0;
                System.out.println("alternativecounter"+alternativecounter);
                JOptionPane.showMessageDialog(null,"Warm Welcome to you, My dear friend");
            }

    }
        System.out.println("Flow Here"+"5");
        Calendar now = Calendar.getInstance();
        int h = now.get(Calendar.HOUR_OF_DAY);
        int m = now.get(Calendar.MINUTE);
        int s = now.get(Calendar.SECOND);
        _textfield1.setText("" + fakeSecond + "");

    }

    }

    public static void main(String[] args) {
        System.out.println("Flow Here"+"1");
        JFrame clock = new clockExample1();
        clock.setVisible(true);
    }

    }
</code>```

Body:
With the code below, the timer counts 4 seconds, and if it reaches 1,
'Hello World!' Get's printed.

How can i make it so that the, timer counts to 4 TWICE and print
Hello World only at the first count 1.

How do i do this?

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Calendar;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import java.awt.Color;
    import java.awt.Toolkit;

class clockExample1 extends JFrame {

    private JTextField _textfield1;

    public clockExample1() {

        _textfield1 = new JTextField(5);
        _textfield1.setEditable(false);
        JPanel panel1 = new JPanel();
        panel1.setLayout(new FlowLayout());
        panel1.add(_textfield1);
        JButton button1 = new JButton("click here");

        this.setContentPane(panel1);
        this.setTitle("Text Clock 1");
        this.pack();
        this.setLocationRelativeTo(null);
        this.setResizable(true);
        panel1.add(button1);

        ClockListener cl = new ClockListener();
        Timer t = new Timer(1000, cl);
        t.start();

            }

class ClockListener implements ActionListener {

    int count = 0;

    public void actionPerformed(ActionEvent e) {

        int fakeSecond = (count++ % 4) + 1;
        if (fakeSecond == 1) {  System.out.println( "Hello, World!" );

 }
        Calendar now = Calendar.getInstance();
        int h = now.get(Calendar.HOUR_OF_DAY);
        int m = now.get(Calendar.MINUTE);
        int s = now.get(Calendar.SECOND);
        _textfield1.setText("" + fakeSecond + "");

    }

}

    public static void main(String[] args) {
        JFrame clock = new clockExample1();
        clock.setVisible(true);
    }

}

Body:
Just have an Aletrnativecounter, as i had did in the following

import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Calendar;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import java.awt.Color;
    import java.awt.Toolkit;

    class clockExample1 extends JFrame {

    private JTextField _textfield1;

    public clockExample1() {
        System.out.println("Flow Here"+"2");
        _textfield1 = new JTextField(5);
        _textfield1.setEditable(false);
        JPanel panel1 = new JPanel();
        panel1.setLayout(new FlowLayout());
        panel1.add(_textfield1);
        JButton button1 = new JButton("click here");

        this.setContentPane(panel1);
        this.setTitle("Text Clock 1");
        this.pack();
        this.setLocationRelativeTo(null);
        this.setResizable(true);
        panel1.add(button1);

        System.out.println("Flow Here"+"3");
        ClockListener cl = new ClockListener();
        Timer t = new Timer(1000, cl);
        t.start();

            }

    class ClockListener implements ActionListener {

    int count = 0, alternativecounter=0;

    public void actionPerformed(ActionEvent e) {
        System.out.println("Flow Here"+"4");
        int fakeSecond = (count++ % 4) + 1;

        if (fakeSecond == 1) {
            alternativecounter+=1;
            System.out.println("alternativecounter"+alternativecounter);
            if(alternativecounter==2)
            {

                alternativecounter=0;
                System.out.println("alternativecounter"+alternativecounter);
                JOptionPane.showMessageDialog(null,"Warm Welcome to you, My dear friend");
            }

    }
        System.out.println("Flow Here"+"5");
        Calendar now = Calendar.getInstance();
        int h = now.get(Calendar.HOUR_OF_DAY);
        int m = now.get(Calendar.MINUTE);
        int s = now.get(Calendar.SECOND);
        _textfield1.setText("" + fakeSecond + "");

    }

    }

    public static void main(String[] args) {
        System.out.println("Flow Here"+"1");
        JFrame clock = new clockExample1();
        clock.setVisible(true);
    }

    }


答:
Given what you're hoping for, I don't see any problem with:</p>

```<code>dataframe_2.columns = dataframe_1.columns
</code>```

Title: Append dataframe with column names alone to another dataframe with data

Body:
Given what you're hoping for, I don't see any problem with:

dataframe_2.columns = dataframe_1.columns


问:
Microsoft Graph Get access on behalf of a user
Cannot getting an access token by sending a POST request to the /token endpoint from angular to Azure AD.

As mentioned in this documentation (https://learn.microsoft.com/en-us/graph/auth-v2-user), after getting an ahthorization with success, i try to get an access token from Azure AD with Angular 6 but my request does not seem to reach the Azure AD endpoint.

If I execute the request from postman using the same parameters, I get a response.

I do not find what is wrong in my request?

Thank you in advance for your help !

```<code>getToken(tokenId: string) {
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/x-www-form-urlencoded',
        'Host': 'login.microsoftonline.com'
      })
    };
    const body = new HttpParams()
      .set("client_id", "my_client_id")
      .set("scope", "user.read offline_access")
      .set("redirect_uri", "https://localhost:3000/")
      .set("grant_type", "authorization_code")
      .set("client_secret", "my_client_secret")
      .set("code", tokenId);

    this.http.post("https://login.microsoftonline.com/my_tenant_id/oauth2/v2.0/token", body.toString(), httpOptions).toPromise()
    .then(res => {
      // success
    })
    .catch(err => {
      this.error = JSON.stringify(err);
    });
  }
</code>```

There is an error :

"Access to XMLHttpRequest at 'https://login.microsoftonline.com/my_tenant-id/oauth2/v2.0/token' from origin 'https://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource"

i tried to add 'Access-Control-Allow-Origin': '*' to the header but it doesn't work ...

答:
I found a solution : Angular cannot request to "https://login.microsoftonline.com/my_tenant_id/oauth2/v2.0/token" because of the CORS limitations.
So, i post the authorization code to my backend, the backend make the request to get the access token from Azure AD and return the token and the refresh token to Angular.

ps : do not forget "offline_access" scope parameter when getting the first authorization code to be sure to getting the "refresh_token" later !!!

Body:
Cannot getting an access token by sending a POST request to the /token endpoint from angular to Azure AD.

As mentioned in this documentation (https://learn.microsoft.com/en-us/graph/auth-v2-user), after getting an ahthorization with success, i try to get an access token from Azure AD with Angular 6 but my request does not seem to reach the Azure AD endpoint.

If I execute the request from postman using the same parameters, I get a response.

I do not find what is wrong in my request?

Thank you in advance for your help !

getToken(tokenId: string) {
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/x-www-form-urlencoded',
        'Host': 'login.microsoftonline.com'
      })
    };
    const body = new HttpParams()
      .set("client_id", "my_client_id")
      .set("scope", "user.read offline_access")
      .set("redirect_uri", "https://localhost:3000/")
      .set("grant_type", "authorization_code")
      .set("client_secret", "my_client_secret")
      .set("code", tokenId);

    this.http.post("https://login.microsoftonline.com/my_tenant_id/oauth2/v2.0/token", body.toString(), httpOptions).toPromise()
    .then(res => {
      // success
    })
    .catch(err => {
      this.error = JSON.stringify(err);
    });
  }

There is an error :

"Access to XMLHttpRequest at 'https://login.microsoftonline.com/my_tenant-id/oauth2/v2.0/token' from origin 'https://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource"

i tried to add 'Access-Control-Allow-Origin': '*' to the header but it doesn't work ...


问:
SQL query to get all records with certain parent IDs and two additional conditions
So I am working on a table which stores different bus routes. Each route can go through different locations (StationId) and the order in which it goes through each of them is determined by the column StationOrder.

The table looks like this:

```<code>RouteId | StationId | StationOrder |
------------------------------------
1       | 1         | 2
1       | 2         | 3
1       | 4         | 1
3       | 1         | 1
3       | 2         | 3
3       | 3         | 2
</code>```

What I know is the routes that I'm interested in. In this case those are routes with id 1 and 3. I also know which is the starting Station, StationId 1 what I need to select is all StationIds which have StationOrder number higher than the StationOrder number for StationId 1.

I would show what I've tried so far but basically, since the table contains more routes than just two those I know how to select the desired routes:

```<code>SELECT RS.StationId FROM RouteStations AS RS
WHERE RS.RouteId IN (1,3)
</code>```

But when it comes to the second part where I need to select all StationIds with StationOrder number higher than the StationOrder number for StationId 1 for each route my SQL knowledge comes short.

答:
As an alternative to @forpas answer, you can do a join to table itself. </p>

```<code>SELECT s.StationId
FROM RouteStationsS s
    INNER JOIN RouteStation s2 on s.RouteId = s2.RouteId and s.StationOrder > s2.StationOrder
WHERE s2.RouteId IN (1, 3) and s2.StationId = 1
</code>```

Body:
So I am working on a table which stores different bus routes. Each route can go through different locations (StationId) and the order in which it goes through each of them is determined by the column StationOrder.

The table looks like this:

RouteId | StationId | StationOrder |
------------------------------------
1       | 1         | 2
1       | 2         | 3
1       | 4         | 1
3       | 1         | 1
3       | 2         | 3
3       | 3         | 2

What I know is the routes that I'm interested in. In this case those are routes with id 1 and 3. I also know which is the starting Station, StationId 1 what I need to select is all StationIds which have StationOrder number higher than the StationOrder number for StationId 1.

I would show what I've tried so far but basically, since the table contains more routes than just two those I know how to select the desired routes:

SELECT RS.StationId FROM RouteStations AS RS
WHERE RS.RouteId IN (1,3)

But when it comes to the second part where I need to select all StationIds with StationOrder number higher than the StationOrder number for StationId 1 for each route my SQL knowledge comes short.

Body:
As an alternative to @forpas answer, you can do a join to table itself.

SELECT s.StationId
FROM RouteStationsS s
    INNER JOIN RouteStation s2 on s.RouteId = s2.RouteId and s.StationOrder > s2.StationOrder
WHERE s2.RouteId IN (1, 3) and s2.StationId = 1


问:
Which is the difference between Long.valueOf(0) and 0L in Java?
I would like to know the difference between using Long.valueOf(0); or 0L. Are they the same?

I understand that both are Long types so they have a memory consumption of 64-bits long in Java 8.

So how it is better to initialize a variable, considering memory consumption and time complexity?

Long a = Long.valueOf(0);

or

Long b = 0L;

答:
Nothing.

```<code>Long b = 0L;
</code>```

will undergo autoboxing. The compiler replaces it with:

```<code>Long b = Long.valueOf(0L);
</code>```

You can see this if you decompile your class, e.g. using javap.

```<code>void a() {
  Long a = Long.valueOf(0);
}

void b() {
  Long b = 0L;
}
</code>```

Decompiles to:

```<code>  void a();
    Code:
       0: lconst_0
       1: invokestatic  #2                  // Method java/lang/Long.valueOf:(J)Ljava/lang/Long;
       4: astore_1
       5: return

  void b();
    Code:
       0: lconst_0
       1: invokestatic  #2                  // Method java/lang/Long.valueOf:(J)Ljava/lang/Long;
       4: astore_1
       5: return
</code>```

So how it is better initialize a variable, considering memory consumption and time complexity?

Because they are semantically identical, the memory consumption and time complexity is also identical.

Instead, focus on what is actually important, which is readability: use the one you (and others) will find most easy to understand at a glance.

Body:
Nothing.

Long b = 0L;

will undergo autoboxing. The compiler replaces it with:

Long b = Long.valueOf(0L);

You can see this if you decompile your class, e.g. using javap.

void a() {
  Long a = Long.valueOf(0);
}

void b() {
  Long b = 0L;
}

Decompiles to:

  void a();
    Code:
       0: lconst_0
       1: invokestatic  #2                  // Method java/lang/Long.valueOf:(J)Ljava/lang/Long;
       4: astore_1
       5: return

  void b();
    Code:
       0: lconst_0
       1: invokestatic  #2                  // Method java/lang/Long.valueOf:(J)Ljava/lang/Long;
       4: astore_1
       5: return

So how it is better initialize a variable, considering memory consumption and time complexity?

Because they are semantically identical, the memory consumption and time complexity is also identical.

Instead, focus on what is actually important, which is readability: use the one you (and others) will find most easy to understand at a glance.


答:
You can do this with window functions:</p>

```<code>select rs.*
from (select rs.*,
             min(case when stationid = 1 then stationorder end) over (partition by routeid) as stationorder_1
      from routestations rs
     ) rs
where routeid in (1, 3) and
      stationorder > stationorder_1;
</code>```

Title: SQL query to get all records with certain parent IDs and two additional conditions

Body:
You can do this with window functions:

select rs.*
from (select rs.*,
             min(case when stationid = 1 then stationorder end) over (partition by routeid) as stationorder_1
      from routestations rs
     ) rs
where routeid in (1, 3) and
      stationorder > stationorder_1;


问:
Login failed when trying to perform git push to Azure Devops
I am on a Windows 10 machine, and this morning my git credentials were working as expected, and I was busy pushing and pulling code to our Azure Devops project.
Now I cannot, from this specific VM anyways. When I do git pull I get the standard MS authentication prompt, and I can see my MS account (which is connected to windows via our federated AD)

I click on my account, and the prompt goes away, and I get an error in my prompt:

Logon failed, use ctrl+c to cancel basic credential prompt.
Password for 'https://myOrg@dev.azure.com':

If I enter my AD password (or anything else) I get a authentication failed message. I also tried to re-enter my credentials by selecting "Use another account" in the MS sign in window, and I get the same results.

I have seen issues that were solved by removing the cached credentials from the Credential Manager. So I go Control Panel -> Credential Manager and remove all of the credentials that are stored and try the git operation again.

I get the same MS login window, and oddly enough my account is still there, and Connected to windows (and fails the same way when I click on it)

So then I removed my accounts that were associated via Settings -> Accounts -> Access work or school. I could see my MS account there, so that looked promising, but same behaviour.
I tried to update git (it is v2.21.0.windows.1)
I also installed microsoft's git credential manager as per some answers that I found on SO and microsoft's forums.
Still getting the same error.

I rebooted and removed all the credentials/accounts again, then tried from Visual Studio instead of calling git from the command line.

Same error!

My next steps are to rebuild my Windows profile which I am hoping will reset all this stuff. I am able to access the site from another VM, so it seems to be some sort of git configuration/cached credentials on this machine.

Any assistance/ideas are appreciated.

答:
I had this issue when moving my DevOps organisation to a different tenant. The only thing that resolved my issue was to remove the tenant.cache file from the GitCredManager, see:

If you use Visual Studio or the Git command-line tool, you might need to clear the cache for the Git Credential Manager.
  Deleting the %LocalAppData%\GitCredentialManager\tenant.cache file on each client machine resolves the issue.

from https://learn.microsoft.com/en-us/azure/devops/organizations/accounts/connect-organization-to-azure-ad?view=azure-devops


问:
Using Flutter to connect and write to Bluetooth Devices
I'm new with Flutter and am just trying to make this work.

Am using Flutter Blue https://pub.dartlang.org/packages/flutter_blue

It connects though, just this issue when writing.

But when writing i'm receiving this message. Not sure what I am doing wrong though.

here's my code..

```<code>onPressed: () {
                  print("HEY write pressed");
                  var fff1 = new Guid("0000fff1-0000-1000-8000-00805f9b34fb");
                  var fffa = new Guid("0000fffa-0000-1000-8000-00805f9b34fb");
                  BluetoothCharacteristic characteristic = new BluetoothCharacteristic(uuid: fffa, serviceUuid: fff1, descriptors: null, properties: null);
                  _writeCharacteristic(characteristic);
               },
</code>```

PlatformException(locateCharacteristic, service could not be located on the device, null)

I've tried following this post.
Flutter Blue Read characteristic UUID

In production I would probably save the UUID as variables, but the effect should be similar..

If anyone has any guidance or tips that would be super welcome.

答:
Your code is right but the device you want to connect to doesnt contain this service :var fff1 = new Guid("0000fff1-0000-1000-8000-00805f9b34fb");

Check which services exist in the device you want to connect to.

Body:
I'm new with Flutter and am just trying to make this work.

Am using Flutter Blue https://pub.dartlang.org/packages/flutter_blue

It connects though, just this issue when writing.

But when writing i'm receiving this message. Not sure what I am doing wrong though.

here's my code..

onPressed: () {
                  print("HEY write pressed");
                  var fff1 = new Guid("0000fff1-0000-1000-8000-00805f9b34fb");
                  var fffa = new Guid("0000fffa-0000-1000-8000-00805f9b34fb");
                  BluetoothCharacteristic characteristic = new BluetoothCharacteristic(uuid: fffa, serviceUuid: fff1, descriptors: null, properties: null);
                  _writeCharacteristic(characteristic);
               },

PlatformException(locateCharacteristic, service could not be located on the device, null)

I've tried following this post.
Flutter Blue Read characteristic UUID

In production I would probably save the UUID as variables, but the effect should be similar..

If anyone has any guidance or tips that would be super welcome.


问:
concatenate several lines in one with a delimiter with pandas
I want to be able to concatenate string on several lines into one according to an ID. I use the library pandas (python 3).

```<code>val   id
Cat   1
Tiger 2
Ball  3
Bat   1
bill  2
dog   1

l = []
a = 0
while a < lendata:
    if df["id"][a] == 1:
        if a != 0:
            df["val"][tmp] = ' '.join(l)
            l = []
        tmp = a
        l.append(df["val"][a])
    else:
        l.append(df["val"][a])
    a += 1
</code>```

It works with loops.
i need this result,

```<code>val
Cat Tiger Ball
Bat bill
dog
</code>```

not a group by

Question: Do you know how to do it with pandas functions?
Thanks.

答:
With np.split

Use np.diff and find where those differences are less than zero

np.split the val column at those positions

```<code>[*map(' '.join, np.split(df.val, np.flatnonzero(np.diff(df.id) < 0) + 1))]

['Cat Tiger Ball', 'Bat']
</code>```

```<code>pd.Series([*map(' '.join, np.split(df.val, np.flatnonzero(np.diff(df.id) < 0) + 1))])

0    Cat Tiger Ball
1               Bat
dtype: object
</code>```

Combined Wisdom

Using IanS's idea to check where id is equal to 1

```<code>[*map(' '.join, np.split(df.val, np.flatnonzero(df.id == 1)[1:]))]
</code>```

Body:
I want to be able to concatenate string on several lines into one according to an ID. I use the library pandas (python 3).

val   id
Cat   1
Tiger 2
Ball  3
Bat   1
bill  2
dog   1

l = []
a = 0
while a < lendata:
    if df["id"][a] == 1:
        if a != 0:
            df["val"][tmp] = ' '.join(l)
            l = []
        tmp = a
        l.append(df["val"][a])
    else:
        l.append(df["val"][a])
    a += 1

It works with loops.
i need this result,

val
Cat Tiger Ball
Bat bill
dog

not a group by

Question: Do you know how to do it with pandas functions?
Thanks.

Body:
With np.split

Use np.diff and find where those differences are less than zero

np.split the val column at those positions

[*map(' '.join, np.split(df.val, np.flatnonzero(np.diff(df.id) < 0) + 1))]

['Cat Tiger Ball', 'Bat']

pd.Series([*map(' '.join, np.split(df.val, np.flatnonzero(np.diff(df.id) < 0) + 1))])

0    Cat Tiger Ball
1               Bat
dtype: object

Combined Wisdom

Using IanS's idea to check where id is equal to 1

[*map(' '.join, np.split(df.val, np.flatnonzero(df.id == 1)[1:]))]


答:
Replace .columns attribute for the first dataframe with the second's:

```<code>import pandas as pd

df = pd.DataFrame({
    'val': ['Cat', 'Tiger', 'Ball', 'Bat'],
    'id': [1, 2, 3, 1]
})
df2 = pd.DataFrame({
    'waka': [],
    'wattafak': []
})
df.columns = df2.columns
df
</code>```

```<code>    waka    wattafak
0   1   Cat
1   2   Tiger
2   3   Ball
3   1   Bat
</code>```

Body:
I have 2 dataframes as below.

Dataframe 1 (with only column names and no data):

Name   Age   Gender

0 rows * 3 columns

Dataframe 2 (has data with over 1000 rows):

level_1   level_2    level_3
AAA       26         M
BBB       19         F
CCC       24         F

1000 rows * 3 columns

I have to append both the above dataframes.

Expected Output

Dataframe 1

Name   Age   Gender
AAA    26    M
BBB    19    F
CCC    24    F

What i tried so far:

dataframe_1 = dataframe_1.append(dataframe_2,ignore_index = True)

which gave me the below output:

Name   Age   Gender   level_1   level_2   level_3
NaN    NaN   NaN      AAA       26        M
NaN    NaN   NaN      BBB       19        F
NaN    NaN   NaN      CCC       24        F

1000 rows * 6 columns

Body:
Replace .columns attribute for the first dataframe with the second's:

import pandas as pd

df = pd.DataFrame({
    'val': ['Cat', 'Tiger', 'Ball', 'Bat'],
    'id': [1, 2, 3, 1]
})
df2 = pd.DataFrame({
    'waka': [],
    'wattafak': []
})
df.columns = df2.columns
df

    waka    wattafak
0   1   Cat
1   2   Tiger
2   3   Ball
3   1   Bat


问:
Unquote splice without unquote splice?
Is it possible to write the following without using backquote?

(defmacro while (test &rest body)
  `(do ()
       ((not ,test))
     ,@body))
```

<p>Thought I'd try this as an experiment to understand benefit of backquote.</p>

<p>I got as far as this:</p>

<pre class="lang-lisp prettyprint-override"><code>(let* ((test '(> 10))
       (x 0)
       (body '((princ x) (incf x))))
  (list 'do nil (list (list 'not test))))
</code>```

Which successfully generates:

(DO NIL ((NOT (> 10))))
```

To finish this I need a way to spread the n elements of the list body into the generated form.
I know that's the entire purpose of the unquote splice ,@ but is this actually impossible without it? Curious... It's similar to what apply does but I don't want to call a function at this point obviously.

答:
In your case the body contains the remaining forms to be evaluated, and can be added with LIST*:

```<code>(let* ((test '(> 10))
       (x 0)
       (body '((princ x) (incf x))))
  (list* 'do
         nil
         (list (list 'not test))
         body))
</code>```

Another example, where the spliced list is not at the end:

```<code>`(,x ,@y ,z)
</code>```

The above can be written without backquotes as:

```<code>(list* x (append y (list z)))
</code>```

Title: Unquote splice without unquote splice?

Body:
Is it possible to write the following without using backquote?

(defmacro while (test &rest body)
  `(do ()
       ((not ,test))
     ,@body))

Thought I'd try this as an experiment to understand benefit of backquote.

I got as far as this:

(let* ((test '(> 10))
       (x 0)
       (body '((princ x) (incf x))))
  (list 'do nil (list (list 'not test))))

Which successfully generates:

(DO NIL ((NOT (> 10))))

To finish this I need a way to spread the n elements of the list body into the generated form.
I know that's the entire purpose of the unquote splice ,@ but is this actually impossible without it? Curious... It's similar to what apply does but I don't want to call a function at this point obviously.

Body:
In your case the body contains the remaining forms to be evaluated, and can be added with LIST*:

(let* ((test '(> 10))
       (x 0)
       (body '((princ x) (incf x))))
  (list* 'do
         nil
         (list (list 'not test))
         body))

Another example, where the spliced list is not at the end:

`(,x ,@y ,z)

The above can be written without backquotes as:

(list* x (append y (list z)))


问:
Order array of hashes by name but keep names with same id together
I have the following array of hashes:

```<code>  [{:name=>"Albert", :id=>"1"},
  {:name=>"Billy", :id=>"3"},
  {:name=>"Carol", :id=>"4"},
  {:name=>"Dennis", :id=>"2"},
  {:name=>"Ellen", :id=>"1"},
  {:name=>"Frank", :id=>"5"},
  {:name=>"Gerald", :id=>"3"}]
</code>```

I need to sort and have the result be:

```<code>  [{:name=>"Albert", :id=>"1"},
  {:name=>"Ellen", :id=>"1"},
  {:name=>"Billy", :id=>"3"},
  {:name=>"Gerald", :id=>"3"}
  {:name=>"Carol", :id=>"4"},
  {:name=>"Dennis", :id=>"2"},
  {:name=>"Frank", :id=>"5"}]
</code>```

So sort names but group ids together also sorting by name.

I have tried looking at the sort_by method but I don't think it will work in this situation? Any help in the right direction would be appreciated.

答:
You should group by id and then sort by the first’s hash name value.

```<code>input.group_by { |h| h[:id] }.
      values.
      sort_by { |a| a.first[:name] }.
      flatten
#⇒ [{:name=>"Albert", :id=>"1"},
#   {:name=>"Ellen", :id=>"1"},
#   {:name=>"Billy", :id=>"3"},
#   {:name=>"Gerald", :id=>"3"},
#   {:name=>"Carol", :id=>"4"},
#   {:name=>"Dennis", :id=>"2"},
#   {:name=>"Frank", :id=>"5"}]
</code>```

Body:
I have the following array of hashes:

  [{:name=>"Albert", :id=>"1"},
  {:name=>"Billy", :id=>"3"},
  {:name=>"Carol", :id=>"4"},
  {:name=>"Dennis", :id=>"2"},
  {:name=>"Ellen", :id=>"1"},
  {:name=>"Frank", :id=>"5"},
  {:name=>"Gerald", :id=>"3"}]

I need to sort and have the result be:

  [{:name=>"Albert", :id=>"1"},
  {:name=>"Ellen", :id=>"1"},
  {:name=>"Billy", :id=>"3"},
  {:name=>"Gerald", :id=>"3"}
  {:name=>"Carol", :id=>"4"},
  {:name=>"Dennis", :id=>"2"},
  {:name=>"Frank", :id=>"5"}]

So sort names but group ids together also sorting by name.

I have tried looking at the sort_by method but I don't think it will work in this situation? Any help in the right direction would be appreciated.

Body:
You should group by id and then sort by the first’s hash name value.

input.group_by { |h| h[:id] }.
      values.
      sort_by { |a| a.first[:name] }.
      flatten
#⇒ [{:name=>"Albert", :id=>"1"},
#   {:name=>"Ellen", :id=>"1"},
#   {:name=>"Billy", :id=>"3"},
#   {:name=>"Gerald", :id=>"3"},
#   {:name=>"Carol", :id=>"4"},
#   {:name=>"Dennis", :id=>"2"},
#   {:name=>"Frank", :id=>"5"}]