问:
CamcorderProfile.videoCodec returning wrong value
According to the docs, you can use CamcorderProfile to get the devices default video codec format, then set it to MediaRecorder, like this:

```<code>CamcorderProfile mProfile = CamcorderProfile.get(cameraId, CamcorderProfile.QUALITY_HIGH);

//

mMediaRecorder.setVideoEncoder(mProfile.videoCodec);
</code>```

But for some reason it is returning the wrong format.

I'm using the CameraView library and in the FullVideoRecorder class the following is defined:

```<code>switch (mResult.getVideoCodec()) {
    case H_263: mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H263); break;
    case H_264: mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264); break;
    case DEVICE_DEFAULT: mMediaRecorder.setVideoEncoder(mProfile.videoCodec); break;
}
</code>```

The device I'm experiencing the issue with works perfectly fine when I set the video encoder to H_263, but for some reason, when I set it to default it crashes - In this case default means that CamcorderProfile should select the devices default video codec format.

My question:

Is there any reason why CamcorderProfile.videoCodec would return the wrong value and how can this be resolved?

Edit - adding more information

I implemented the following to make sure if CamcoderProfile is returning the wrong value:

```<code>//In onCreate
CamcorderProfile camcorderProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);

//getVideoCodec method below
String profileCodec = getVideoCodec(camcorderProfile.videoCodec);

//Log the result I get
Log.e("Video Codec =", profileCodec);

private String getVideoCodec(int videoCodec){
    switch(videoCodec){
        case MediaRecorder.VideoEncoder.H263:
            return "H263";
        case MediaRecorder.VideoEncoder.H264:
            return "H264";
        case MediaRecorder.VideoEncoder.MPEG_4_SP:
            return "MPEG_4_SP";
        case MediaRecorder.VideoEncoder.DEFAULT:
            return "DEFAULT";
        default:
            return "unknown";
    }
}
</code>```

In my log I get Video Codec = H264, but this is incorrect, it should return Video Codec = H263.

If I pass the following to MediaRecorder, it works perfectly:

```<code>mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H263);
</code>```

but not when I set any of the following:

```<code>mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
mMediaRecorder.setVideoEncoder(mProfile.videoCodec);
</code>```

答:
It looks related to an issue found on CameraView library
https://github.com/natario1/CameraView/issues/467

According with Android documentation if the old android.hardware.camera is used then you cannot trust the value returned by the video profile API.
The same issue is present if you are using the new android.hardware.camera2 with INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY mode.

When using the Camera 2 API in LEGACY mode (i.e. when CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL is set to CameraMetadata.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY), hasProfile(int) may return true for unsupported resolutions. To ensure a a given resolution is supported in LEGACY mode, the configuration given in CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP must contain the the resolution in the supported output sizes.

camcorder.hasProfile is the method for testing if camcorder profile exists for the given camera at the given quality level.

so before using frame rate and resolutions, they have to be checked.

Supported values can be retrieved using getSupportedVideoSizes, getSupportedPreviewSizes, getSupportedPreviewFpsRange methods

getSupportedVideoSizes gets the supported video frame sizes that can be used by MediaRecorder.

If the returned list is not null, the returned list will contain at least one Size and one of the sizes in the returned list must be passed to MediaRecorder.setVideoSize() for camcorder application if camera is used as the video source. In this case, the size of the preview can be different from the resolution of the recorded video during video recording.

So, maybe we should do a checking for the video sizes and if it is empty then lock the preview size to be equal to recording size.

Body:
According to the docs, you can use CamcorderProfile to get the devices default video codec format, then set it to MediaRecorder, like this:

CamcorderProfile mProfile = CamcorderProfile.get(cameraId, CamcorderProfile.QUALITY_HIGH);

//

mMediaRecorder.setVideoEncoder(mProfile.videoCodec);

But for some reason it is returning the wrong format.

I'm using the CameraView library and in the FullVideoRecorder class the following is defined:

switch (mResult.getVideoCodec()) {
    case H_263: mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H263); break;
    case H_264: mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264); break;
    case DEVICE_DEFAULT: mMediaRecorder.setVideoEncoder(mProfile.videoCodec); break;
}

The device I'm experiencing the issue with works perfectly fine when I set the video encoder to H_263, but for some reason, when I set it to default it crashes - In this case default means that CamcorderProfile should select the devices default video codec format.

My question:

Is there any reason why CamcorderProfile.videoCodec would return the wrong value and how can this be resolved?

Edit - adding more information

I implemented the following to make sure if CamcoderProfile is returning the wrong value:

//In onCreate
CamcorderProfile camcorderProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);

//getVideoCodec method below
String profileCodec = getVideoCodec(camcorderProfile.videoCodec);

//Log the result I get
Log.e("Video Codec =", profileCodec);

private String getVideoCodec(int videoCodec){
    switch(videoCodec){
        case MediaRecorder.VideoEncoder.H263:
            return "H263";
        case MediaRecorder.VideoEncoder.H264:
            return "H264";
        case MediaRecorder.VideoEncoder.MPEG_4_SP:
            return "MPEG_4_SP";
        case MediaRecorder.VideoEncoder.DEFAULT:
            return "DEFAULT";
        default:
            return "unknown";
    }
}

In my log I get Video Codec = H264, but this is incorrect, it should return Video Codec = H263.

If I pass the following to MediaRecorder, it works perfectly:

mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H263);

but not when I set any of the following:

mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
mMediaRecorder.setVideoEncoder(mProfile.videoCodec);


来源: stackexchange

问:
what query to use in this situation- sqlServer
I haves 2 tables:

Info:

Score:

What query can i use to get this result?
( The months and years column show the score of the guys in June-2019

答:
Try the following:

```<code>select info.id, info.name,info.age, sum(case when MONTH(convert(datetime,score.date,5)) = 6 and Year(convert(datetime,score.date,5)) = 2019 then score else 0 end) as monthS,sum(case when MONTH(convert(datetime,score.date,5)) = 6 and Year(convert(datetime,score.date,5)) = 2019 then score else 0 end) as  yearS
from info
inner join score
on info.id = score.id
group by info.id, info.name,info.age
</code>```

OR:

```<code>select info.id, info.name,info.age, sum(isnull(score,0)) as monthS,sum(isnull(score,0)) as  yearS
from info
left join
(
    select * from score
    where MONTH(convert(datetime,score.date,5)) = 6 and Year(convert(datetime,score.date,5)) = 2019
 ) as s
on info.id = s.id
group by info.id, info.name,info.age
</code>```

Example working here.

ContentLicense: CC BY-SA 4.0

Body:
Try the following:

select info.id, info.name,info.age, sum(case when MONTH(convert(datetime,score.date,5)) = 6 and Year(convert(datetime,score.date,5)) = 2019 then score else 0 end) as monthS,sum(case when MONTH(convert(datetime,score.date,5)) = 6 and Year(convert(datetime,score.date,5)) = 2019 then score else 0 end) as  yearS
from info
inner join score
on info.id = score.id
group by info.id, info.name,info.age

OR:

select info.id, info.name,info.age, sum(isnull(score,0)) as monthS,sum(isnull(score,0)) as  yearS
from info
left join
(
    select * from score
    where MONTH(convert(datetime,score.date,5)) = 6 and Year(convert(datetime,score.date,5)) = 2019
 ) as s
on info.id = s.id
group by info.id, info.name,info.age

Example working here.


问:
display of blocks when changing tabs
I have the panel with tabs and a panel with content container.
When switching tabs, only div should be changed, and header should be displayed in all tabs.
I use the event selectedTabChange() that is listened to to check which tab is active and show the necessary div tag. What should I write to selectedTabChange()

.html:

```<code>            <mat-tab label="first"></mat-tab>
            <mat-tab label="second"></mat-tab>
            <mat-tab label="third"></mat-tab>
          </mat-tab-group>
          <div class="container">
            <div class="header">Header</div>
            <div *ngIf="isBlock2! && !isBlock3" class="block1">Text</div>
            <div *ngIf="isBlock1! && !isBlock3" class="block2">Text</div>
            <div *ngIf="isBlock1! && !isBlock2" class="block3">Text</div>
          </div>
</code>```

.ts:

```<code>   public isBlock2 = false;
   public isBlock3 = false;

  changeTabs(event) : void {
      isBlock1 != isBlock1;
  }
</code>```

答:
```<code><mat-tab-group>
  <mat-tab label="First"> Content 1 </mat-tab>
  <mat-tab label="Second"> Content 2 </mat-tab>
  <mat-tab label="Third"> Content 3 </mat-tab>
</mat-tab-group>
</code>```

Try something like this

Title: display of blocks when changing tabs

Body:
I have the panel with tabs and a panel with content container.
When switching tabs, only div should be changed, and header should be displayed in all tabs.
I use the event selectedTabChange() that is listened to to check which tab is active and show the necessary div tag. What should I write to selectedTabChange()

.html:

            <mat-tab label="first"></mat-tab>
            <mat-tab label="second"></mat-tab>
            <mat-tab label="third"></mat-tab>
          </mat-tab-group>

Header

Text

Text

Text

.ts:

   public isBlock2 = false;
   public isBlock3 = false;

  changeTabs(event) : void {
      isBlock1 != isBlock1;
  }

Body:
<mat-tab-group>
  <mat-tab label="First"> Content 1 </mat-tab>
  <mat-tab label="Second"> Content 2 </mat-tab>
  <mat-tab label="Third"> Content 3 </mat-tab>
</mat-tab-group>

Try something like this


问:
Make Regex Match Whitespaces in Java
How can I make this regex match white spaces? Currently, it can only match the following:

```<code>abcdatcsdotuniversitydotedu
</code>```

I would like it to mach the following:

```<code>abcd at cs dot university dot edu
</code>```

This is the Regex:

```<code>([A-Za-z][A-Za-z0-9.\\-_]*)\\s[ ]?(at)[ ]*([A-Za-z][A-Za-z0-9\\-_(dot)]*[ ]?(dot)[ ]*[A-Za-z]+)
</code>```

答:
```<code>public static boolean isAlphaNumericWithWhiteSpace(String text) {
        return text != null && text.matches("^[\\p{L}\\p{N}ın\\s]*$");
    }
</code>```

\p{L} matches a single code point in the category "letter".

\p{N} matches any kind of numeric character in any script.

I am using this code.

ContentLicense: CC BY-SA 3.0

Title: Make Regex Match Whitespaces in Java

Body:
How can I make this regex match white spaces? Currently, it can only match the following:

abcdatcsdotuniversitydotedu

I would like it to mach the following:

abcd at cs dot university dot edu

This is the Regex:

([A-Za-z][A-Za-z0-9.\\-_]*)\\s[ ]?(at)[ ]*([A-Za-z][A-Za-z0-9\\-_(dot)]*[ ]?(dot)[ ]*[A-Za-z]+)

Body:
public static boolean isAlphaNumericWithWhiteSpace(String text) {
        return text != null && text.matches("^[\\p{L}\\p{N}ın\\s]*$");
    }

\p{L} matches a single code point in the category "letter".

\p{N} matches any kind of numeric character in any script.

I am using this code.


问:
Groupby + Transpose column starting with particular string
I have a df like this:

```<code>ID   Name    Price
1    Fruit   10.5
1    xxx     10.5
1    yyy     8.5
1    Apple    4.2
1    aaa      4.1
1    bbb      0.1
1    Mango    2.1
1    abc      1
1    lmn
2    Fruit1   7.6  ### and so on for ID 2
</code>```

Above df has below properties:

The same thing is repeated for ID 2,3,4 ...and so on

For every ID the 1st line item will be different. eg Fruit and Fruit1

For every ID there will always be Apple some row items and then Mango

Expected Output:

```<code>ID  Name   Price   Apple  aaa  bbb  Mango
1   Fruit  10.5    4.2    4.1  0.1  2.1
2   Fruit1 7.6
</code>```

Problem:

1.I want a df which keeps the 1st row for every ID

2.Take all the rows starting from Apple till Mango, do a transpose and put their price value

3.Don't care about the rows like xxx or abc in my expected output

I know how to groupby by ID or transpose by a column but can't figure out to groupby + transpose only for certain rows.

答:
Sometimes Pandas methods aren't the answer.

```<code>seen = set()
result = []
current = None
apple = 'Apple'
mango = 'Mango'
fruit = {apple, mango}

for tup in df.itertuples():
    if tup.ID not in seen:
        result.append({'ID': tup.ID, 'Name': tup.Name})
        current = result[-1]
        seen.add(tup.ID)
    elif mango not in current and (tup.Name in fruit or apple in current):
        current[tup.Name] = tup.Price

d = pd.DataFrame(result)

d

   Apple  ID  Mango    Name   aaa   bbb
0    4.2   1    2.1   Fruit   4.1   0.1
1   40.2   2   20.1  Fruit1  40.1  10.1
</code>```

I'll use a fun sorting technique to get things in the correct order.

```<code>key = lambda x: (x != 'ID', x != 'Name', x != 'Apple', x == 'Mango')
d[sorted(d, key=key)]

   ID    Name  Apple   aaa   bbb  Mango
0   1   Fruit    4.2   4.1   0.1    2.1
1   2  Fruit1   40.2  40.1  10.1   20.1
</code>```

Experimental

```<code>def f(id_, d):
    names = d.Name.to_numpy()
    apple = names == 'Apple'
    mango = np.append(False, names[:-1] == 'Mango')
    a = np.logical_or.accumulate(apple)
    m = np.logical_or.accumulate(mango)
    mask = a ^ m
    res = {'ID': id_, 'Name': d.Name.iloc[0], **dict(zip(names[mask], d.Price[mask]))}
    return res

key = lambda x: (x != 'ID', x != 'Name', x != 'Apple', x == 'Mango')
pd.DataFrame([*map(f, *zip(*df.groupby('ID'),))]).pipe(lambda d: d[sorted(d, key=key)])

   ID    Name  Apple   aaa   bbb  Mango
0   1   Fruit    4.2   4.1   0.1    2.1
1   2  Fruit1   40.2  40.1  10.1   20.1
</code>```

Experiment #2

This isn't perfect as it doesn't guarantee that only things between 'Apple' and 'Mango' are kept.

```<code>def f(d):
    d0 = d.drop('Price', 1).head(1).reset_index(drop=True)
    d1 = d.set_index('Name')[['Price']].tail(-1).T.reset_index(drop=True)
    return d0.join(d1)

d = pd.concat([f(d) for _, d in df.groupby('ID')], ignore_index=True)
i, j = d.columns.get_indexer(['Apple', 'Mango'])

d[['ID', 'Name']].join(d[d.columns[i:j + 1]])

   ID    Name  Apple   aaa   bbb  Mango
0   1   Fruit    4.2   4.1   0.1    2.1
1   2  Fruit1   40.2  40.1  10.1   20.1
</code>```

Body:
I have a df like this:

ID   Name    Price
1    Fruit   10.5
1    xxx     10.5
1    yyy     8.5
1    Apple    4.2
1    aaa      4.1
1    bbb      0.1
1    Mango    2.1
1    abc      1
1    lmn
2    Fruit1   7.6  ### and so on for ID 2

Above df has below properties:

The same thing is repeated for ID 2,3,4 ...and so on

For every ID the 1st line item will be different. eg Fruit and Fruit1

For every ID there will always be Apple some row items and then Mango

Expected Output:

ID  Name   Price   Apple  aaa  bbb  Mango
1   Fruit  10.5    4.2    4.1  0.1  2.1
2   Fruit1 7.6

Problem:

1.I want a df which keeps the 1st row for every ID

2.Take all the rows starting from Apple till Mango, do a transpose and put their price value

3.Don't care about the rows like xxx or abc in my expected output

I know how to groupby by ID or transpose by a column but can't figure out to groupby + transpose only for certain rows.

Body:
Sometimes Pandas methods aren't the answer.

seen = set()
result = []
current = None
apple = 'Apple'
mango = 'Mango'
fruit = {apple, mango}

for tup in df.itertuples():
    if tup.ID not in seen:
        result.append({'ID': tup.ID, 'Name': tup.Name})
        current = result[-1]
        seen.add(tup.ID)
    elif mango not in current and (tup.Name in fruit or apple in current):
        current[tup.Name] = tup.Price

d = pd.DataFrame(result)

d

   Apple  ID  Mango    Name   aaa   bbb
0    4.2   1    2.1   Fruit   4.1   0.1
1   40.2   2   20.1  Fruit1  40.1  10.1

I'll use a fun sorting technique to get things in the correct order.

key = lambda x: (x != 'ID', x != 'Name', x != 'Apple', x == 'Mango')
d[sorted(d, key=key)]

   ID    Name  Apple   aaa   bbb  Mango
0   1   Fruit    4.2   4.1   0.1    2.1
1   2  Fruit1   40.2  40.1  10.1   20.1

Experimental

def f(id_, d):
    names = d.Name.to_numpy()
    apple = names == 'Apple'
    mango = np.append(False, names[:-1] == 'Mango')
    a = np.logical_or.accumulate(apple)
    m = np.logical_or.accumulate(mango)
    mask = a ^ m
    res = {'ID': id_, 'Name': d.Name.iloc[0], **dict(zip(names[mask], d.Price[mask]))}
    return res

key = lambda x: (x != 'ID', x != 'Name', x != 'Apple', x == 'Mango')
pd.DataFrame([*map(f, *zip(*df.groupby('ID'),))]).pipe(lambda d: d[sorted(d, key=key)])

   ID    Name  Apple   aaa   bbb  Mango
0   1   Fruit    4.2   4.1   0.1    2.1
1   2  Fruit1   40.2  40.1  10.1   20.1

Experiment #2

This isn't perfect as it doesn't guarantee that only things between 'Apple' and 'Mango' are kept.

def f(d):
    d0 = d.drop('Price', 1).head(1).reset_index(drop=True)
    d1 = d.set_index('Name')[['Price']].tail(-1).T.reset_index(drop=True)
    return d0.join(d1)

d = pd.concat([f(d) for _, d in df.groupby('ID')], ignore_index=True)
i, j = d.columns.get_indexer(['Apple', 'Mango'])

d[['ID', 'Name']].join(d[d.columns[i:j + 1]])

   ID    Name  Apple   aaa   bbb  Mango
0   1   Fruit    4.2   4.1   0.1    2.1
1   2  Fruit1   40.2  40.1  10.1   20.1


问:
Why do the programmers usually use underscore prefix inside of some function variables?
Thing is I know programming basics, someone told me this is used to encapsulation inside the source of the program (the code with OOP (object oriented programming)).

But I want to know how to implement this programming style successfully, thank you!

I didn't pay attention to it, but as I told you before I could see this is used to make some reference to a variable/property that is similar to another one declared on another place.

```<code>function sample(param, parent){
  let _param = "something(specially an object or method from an object)"
}
</code>```

答: It is a mild form of hungarian notation to distinguish the scope of a given variable.</p>

Body:
Thing is I know programming basics, someone told me this is used to encapsulation inside the source of the program (the code with OOP (object oriented programming)).

But I want to know how to implement this programming style successfully, thank you!

I didn't pay attention to it, but as I told you before I could see this is used to make some reference to a variable/property that is similar to another one declared on another place.

function sample(param, parent){
  let _param = "something(specially an object or method from an object)"
}


问:
How to set SPC to act as Enter in minibuffer mode?
When I edit in minibuffer mode,  I must press Enter  to exit minibuffer.

But I prefer to use Space.

"Space" completes word again and again.

When the message is "Sole Completion", press Space to exit minibuffer.

Defaullt Space key in the second step cannot exit minibuffer, I remap it , but it not works at all.

(define-key minibuffer-local-map (kbd "SPC") `minibuffer-complete-and-exit)

any idea？

答:
Need to define a key in the  minibuffer-local-completion-map:

```<code>(define-key minibuffer-local-completion-map (kbd "SPC") 'minibuffer-complete-and-exit)
</code>```

Body:
Need to define a key in the  minibuffer-local-completion-map:

(define-key minibuffer-local-completion-map (kbd "SPC") 'minibuffer-complete-and-exit)


问:
Javascript function only works on the first row only inside my modal
I am using a javascript function for input verification where it is being used inside a modal. I click the edit button at the first row, javascript functions work well. But when I click on the edit button on the second row, and succeeding rows, it doesn't function.

I am not really sure if the problem is the data inside the modal or the data outside the modal

I tried adding a class name in the input fields and changing the calling function in javascript from "#name" to ".name" but it did not work.

I also tried the shown.bs function

// Here is my code for the table (partial)

```<code>    <?php
    if ($result = mysqli_query($conn, $sql_accounts)) {
    while ($row=mysqli_fetch_array($result)) {
    ?>
    <tr>
    <form action="update.php" method="POST">
    <td>
    <?php echo $row["username"]; ?> </td>
    <td>
    <?php echo $row["firstname"]; ?> </td>
    <td> .....
    <td>
    <?php echo $row["status"]; ?> </td>
    <td>
    <?php
    if ($row["status"] == "Deactivated") {
    ?>
    <a href="update.php?activate=<?php echo $row['accountid']; ?>" class="btn btn-info"> Activate </a>
    <?php
    } elseif ($row["status"] == "Active") {
    ?>
    <a href="update.php?deactivate=<?php echo $row['accountid']; ?>" class="btn btn-warning"> Deactivate </a>
    <?php
    } ?>
    <a href="#edit<?php echo $row['accountid']; ?>" data-toggle="modal" class="btn btn-success" data-toggle="modal">Edit</a>
</code>```

// Here is my code for the modal (partial)

```<code>    <div id="edit<?php echo $row['accountid']; ?>" class="modal fade" role="dialog">
    <div class="modal-dialog">
    <!-- Modal content-->
    <div class="modal-content">
    <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal">×</button>
    <h4 class="modal-title">Edit Account</h4>
    </div>
    <div class="modal-body">
    <form method="POST" action="editaccount.php">
    <div class="form-group">
    <input type="hidden" name="edit_item_id" value="<?php echo $row['accountid']; ?>">
    <label>Username</label>
    <span id="popover-username" class="pun hide pull-right block-help"><i class="fa fa-info-circle text-danger" aria-hidden="true"></i> Username must not contain any special characters</span>
    <input type="text" id="username" name="username" class="username form-control" value="<?php echo $row['username']; ?>" placeholder="Enter Username">
</code>```

//Here is my javascript function

```<code>    <script>
        $(document).ready(function() {

            $('#password').keyup(function() {
                var password = $('#password').val();
                if (checkStrength(password) == false) {
                    $("#submit").attr('disabled', 'disabled');
                }
            });

            $('#confirm_password').blur(function() {
                if ($('#password').val() !== $('#confirm_password').val()) {
                    $('#popover-cpassword').removeClass('hide');
                    $("#submit").attr('disabled', 'disabled');
                } else {
                    $('#popover-cpassword').addClass('hide');
                    $("#submit").removeAttr('disabled');
                }
            });

            $('#username').blur(function() {
                var regex = /\`|\~|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\+|\=|\[|\{|\]|\}|\||\\|\'|\<|\,|\.|\>|\?|\/|\""|\;|\:|\s/;
                if ($('#username').val().match(regex)) {
                    $('#popover-username').removeClass('hide');
                    $("#submit").attr('disabled', 'disabled');
                } else {
                    $('#popover-username').addClass('hide');
                    $('#sign-up').attr('disabled', false);
                    $("#submit").removeAttr('disabled');
                }
            })

            $('#contact_number').blur(function() {
                var regex = /^[(9)][(\d+)]{9}$/;
                if ($('#contact_number').val().match(regex)) {
                    $('#popover-cnumber').addClass('hide');
                    $("#submit").removeAttr('disabled');
                } else {
                    $('#popover-cnumber').removeClass('hide');
                    $("#submit").attr('disabled', 'disabled');
                }
            });

            $('#password').keyup(function() {
                var password = $('#password').val();
                if (checkStrength(password) == false) {
                    $("#submit").attr('disabled', 'disabled');
                }
            });
</code>```

A message should come out once an input is wrong, like for example I input # in the username field there should be a message user name must containany special character where the javascript function removes the class hide from the span code in the modal

答:
As I mentioned above you should use class selector and also I slightly improved your validations

```<code>$('.password').keyup(function() {
  $("#submit").prop('disabled', checkStrength($(this).val()) === false);
});

$('.confirm_password').blur(function() {
  var arePasswordTheSame = $('.password').val() !== $(this).val();
  $('.popover-cpassword').toggleClass('hide', !arePasswordTheSame);
  $("#submit").prop('disabled', !arePasswordTheSame)
});

$('.username').blur(function() {
  var regex = /\`|\~|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\+|\=|\[|\{|\]|\}|\||\\|\'|\<|\,|\.|\>|\?|\/|\""|\;|\:|\s/;
  var isUserNameCorrect = $(this).val().match(regex);
  $('.popover-username').toggleClass('hide', !isUserNameCorrect);
  $(".submit").prop('disabled', !isUserNameCorrect);
  $('.sign-up').prop('disabled', !isUserNameCorrect);
})

$('.contact_number').blur(function() {
  var regex = /^[(9)][(\d+)]{9}$/;
  var isNumberCorrect = $(this).val().match(regex)
  $('.popover-cnumber').toggleClass('hide', !isNumberCorrect);
  $(".submit").prop('disabled', !isNumberCorrect);
});
</code>```

Also you will need to add your current container to all class seelctors. For more info please reference API

Body:
I am using a javascript function for input verification where it is being used inside a modal. I click the edit button at the first row, javascript functions work well. But when I click on the edit button on the second row, and succeeding rows, it doesn't function.

I am not really sure if the problem is the data inside the modal or the data outside the modal

I tried adding a class name in the input fields and changing the calling function in javascript from "#name" to ".name" but it did not work.

I also tried the shown.bs function

// Here is my code for the table (partial)

    <?php
    if ($result = mysqli_query($conn, $sql_accounts)) {
    while ($row=mysqli_fetch_array($result)) {
    ?>

    <form action="update.php" method="POST">

    <?php echo $row["username"]; ?>

    <?php echo $row["firstname"]; ?>
     .....

    <?php echo $row["status"]; ?>

    <?php
    if ($row["status"] == "Deactivated") {
    ?>
    <a href="update.php?activate=<?php echo $row['accountid']; ?>" class="btn btn-info"> Activate
    <?php
    } elseif ($row["status"] == "Active") {
    ?>
    <a href="update.php?deactivate=<?php echo $row['accountid']; ?>" class="btn btn-warning"> Deactivate
    <?php
    } ?>
    <a href="#edit<?php echo $row['accountid']; ?>" data-toggle="modal" class="btn btn-success" data-toggle="modal">Edit

// Here is my code for the modal (partial)

    <div id="edit<?php echo $row['accountid']; ?>" class="modal fade" role="dialog">

    <button type="button" class="close" data-dismiss="modal">×</button>

Edit Account

    <form method="POST" action="editaccount.php">

    <input type="hidden" name="edit_item_id" value="<?php echo $row['accountid']; ?>">
    Username
     Username must not contain any special characters
    <input type="text" id="username" name="username" class="username form-control" value="<?php echo $row['username']; ?>" placeholder="Enter Username">

//Here is my javascript function

Body:
As I mentioned above you should use class selector and also I slightly improved your validations

$('.password').keyup(function() {
  $("#submit").prop('disabled', checkStrength($(this).val()) === false);
});

$('.confirm_password').blur(function() {
  var arePasswordTheSame = $('.password').val() !== $(this).val();
  $('.popover-cpassword').toggleClass('hide', !arePasswordTheSame);
  $("#submit").prop('disabled', !arePasswordTheSame)
});

$('.username').blur(function() {
  var regex = /\`|\~|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\+|\=|\[|\{|\]|\}|\||\\|\'|\<|\,|\.|\>|\?|\/|\""|\;|\:|\s/;
  var isUserNameCorrect = $(this).val().match(regex);
  $('.popover-username').toggleClass('hide', !isUserNameCorrect);
  $(".submit").prop('disabled', !isUserNameCorrect);
  $('.sign-up').prop('disabled', !isUserNameCorrect);
})

$('.contact_number').blur(function() {
  var regex = /^[(9)][(\d+)]{9}$/;
  var isNumberCorrect = $(this).val().match(regex)
  $('.popover-cnumber').toggleClass('hide', !isNumberCorrect);
  $(".submit").prop('disabled', !isNumberCorrect);
});

Also you will need to add your current container to all class seelctors. For more info please reference API


问:
Java ExceptionInitializationError in static Block
I am trying to call the URL retrieving method inside the static block, the Instantiation of bean failed; nested exception is java.lang.ExceptionInInitializerError.

I am trying to get a WSDL url from the config file. this configuration data stored DB.

```<code>static
{
    URL url = null;
    WebServiceException e = null;
    try
{
    url = getVertexConfiguration();
    } catch (MalformedURLException ex) {
            e = new WebServiceException(ex);
        }
    }

private static URL getVertexConfiguration() throws MalformedURLException
    {
        try {
            configuration = configurationDAO.getByRefName("tax/vertex",
                    SecureSession.getUser().getDataDomain() != null ?
                            SecureSession.getUser().getDataDomain() : "app.cantata");
        } catch (B2BTransactionFailed b2BTransactionFailed) {

        }

        Map<String, DynamicAttribute> vertexTaxConfig = configuration.getConfigs();
        vertexWsdlUrl = vertexTaxConfig.get("vertexWsdlUrl").getValue().toString();

        return new URL(vertexWsdlUrl);
    }

}
</code>```

I am getting static block, the Instantiation of bean failed; nested exception is java.lang.ExceptionInInitializerError.

答: The root cause is that static block is the earliest step when setup as class level initialization which even ahead of constructor calling. That is to say your dependency in static block such as that configurationDAO has not initialized yet. You shouldn't use static for it. Instead, you should make it a normal Instance method.

Body:
I am trying to call the URL retrieving method inside the static block, the Instantiation of bean failed; nested exception is java.lang.ExceptionInInitializerError.

I am trying to get a WSDL url from the config file. this configuration data stored DB.

static
{
    URL url = null;
    WebServiceException e = null;
    try
{
    url = getVertexConfiguration();
    } catch (MalformedURLException ex) {
            e = new WebServiceException(ex);
        }
    }

private static URL getVertexConfiguration() throws MalformedURLException
    {
        try {
            configuration = configurationDAO.getByRefName("tax/vertex",
                    SecureSession.getUser().getDataDomain() != null ?
                            SecureSession.getUser().getDataDomain() : "app.cantata");
        } catch (B2BTransactionFailed b2BTransactionFailed) {

        }

        Map<String, DynamicAttribute> vertexTaxConfig = configuration.getConfigs();
        vertexWsdlUrl = vertexTaxConfig.get("vertexWsdlUrl").getValue().toString();

        return new URL(vertexWsdlUrl);
    }

}

I am getting static block, the Instantiation of bean failed; nested exception is java.lang.ExceptionInInitializerError.


问:
Regaining focus on Excel after executing VBA in PowerPoint
I am preparing an Excel file in which I run an UserForm aimed at updating PowerPoint Slides. The problem that I have is that at some point after pasting some pictures in the PowerPOint Slides I am calling for Open Dialog window to select a file to embed in the presentation. However excel is not on focus on the time and it starts flashing in the background so the use has to see it and activate it to open the dialog window.

I have tried using Workbook.activate, Select expression and nothing worked.

```<code>    Dim s As Integer
        For s = MyPresentation.Slides(9).Shapes.Count To 1 Step -1
            If MyPresentation.Slides(9).Shapes(s).Type = msoEmbeddedOLEObject Then
                MyPresentation.Slides(9).Shapes(s).Delete
            End If
        Next s

indexsheet.Activate

Dim Met2FactSheet As String
Dim HerFactSheet As String

MsgBox "Please choose the Metro2 Fact Sheet", vbQuestion, "Metro2 Fact Sheet selection"

Application.DisplayAlerts = False
    With Application.FileDialog(msoFileDialogFilePicker)
          If .Show <> -1 Then MsgBox "No file selected! Exiting script.": End
        Met2FactSheet = .SelectedItems(1)

    End With
</code>```

答:
My VBA editor is busted at the minute so I can't confirm anything, but try

AppActivate("Excel.Application")

or alternatively, try using
GetObject("Excel.Application")

to get a handle on the application and then attempt via a different method?

Body:
I am preparing an Excel file in which I run an UserForm aimed at updating PowerPoint Slides. The problem that I have is that at some point after pasting some pictures in the PowerPOint Slides I am calling for Open Dialog window to select a file to embed in the presentation. However excel is not on focus on the time and it starts flashing in the background so the use has to see it and activate it to open the dialog window.

I have tried using Workbook.activate, Select expression and nothing worked.

    Dim s As Integer
        For s = MyPresentation.Slides(9).Shapes.Count To 1 Step -1
            If MyPresentation.Slides(9).Shapes(s).Type = msoEmbeddedOLEObject Then
                MyPresentation.Slides(9).Shapes(s).Delete
            End If
        Next s

indexsheet.Activate

Dim Met2FactSheet As String
Dim HerFactSheet As String

MsgBox "Please choose the Metro2 Fact Sheet", vbQuestion, "Metro2 Fact Sheet selection"

Application.DisplayAlerts = False
    With Application.FileDialog(msoFileDialogFilePicker)
          If .Show <> -1 Then MsgBox "No file selected! Exiting script.": End
        Met2FactSheet = .SelectedItems(1)

    End With


答:
That exception is a relaying mechanism for an error which occurred while running a static initializer.  The exception should have a cause, which will describe the actual error.  Per your description, above, there look to be three layers of exception: Error reporting from bean initialization, the ExceptionInInitializer exception, then the cause of the ExceptionInInitializer exception.  The exception processing should display all three layers, but might not, which will make uncovering the base exception more difficult.

From the ExceptionInInitializer javaDoc:

```<code> * Signals that an unexpected exception has occurred in a static initializer.
 * An <code>ExceptionInInitializerError</code> is thrown to indicate that an
 * exception occurred during evaluation of a static initializer or the
 * initializer for a static variable.
</code>```

As a fall-back, you could put inside getVertexConfiguration a try-catch on Throwable, and have the catch block print out the stack:

```<code>private static URL getVertexConfiguration() throws MalformedURLException {
    try {
        // Code omitted
    } catch ( Throwable th ) {
        th.printStackTrace();
        return null;
    }
}
</code>```

Title: Java ExceptionInitializationError in static Block

Body:
That exception is a relaying mechanism for an error which occurred while running a static initializer.  The exception should have a cause, which will describe the actual error.  Per your description, above, there look to be three layers of exception: Error reporting from bean initialization, the ExceptionInInitializer exception, then the cause of the ExceptionInInitializer exception.  The exception processing should display all three layers, but might not, which will make uncovering the base exception more difficult.

From the ExceptionInInitializer javaDoc:

 * Signals that an unexpected exception has occurred in a static initializer.
 * An <code>ExceptionInInitializerError</code> is thrown to indicate that an
 * exception occurred during evaluation of a static initializer or the
 * initializer for a static variable.

As a fall-back, you could put inside getVertexConfiguration a try-catch on Throwable, and have the catch block print out the stack:

private static URL getVertexConfiguration() throws MalformedURLException {
    try {
        // Code omitted
    } catch ( Throwable th ) {
        th.printStackTrace();
        return null;
    }
}


问:
Bootstrap-Wizard: onPrevious not working with if index?
I am using a bootstrap wizard in one of my applications but i noticed when i try and use the index position of the tabs to achieve a certain goal it would only work with the next button, not the previous button. onPrevious works, just wont go into the if statement.

```<code>$('#rootwizard').bootstrapWizard({
        'tabClass': 'bwizard-steps',
        onTabClick: function(tab, navigation, index) {
            return false;
        },
        onNext: function(tab, navigation, index) {

            alert('this works');

            if (index === 1) {
                alert('this works');
            }

        },
        onPrevious: function(tab, navigation, index) {

            alert('this works');

            if (index === 2) {
                alert('this doesn't work');
            }
        }
    });
</code>```

My goal is specific with the 2nd tab previous button, but it simply wont work despite the code being exactly the same as the onNext witch works perfectly. Any ideas?

答:
if you have two tabs the index are 0 and 1 , not 1 and 2

index has the value of the tab where you are going to be, not the tab where you are

Body:
I am using a bootstrap wizard in one of my applications but i noticed when i try and use the index position of the tabs to achieve a certain goal it would only work with the next button, not the previous button. onPrevious works, just wont go into the if statement.

$('#rootwizard').bootstrapWizard({
        'tabClass': 'bwizard-steps',
        onTabClick: function(tab, navigation, index) {
            return false;
        },
        onNext: function(tab, navigation, index) {

            alert('this works');

            if (index === 1) {
                alert('this works');
            }

        },
        onPrevious: function(tab, navigation, index) {

            alert('this works');

            if (index === 2) {
                alert('this doesn't work');
            }
        }
    });

My goal is specific with the 2nd tab previous button, but it simply wont work despite the code being exactly the same as the onNext witch works perfectly. Any ideas?


问:
Why do these constraints seem to lag when animated?
I am animating my constraints using UIView.animate. drawerHeight is a constraint variable.

Here is the code:

```<code>drawerHeight?.constant = newHeight

UIView.animate(withDuration: 0.35, delay: 0, usingSpringWithDamping: 0.65, initialSpringVelocity: 2, options: .allowUserInteraction, animations: {
    self.superview?.layoutIfNeeded()
})
</code>```

Here is a video of what the issue looks like.

Looking at the bottom of the video, the bottom edge appears to lag behind. Why do these constraints seem to lag when animated?

This is a self-answered question. This post is to help people in the future discover what they did wrong, and how to quickly fix it.

答:
The issue was that the constraint was attached to a view in a deeper hierarchy than before. When using layoutIfNeeded(), it should be called on the superview of the view containing the constraints.

In my situation, I put the view with the drawerHeight constraint within another UIView, which made it deeper in the hierarchy.

I fixed the issue by doing

self.superview?.superview?.layoutIfNeeded() ,

instead of

self.superview?.layoutIfNeeded() .

Body:
I am animating my constraints using UIView.animate. drawerHeight is a constraint variable.

Here is the code:

drawerHeight?.constant = newHeight

UIView.animate(withDuration: 0.35, delay: 0, usingSpringWithDamping: 0.65, initialSpringVelocity: 2, options: .allowUserInteraction, animations: {
    self.superview?.layoutIfNeeded()
})

Here is a video of what the issue looks like.

Looking at the bottom of the video, the bottom edge appears to lag behind. Why do these constraints seem to lag when animated?

This is a self-answered question. This post is to help people in the future discover what they did wrong, and how to quickly fix it.


问:
A Web Component is the only technology to create framework-agnostic components. Or is there any alternative?
I have build a JavaScript toolkit in Angular which contains a lot of 'basic' components, like buttons and fields. For a new project, I am doing some research for a more framework-agnostic way to implement such components, so I can reuse my components in other JavaScript frameworks as well.

During my research I found just one alternative: web components, using custom elements. According to so many resources and blogs a web component is the best and only way to create a framework-agnostic component. How can I considering a new technology if there is just one? Or am I missing something?

答:
The Web Component API, as far as I know, is the only built in framework for Web Components.

There are plenty of other frameworks for making components but those normally come with lots of extras that have nothing to do with components.

I had a system I wrote years ago that was just for creating a component and nothing else. But it was very limited and I have since moved to Web Components for everything.

Writing a true, native Web Component allows you to reuse that code in any and all frameworks. I have some components that have been used, without change in Vanilla JS, AngularJS, Angular, VUE and React.

There are issues with a shadowDOM element and styling between projects but that is small compared to being able to reuse all of your components when your company insist on changing frameworks.


问:
How to fix "Cannot read property 'trim' of undefined" error in node
I'm implementing a simple WebAPI in Firebase cloud functions with express by TypeScript.
My code is following.

```<code>import * as functions from 'firebase-functions';
import * as express from 'express';

const app = express()

app.post('/', (req, res) => {
    var resText: string = "NotEmpty"
    const text: string = req.body.text

    if (isEmpty(text)) {
        resText = "Empty"
    }
    console.log("text: ", text)
    console.log("resText: ", resText)
    res.send("Echo " + resText)
})

exports.api = functions.https.onRequest(app)

const isEmpty = (str: string): boolean => {
    console.log("str: ", str, "+++")
    const trimedStr = str.trim()
    const result = (trimedStr === null || trimedStr === "")
    console.log("result: ", result)
    return result
}

</code>```

Build to transform typescript to javascript worked fine.
However, when I did POST method, following error occurred.

```<code>>  TypeError: Cannot read property 'trim' of undefined
>      at isEmpty (/Users/kenny/Test/firebase_functions/functions/lib/index.js:22:27)
>      at app.post (/Users/kenny/Test/firebase_functions/functions/lib/index.js:9:9)
>      at Layer.handle [as handle_request] (/Users/kenny/Test/firebase_functions/functions/node_modules/expr
ess/lib/router/layer.js:95:5)
>      at next (/Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/router/route.js:137:
13)
>      at Route.dispatch (/Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/router/rou
te.js:112:3)
>      at Layer.handle [as handle_request] (/Users/kenny/Test/firebase_functions/functions/node_modules/expr
ess/lib/router/layer.js:95:5)
>      at /Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/router/index.js:281:22
>      at Function.process_params (/Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/r
outer/index.js:335:12)
>      at next (/Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/router/index.js:275:
10)
>      at expressInit (/Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/middleware/in
it.js:40:5)

</code>```

How can I fix this error ?

答:
Your problem is that isEmpty is not prepared to receive things that are not a string.

Quick fix: set a default value

const isEmpty = (str=''): boolean => {
    // code...
}
```

<p><strong>Better solution</strong>: Validate your data.</p>

<p>While developing any API, you need to validate the entry data to your request. </p>

<blockquote>
  <p>You are working on an API endpoint to create a new user and you will require some data along with the request like firstname, lastname, age and birthdate for the user you are about to create. Obviously, passing Sally as value for age or 53 for birthdate won't get things rolling in the right direction. You really don't want bad data making its way through your application so what do you do? The answer is Data Validation.
  Reference. </p>
</blockquote>

<p>I'll make a quick example for this case using Joi:</p>

<pre class="lang-js prettyprint-override"><code>// code...

const schema = {
    text: Joi.string()
};

app.post('/', (req, res) => {
    //my code starts here
    const data = req.body;
    const {error, value} = Joi.validate(data, schema);

    if(error) {
        return res.status(400).json(error);
    }
    // ends here

    var resText: string = "NotEmpty"
    const text: string = req.body.text

    if (isEmpty(text)) {
        resText = "Empty"
    }
    console.log("text: ", text)
    console.log("resText: ", resText)
    res.send("Echo " + resText)
});

// code...
</code>```

Body:
I'm implementing a simple WebAPI in Firebase cloud functions with express by TypeScript.
My code is following.

import * as functions from 'firebase-functions';
import * as express from 'express';

const app = express()

app.post('/', (req, res) => {
    var resText: string = "NotEmpty"
    const text: string = req.body.text

    if (isEmpty(text)) {
        resText = "Empty"
    }
    console.log("text: ", text)
    console.log("resText: ", resText)
    res.send("Echo " + resText)
})

exports.api = functions.https.onRequest(app)

const isEmpty = (str: string): boolean => {
    console.log("str: ", str, "+++")
    const trimedStr = str.trim()
    const result = (trimedStr === null || trimedStr === "")
    console.log("result: ", result)
    return result
}

Build to transform typescript to javascript worked fine.
However, when I did POST method, following error occurred.

>  TypeError: Cannot read property 'trim' of undefined
>      at isEmpty (/Users/kenny/Test/firebase_functions/functions/lib/index.js:22:27)
>      at app.post (/Users/kenny/Test/firebase_functions/functions/lib/index.js:9:9)
>      at Layer.handle [as handle_request] (/Users/kenny/Test/firebase_functions/functions/node_modules/expr
ess/lib/router/layer.js:95:5)
>      at next (/Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/router/route.js:137:
13)
>      at Route.dispatch (/Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/router/rou
te.js:112:3)
>      at Layer.handle [as handle_request] (/Users/kenny/Test/firebase_functions/functions/node_modules/expr
ess/lib/router/layer.js:95:5)
>      at /Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/router/index.js:281:22
>      at Function.process_params (/Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/r
outer/index.js:335:12)
>      at next (/Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/router/index.js:275:
10)
>      at expressInit (/Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/middleware/in
it.js:40:5)

How can I fix this error ?

Body:
Your problem is that isEmpty is not prepared to receive things that are not a string.

Quick fix: set a default value

const isEmpty = (str=''): boolean => {
    // code...
}

Better solution: Validate your data.

While developing any API, you need to validate the entry data to your request.

You are working on an API endpoint to create a new user and you will require some data along with the request like firstname, lastname, age and birthdate for the user you are about to create. Obviously, passing Sally as value for age or 53 for birthdate won't get things rolling in the right direction. You really don't want bad data making its way through your application so what do you do? The answer is Data Validation.
  Reference.

I'll make a quick example for this case using Joi:

// code...

const schema = {
    text: Joi.string()
};

app.post('/', (req, res) => {
    //my code starts here
    const data = req.body;
    const {error, value} = Joi.validate(data, schema);

    if(error) {
        return res.status(400).json(error);
    }
    // ends here

    var resText: string = "NotEmpty"
    const text: string = req.body.text

    if (isEmpty(text)) {
        resText = "Empty"
    }
    console.log("text: ", text)
    console.log("resText: ", resText)
    res.send("Echo " + resText)
});

// code...


问:
Can I make browsers choose UTF-8 for viewing source code?
I put up some source code files for viewing on the web. The problem is, browsers tend to not understand that these files are in UTF-8, and I wonder if there's anything I can do about that. (I'm sure some browsers use UTF-8 per default, but Safari at least doesn't. I have to go into the View menu and choose the encoding manually to make it look right.)

My set of webpages is here, with several Python files and one C file: fgcode.avadeaux.net. I tried putting a charset="UTF-8" attribute in the a elements in the , but that doesn't seem to help. The Python files declare the charset in a comment on the top line, but the browser ignores that as well (which is no surprise, it's not a Python source code browser after all).

I don't have much control over the web server, it's run by my ISP and I just put the files there. But I'd still be interested to know if this problem has a web server configuration solution.

Solution: solved, as per links provided, by adding an .htaccess file with the following content:

```<code>AddDefaultCharset UTF-8
AddCharset UTF-8 .py
AddCharset UTF-8 .c
</code>```

Only the first line wasn't enough in my case.

答:
If you are allowed to place a .htaccess file in your content directory, you might be able to specify a charset there.

YMMV depending on which server software they run, and how permissive the config is.

See:

How to change the default encoding to UTF-8 for Apache?

htaccess UTF-8 encoding for .html, .css, .js - Whats the best way?

Body:
I put up some source code files for viewing on the web. The problem is, browsers tend to not understand that these files are in UTF-8, and I wonder if there's anything I can do about that. (I'm sure some browsers use UTF-8 per default, but Safari at least doesn't. I have to go into the View menu and choose the encoding manually to make it look right.)

My set of webpages is here, with several Python files and one C file: fgcode.avadeaux.net. I tried putting a charset="UTF-8" attribute in the a elements in the , but that doesn't seem to help. The Python files declare the charset in a comment on the top line, but the browser ignores that as well (which is no surprise, it's not a Python source code browser after all).

I don't have much control over the web server, it's run by my ISP and I just put the files there. But I'd still be interested to know if this problem has a web server configuration solution.

Solution: solved, as per links provided, by adding an .htaccess file with the following content:

AddDefaultCharset UTF-8
AddCharset UTF-8 .py
AddCharset UTF-8 .c

Only the first line wasn't enough in my case.


问:
How do you debug without an interactive console
As a self-taught programmer, I learned to debug using an interactive console that kept all of my variables in memory when I build /run the script.  However, I noticed the overwhelming trend for debugging in IDEs (and, I suppose CLI + Editor solutions, for that matter) is to build your script in one place and provide a separate console "sandbox" type area that only keeps variables if you copy/paste your code.

How do you debug without an interactive console?  Can anyone list a few debugging steps that could help me be a better programmer / debugger?

Currently, this is a very simplified version of what I do:

Write some pseudocode (sometimes)

Write some code in an editor that should work

run / build the script

Check stdout for errors

If no errors, then 7.

If errors, then back to 2 after fixing the offending code.

Type variable names into console to verify that they look like I
anticipated.

Rinse and Repeat until it works as I intended.

答: Use print statements in between the areas of problem code... otherwise, just download a good IDE</p>


问:
How do you execute python code in a website
I am creating a website and want to integrate some python code which will be executed and return some information. Here is the code:

```<code>import requests
from bs4 import BeautifulSoup

def trade_spider(max_pages):
    page = 1
    while(page <= max_pages):
            search = 'Ipad'
            url = 'https://www.ebay.com/sch/i.html?_from=R40&_nkw=' + search + '&_sacat=0&_pgn=' + str(page)
            src = requests.get(url)
            text = src.text
            soup = BeautifulSoup(text, features="html.parser")
            for link in soup.findAll('a', {'class': 's-item__link'}):
                    href = link.get('href')
                    title = link.string
                    print(href)
                    if(title == None):
                        title = "Sorry the title was unavailable however you can check the price."
                    print(title)
                    price = get_item_price(href)
                    print(price + '\n')
            page += 1

def get_item_price(item_url):
    src = requests.get(item_url)
    text = src.text
    soup = BeautifulSoup(text, features="html.parser")
    for item_price in soup.findAll('span', {'class': 'notranslate'}):
            price = item_price.string
            return price

trade_spider(1)
</code>```

Now i have tried youtube and found a working solution however not for my code. i think this might be because of the modules i am using. So does anyone have a way to execute this code and return the output?

答:
you should use python web servers like apache tornado e.g.

but I advice you to search about django to learn better about web development by python.

Body:
I am creating a website and want to integrate some python code which will be executed and return some information. Here is the code:

import requests
from bs4 import BeautifulSoup

def trade_spider(max_pages):
    page = 1
    while(page <= max_pages):
            search = 'Ipad'
            url = 'https://www.ebay.com/sch/i.html?_from=R40&_nkw=' + search + '&_sacat=0&_pgn=' + str(page)
            src = requests.get(url)
            text = src.text
            soup = BeautifulSoup(text, features="html.parser")
            for link in soup.findAll('a', {'class': 's-item__link'}):
                    href = link.get('href')
                    title = link.string
                    print(href)
                    if(title == None):
                        title = "Sorry the title was unavailable however you can check the price."
                    print(title)
                    price = get_item_price(href)
                    print(price + '\n')
            page += 1

def get_item_price(item_url):
    src = requests.get(item_url)
    text = src.text
    soup = BeautifulSoup(text, features="html.parser")
    for item_price in soup.findAll('span', {'class': 'notranslate'}):
            price = item_price.string
            return price

trade_spider(1)

Now i have tried youtube and found a working solution however not for my code. i think this might be because of the modules i am using. So does anyone have a way to execute this code and return the output?


答:
You need a  element in the document being served. In  you will also need: <meta charset="utf-8">.

If the document you're linking to does not have this, you may need to set up a proxy to wrap it. Browsers understand HTML. Your .py files are just text, so they contain not instructions the browser will understand.

Title: Can I make browsers choose UTF-8 for viewing source code?

Body:
You need a <head> element in the document being served. In <head> you will also need: <meta charset="utf-8">.

If the document you're linking to does not have this, you may need to set up a proxy to wrap it. Browsers understand HTML. Your .py files are just text, so they contain not instructions the browser will understand.


问:
Is this possible for create slave with K8S plugin without setting Jenkins on cluster?
I'm trying to configure K8s plugin on Jenkins to automatically create slave agent whenever a job is triggered. However, as far as I researched, it is only possible to do so providing that Jenkins server is running on k8s cluster. Is there a way to configure k8s plugin on Jenkins server which is running on Openstack server?

I've a Jenkins server and also configured k8s plugin on it. Everytime I build a new job, a new pod for slave agent is created but not possible to be started. When i tried command kubectl logs <pod-name> I received the following error:

```<code>Error from server: Get https://XX.XX.XX.XX:10250/containerLogs/jenkins/slave-tester-4c4wb/jnlp: net/http: TLS handshake timeout
</code>```

答:
This is definitely possible, there is a good amount of documentation available here: https://github.com/jenkinsci/kubernetes-plugin#kubernetes-cloud-configuration

The important part is: "When running the Jenkins master outside of Kubernetes you will need to set the credential to secret text. The value of the credential will be the token of the service account you created for Jenkins in the cluster the agents will run on."

Body:
I'm trying to configure K8s plugin on Jenkins to automatically create slave agent whenever a job is triggered. However, as far as I researched, it is only possible to do so providing that Jenkins server is running on k8s cluster. Is there a way to configure k8s plugin on Jenkins server which is running on Openstack server?

I've a Jenkins server and also configured k8s plugin on it. Everytime I build a new job, a new pod for slave agent is created but not possible to be started. When i tried command kubectl logs <pod-name> I received the following error:

Error from server: Get https://XX.XX.XX.XX:10250/containerLogs/jenkins/slave-tester-4c4wb/jnlp: net/http: TLS handshake timeout


答:
An option would be to group by 'Month' and use one of the ranking functions (dense_rank, row_number(), min_rank - based on the needs) to rank the 'Discharge' column

```<code>library(dplyr)
df1 %>%
    group_by(Month) %>%
    mutate(Rank = dense_rank(Discharge))
</code>```

Title: How to rearrange daily stream discharge data into monthly format and rank the discharge values for each month using R

Body:
I have a data set of daily stream discharge values from a gauging station for approximately 50 years. The data is arranged into three columns, namely, "date", "month", "discharge".(Sample data shown here)

`

 Date<- as.Date(c('1938-10-01','1954-10-27', '1967-06-16','1943-01-01','1945-01-14','1945-03-14','1954-05-04','1960-04-23','1960-05-09','1962-01-18','1968-12-19','1972-01-15','1977-08-15','1981-04-11','1986-06-20','1989-01-20','1992-03-29'))

> Months<- c('Oct','Oct','Jun','Jan','Jan','Mar','May','Apr','May','Jan','Dec','Jan','Aug','Apr','Jun','Jan','Mar')
> Dis<-c('1000','1200','400','255','450','215','360','120','145','1204','752','635','1456','154','154','1204','450')
> Sampledata<-data.frame("Date"=Date,"Months"=Months,"Disch"=Dis)
> print(Sampledata)
         Date Months Disch
1  1938-10-01    Oct  1000
2  1954-10-27    Oct  1200
3  1967-06-16    Jun   400
4  1943-01-01    Jan   255
5  1945-01-14    Jan   450
6  1945-03-14    Mar   215
7  1954-05-04    May   360
8  1960-04-23    Apr   120
9  1960-05-09    May   145
10 1962-01-18    Jan  1204
11 1968-12-19    Dec   752
12 1972-01-15    Jan   635
13 1977-08-15    Aug  1456
14 1981-04-11    Apr   154
15 1986-06-20    Jun   154
16 1989-01-20    Jan  1204
17 1992-03-29    Mar   450

I want to calculate ranks for each month separately for all the years. For example: Calculate rank in ascending order for the month of January for 50 years. With the same rank value assigned to a duplicate discharge value. Desired output shown here:

>         Date Month Disch Rank
1 1943-01-01   Jan   255    1
2 1945-01-14   Jan   450    2
3 1962-01-18   Jan  1204    4
4 1972-01-15   Jan   635    3
5 1989-01-20   Jan  1204    4
>         Date Month Disch Rank
1 1945-03-14   Mar   215    1
2 1992-03-29   Mar   450    2
3 2001-03-19   Mar   450    2

Body:
An option would be to group by 'Month' and use one of the ranking functions (dense_rank, row_number(), min_rank - based on the needs) to rank the 'Discharge' column

library(dplyr)
df1 %>%
    group_by(Month) %>%
    mutate(Rank = dense_rank(Discharge))


问:
How I can use Java Regex for Turkish characters to UTF-8
I'm trying to do a regex operations in Java. But when I search in the Turkish text , I'm having trouble . For example;

```<code>Search Text = "Ahmet Yıldırım" or "Esin AYDEMİR"

//The e-mail stated in part(Ex: yildirim@example.com) , trying to look in name.
Regex Strings = "yildirim" or  "aydemir".
</code>```

Searched text is dynamically changing.Therefore , how can I solve this by using java regex pattern. Or How do I convert Turkish characters(Ex: AYDEMİR convert to AYDEMIR  or Yıldırım -> Yildirim).

Sorry, about my grammer mistakes!...

答:
I am using this pattern.

```<code>public static boolean isAlphaNumericWithWhiteSpace(String text) {
        return text != null && text.matches("^[\\p{L}\\p{N}ın\\s]*$");
    }
</code>```

\p{L} matches a single code point in the category "letter".

\p{N} matches any kind of numeric character in any script.

Body:
I'm trying to do a regex operations in Java. But when I search in the Turkish text , I'm having trouble . For example;

Search Text = "Ahmet Yıldırım" or "Esin AYDEMİR"

//The e-mail stated in part(Ex: yildirim@example.com) , trying to look in name.
Regex Strings = "yildirim" or  "aydemir".

Searched text is dynamically changing.Therefore , how can I solve this by using java regex pattern. Or How do I convert Turkish characters(Ex: AYDEMİR convert to AYDEMIR  or Yıldırım -> Yildirim).

Sorry, about my grammer mistakes!...

Body:
I am using this pattern.

public static boolean isAlphaNumericWithWhiteSpace(String text) {
        return text != null && text.matches("^[\\p{L}\\p{N}ın\\s]*$");
    }

\p{L} matches a single code point in the category "letter".

\p{N} matches any kind of numeric character in any script.


答:
This approach would work only if your php code generates one

Per each account, putting all of them in the html.

Title: Javascript function only works on the first row only inside my modal

Body:
I am using a javascript function for input verification where it is being used inside a modal. I click the edit button at the first row, javascript functions work well. But when I click on the edit button on the second row, and succeeding rows, it doesn't function.

I am not really sure if the problem is the data inside the modal or the data outside the modal

I tried adding a class name in the input fields and changing the calling function in javascript from "#name" to ".name" but it did not work.

I also tried the shown.bs function

// Here is my code for the table (partial)

    <?php
    if ($result = mysqli_query($conn, $sql_accounts)) {
    while ($row=mysqli_fetch_array($result)) {
    ?>

    <form action="update.php" method="POST">

    <?php echo $row["username"]; ?>

    <?php echo $row["firstname"]; ?>
     .....

    <?php echo $row["status"]; ?>

    <?php
    if ($row["status"] == "Deactivated") {
    ?>
    <a href="update.php?activate=<?php echo $row['accountid']; ?>" class="btn btn-info"> Activate
    <?php
    } elseif ($row["status"] == "Active") {
    ?>
    <a href="update.php?deactivate=<?php echo $row['accountid']; ?>" class="btn btn-warning"> Deactivate
    <?php
    } ?>
    <a href="#edit<?php echo $row['accountid']; ?>" data-toggle="modal" class="btn btn-success" data-toggle="modal">Edit

// Here is my code for the modal (partial)

    <div id="edit<?php echo $row['accountid']; ?>" class="modal fade" role="dialog">

    <button type="button" class="close" data-dismiss="modal">×</button>

Edit Account

    <form method="POST" action="editaccount.php">

    <input type="hidden" name="edit_item_id" value="<?php echo $row['accountid']; ?>">
    Username
     Username must not contain any special characters
    <input type="text" id="username" name="username" class="username form-control" value="<?php echo $row['username']; ?>" placeholder="Enter Username">

//Here is my javascript function


问:
What are the options for the -Encoding parameter in the Import-DbaCsv tool?
I can't figure out what the Import-DbaCsv tool is expecting for the -Encoding parameter.

The docs aren't helpful - https://docs.dbatools.io/#Import-DbaCsv

I've tried UTF-8, UTF8, and UTF in upper case, lower case, with quotes, and without quotes.

I always get and error message like this:

Cannot convert the "UTF-8" value of type "System.String" to type "System.Text.Encoding"

答: Sorry, that was my bad. I've updated Import-DbaCsv a ton and this will be addressed when dbatools 1.0 comes out in 20 days. In addition to being able to pass plain-text encoding, Encoding will autocomplete and actually work when we release. If you'd like it earlier, check out our prerelease branch in GitHub.


问:
ClassNotFoundException thrown when trying to find jdbc driver using Vaadin Framework
I am making a web app with java, using the Vaadin framework. I have tried to implement jdbc, but gotten an error. I have downloaded the latest jdbc jar.
The code throws a ClassNotFound exception.

I have tried to add it to eclipse build path, and I have tried to put it into WEB-INF/lib (C:\Users\desktopname\Documents\Java-ee\target\my-starter-project-1.0-SNAPSHOT\WEB-INF\lib
I have also tried to put it into

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class DBConnect {

    private Connection con;
    private Statement st;
    private ResultSet rs;

    public DBConnect() {
        try {
            //com.mysql.jdbc.Driver
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            con= DriverManager.getConnection("jdbc:mysql://remotemysql.com:3306/Z3EoHAi3pW", "username", "password");
            st = con.createStatement();
        } catch (Exception e) {
            System.out.println("Error:" + e);
        }
    }

}
```

Error:java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

答:
add mysql JDBC driver jar file to your classpath. Then you will be fine. You can download here. If you are using maven. use below:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.6</version>
</dependency>

```

Body:
I am making a web app with java, using the Vaadin framework. I have tried to implement jdbc, but gotten an error. I have downloaded the latest jdbc jar.
The code throws a ClassNotFound exception.

I have tried to add it to eclipse build path, and I have tried to put it into WEB-INF/lib (C:\Users\desktopname\Documents\Java-ee\target\my-starter-project-1.0-SNAPSHOT\WEB-INF\lib
I have also tried to put it into

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class DBConnect {

    private Connection con;
    private Statement st;
    private ResultSet rs;

    public DBConnect() {
        try {
            //com.mysql.jdbc.Driver
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            con= DriverManager.getConnection("jdbc:mysql://remotemysql.com:3306/Z3EoHAi3pW", "username", "password");
            st = con.createStatement();
        } catch (Exception e) {
            System.out.println("Error:" + e);
        }
    }

}

Error:java.lang.ClassNotFoundException: com.mysql.jdbc.Driver


问:
google smtp is not working on deployment but it works on local server
google smtp works fine on local server but after deployment it gives me that error

exception: "Swift_TransportException" file:
  "/home/sellective/public_html/sellective/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/StreamBuffer.php"
  line: 269 message: "Connection could not be established with host
  smtp.googlemail.com"

my credentials are right .
I've tried another account , another port and another encryption method also not working.

答:
I stacked with similar problem few days ago. But I used PHPMailer to get gmail SMTP server connection. Maybe, your server belongs to goDaddy domains. PHPMailer wiki say this:

Popular US hosting provider GoDaddy imposes very strict (to the point
  of becoming almost useless) constraints on sending an email. They
  block outbound SMTP to ports 25, 465 and 587 to all servers except
  their own.

So, probably, you can't use google SMTP from your present server.

Use WhoIs services to check who is Registrar of your hosting.


问:
Gaps in a line while trying to draw them with a mouse problem
I have written a program to draw a sin function in a way it is not easy to explain, but really easy to see it, so this is the whole

```<code>import pygame
import math
import fractions

window = pygame.display.set_mode((0, 0))#, pygame.FULLSCREEN)
pygame.font.init()
running = True
w, h = pygame.display.get_surface().get_size()
myfont = pygame.font.SysFont("monospace", 12)
myfont2 = pygame.font.SysFont("monospace", 30)

white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
wCol = (100, 100, 100)
yellow = (0, 0, 255)

#temp
last = [0, 0]
lastQ = 0
q = 0

unit = 50
radius = 100
xa = int(w/3)
ya1 = 0
ya2 = int(h)
xb1 = 0
xb2 = int(w)
yb = int(h/2)
xc = int(xa - radius)
yc = int(yb)
subtraction = 2
rotCount = 0
points = []

def check4points(angleC, sinC):
    isInArr = False
    for i in points:
        if i[0] == angleC and i[1] == sinC:
            isInArr = True
        else:
            isInArr = False
    return(isInArr)

def draw():
    global points
    window.fill(white)
    #axis and units
    pygame.draw.line(window, black, (xa, ya1), (xa, ya2), 2) # OY
    pygame.draw.line(window, black, (xb1, yb), (xb2, yb), 2) # OX
    #x units
    deltaU = 0
    for i in range(xa, w, 50):
        pygame.draw.line(window, black, (i, (yb - 5)), (i, (yb + 5)), 1)
        text = myfont.render(str(fractions.Fraction(deltaU).limit_denominator()) + "PI", 1, black)
        window.blit(text, (i - 15, yb + 5))
        deltaU += 1/6
    deltaU = 0
    for i in range(xa, 0, -50):
        pygame.draw.line(window, black, (i, (yb - 5)), (i, (yb + 5)), 1)
        text = myfont.render(str(fractions.Fraction(deltaU).limit_denominator()) + "PI", 1, black)
        window.blit(text, ((i) - 15, yb + 5))
        deltaU -= 1/6
    #y units
    deltaU = 0
    for i in range(yb, h, 50):
        pygame.draw.line(window, black, ((xa - 5), i), ((xa + 5), i), 1)
        text = myfont.render(str(deltaU), 1, black)
        window.blit(text, (xa + 10, i - 10))
        deltaU -= 0.5
    deltaU = 0
    for i in range(yb, 0, -50):
        pygame.draw.line(window, black, ((xa - 5), i), ((xa + 5), i), 1)
        text = myfont.render(str(deltaU), 1, black)
        window.blit(text, (xa + 10, i - 10))
        deltaU += 0.5
    text1 = myfont2.render("Kąt: " + str(angle), 2, black)
    text2 = myfont2.render("Sinus kąta: " + str(sinFinal), 2, black)
    text3 = myfont2.render("R - Reset", 2, black)
    window.blit(text1, (50, 100))
    window.blit(text2, (50, 130))
    window.blit(text3, (w*0.9, h*0.9))

    #circle thingy
    pygame.draw.circle(window, black, (xc, yc), radius, 2)
    pygame.draw.line(window, wCol, (xa - (2*unit), yb), satelliteCenter, 3)
    #pygame.draw.line(window, wCol, (mouse_xPos, mouse_yPos), (mouse_xPos, yb), 2)
    #pygame.draw.line(window, wCol, (mouse_xPos, mouse_yPos), (xa, mouse_yPos), 2)

    #point/sin graph
    pygame.draw.line(window, yellow, satelliteCenter, (satelliteCenter[0], yb), 2)
    pygame.draw.line(window, wCol, satelliteCenter, (w, satelliteCenter[1]), 2)
    pygame.draw.line(window, wCol, (0, satelliteCenter[1]), satelliteCenter, 2)
    pygame.draw.circle(window, red, satelliteCenter, 6)

    sinC = int(yb - (sinFinal * 100))
    angleC = (int(angle*(5/9)*3) + xa)

    point = [angleC, sinC]

    if check4points(angleC, sinC) == False:
        points.append(point)

    for i in range(len(points) - 1):
        pygame.draw.circle(window, red, (points[i][0], points[i][1]), 6, 0)

    pygame.draw.line(window, yellow, (angleC, sinC), (angleC, yb), 2)

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
            quit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                running = False
                quit()
            if event.key == pygame.K_LEFT:
                rotCount -= 1
            if event.key == pygame.K_RIGHT:
                rotCount += 1
            if event.key == pygame.K_r:
                points = []
                rotCount = 0

    mouse_xPos = pygame.mouse.get_pos()[0]
    mouse_yPos = pygame.mouse.get_pos()[1]

    satelliteCenter = (xc+radius, yb)
    vector = (mouse_xPos-xc, mouse_yPos-yb)
    distance = (vector[0]**2 + vector[1]**2)**0.5

    if distance > 0:
        scalar = radius/distance
        satelliteCenter = (int(round(xc + vector[0]*scalar)),
                           int(round(yb + vector[1]*scalar)) )

    if q == 1 and lastQ == 4:
        rotCount += 1
    elif q == 4 and lastQ == 1:
        rotCount -= 1

    lastQ = q

    last = satelliteCenter

    xrel = (mouse_xPos - xa)/50
    yrel = -(mouse_yPos - yb)/50
    xcircle = -2

    x = xrel - xcircle
    y = yrel
    hypotenuse = math.sqrt(x**2 + y**2)

    sin = y/hypotenuse
    angle = math.degrees(math.asin(sin))
    if x >= 0 and y > 0:
        angle = angle + (rotCount*360)
        q = 1
    elif x > 0 and y <= 0:
        angle = angle + 360 + (rotCount*360)
        q = 4
    elif x <= 0 and y < 0:
        angle = 180 - angle + (rotCount*360)
        q = 3
    elif x < 0 and y >= 0:
        angle = 180 - angle + (rotCount*360)
        q = 2

    sinFinal = math.sin(math.radians(angle))

    draw()

    pygame.display.flip()

</code>```

I have tried to subtract x coordinate of last drawn point and x coordinate of currently drawn one and check if it is greater than a given number (eg. 2 pixels). It seems to fail and is really non-efficient

These are the lines drawing the points:

```<code>
    sinC = int(yb - (sinFinal * 100))
    angleC = (int(angle*(5/9)*3) + xa)

    point = [angleC, sinC]

    if check4points(angleC, sinC) == False:
        points.append(point)

    for i in range(len(points) - 1):
        pygame.draw.circle(window, red, (points[i][0], points[i][1]), 6, 0)

    pygame.draw.line(window, yellow, (angleC, sinC), (angleC, yb), 2)
</code>```

If you could, please, tell me how I could make a perception of a smooth line.
Thanks in advance :)

BTW Don't judge me for my spaghetti code, I am just a beginner :D

答:
Use round instead of int:

sinC   = round(yb - (sinFinal * 100))
angleC = round(angle*(5/9)*3 + xa)
```

<p>To find existing points in the list (<code>points</code>) it is sufficient to find <code>any</code> point with the same <em>x</em> coordinate:</p>

<pre class="lang-py prettyprint-override"><code>any([x for x in points if x==point[0]])
</code>```

Sort (sorted) the list of points, after a new point was added:

point = [angleC, sinC]
if not any([x for x in points if x==point[0]]):
    points.append(point)
    points = sorted(points, key = lambda p : p[0])
```

<p>When the curve is drawn, then calculate the <em>x</em>-distance of a point to its successor and predecessor:</p>

<pre class="lang-py prettyprint-override"><code>dist_p = 0 if i==0 else points[i][0]-points[i-1][0]
dist_s = 0 if i>len(points)-2 else points[i+1][0]-points[i][0]
</code>```

Draw a point, when the distance to the successor and predecessor is acceeded by a certain threshold and draw a line else:

sinC   = round(yb - (sinFinal * 100))
angleC = round(angle*(5/9)*3 + xa)

point = [angleC, sinC]
if not any([x for x in points if x==point[0]]):
    points.append(point)
    points = sorted(points, key = lambda p : p[0])

threshold = 10
for i in range(len(points)):
    dist_p = 0 if i==0 else points[i][0]-points[i-1][0]
    dist_s = 0 if i>len(points)-2 else points[i+1][0]-points[i][0]
    if dist_p > threshold and dist_s > threshold:
        pygame.draw.circle(window, red, points[i], 6, 0)
    elif 0 < dist_p < threshold:
        pygame.draw.line(window, red, points[i-1], points[i], 2)
```

Body:
I have written a program to draw a sin function in a way it is not easy to explain, but really easy to see it, so this is the whole

import pygame
import math
import fractions

window = pygame.display.set_mode((0, 0))#, pygame.FULLSCREEN)
pygame.font.init()
running = True
w, h = pygame.display.get_surface().get_size()
myfont = pygame.font.SysFont("monospace", 12)
myfont2 = pygame.font.SysFont("monospace", 30)

white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
wCol = (100, 100, 100)
yellow = (0, 0, 255)

#temp
last = [0, 0]
lastQ = 0
q = 0

unit = 50
radius = 100
xa = int(w/3)
ya1 = 0
ya2 = int(h)
xb1 = 0
xb2 = int(w)
yb = int(h/2)
xc = int(xa - radius)
yc = int(yb)
subtraction = 2
rotCount = 0
points = []

def check4points(angleC, sinC):
    isInArr = False
    for i in points:
        if i[0] == angleC and i[1] == sinC:
            isInArr = True
        else:
            isInArr = False
    return(isInArr)

def draw():
    global points
    window.fill(white)
    #axis and units
    pygame.draw.line(window, black, (xa, ya1), (xa, ya2), 2) # OY
    pygame.draw.line(window, black, (xb1, yb), (xb2, yb), 2) # OX
    #x units
    deltaU = 0
    for i in range(xa, w, 50):
        pygame.draw.line(window, black, (i, (yb - 5)), (i, (yb + 5)), 1)
        text = myfont.render(str(fractions.Fraction(deltaU).limit_denominator()) + "PI", 1, black)
        window.blit(text, (i - 15, yb + 5))
        deltaU += 1/6
    deltaU = 0
    for i in range(xa, 0, -50):
        pygame.draw.line(window, black, (i, (yb - 5)), (i, (yb + 5)), 1)
        text = myfont.render(str(fractions.Fraction(deltaU).limit_denominator()) + "PI", 1, black)
        window.blit(text, ((i) - 15, yb + 5))
        deltaU -= 1/6
    #y units
    deltaU = 0
    for i in range(yb, h, 50):
        pygame.draw.line(window, black, ((xa - 5), i), ((xa + 5), i), 1)
        text = myfont.render(str(deltaU), 1, black)
        window.blit(text, (xa + 10, i - 10))
        deltaU -= 0.5
    deltaU = 0
    for i in range(yb, 0, -50):
        pygame.draw.line(window, black, ((xa - 5), i), ((xa + 5), i), 1)
        text = myfont.render(str(deltaU), 1, black)
        window.blit(text, (xa + 10, i - 10))
        deltaU += 0.5
    text1 = myfont2.render("Kąt: " + str(angle), 2, black)
    text2 = myfont2.render("Sinus kąta: " + str(sinFinal), 2, black)
    text3 = myfont2.render("R - Reset", 2, black)
    window.blit(text1, (50, 100))
    window.blit(text2, (50, 130))
    window.blit(text3, (w*0.9, h*0.9))

    #circle thingy
    pygame.draw.circle(window, black, (xc, yc), radius, 2)
    pygame.draw.line(window, wCol, (xa - (2*unit), yb), satelliteCenter, 3)
    #pygame.draw.line(window, wCol, (mouse_xPos, mouse_yPos), (mouse_xPos, yb), 2)
    #pygame.draw.line(window, wCol, (mouse_xPos, mouse_yPos), (xa, mouse_yPos), 2)

    #point/sin graph
    pygame.draw.line(window, yellow, satelliteCenter, (satelliteCenter[0], yb), 2)
    pygame.draw.line(window, wCol, satelliteCenter, (w, satelliteCenter[1]), 2)
    pygame.draw.line(window, wCol, (0, satelliteCenter[1]), satelliteCenter, 2)
    pygame.draw.circle(window, red, satelliteCenter, 6)

    sinC = int(yb - (sinFinal * 100))
    angleC = (int(angle*(5/9)*3) + xa)

    point = [angleC, sinC]

    if check4points(angleC, sinC) == False:
        points.append(point)

    for i in range(len(points) - 1):
        pygame.draw.circle(window, red, (points[i][0], points[i][1]), 6, 0)

    pygame.draw.line(window, yellow, (angleC, sinC), (angleC, yb), 2)

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
            quit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                running = False
                quit()
            if event.key == pygame.K_LEFT:
                rotCount -= 1
            if event.key == pygame.K_RIGHT:
                rotCount += 1
            if event.key == pygame.K_r:
                points = []
                rotCount = 0

    mouse_xPos = pygame.mouse.get_pos()[0]
    mouse_yPos = pygame.mouse.get_pos()[1]

    satelliteCenter = (xc+radius, yb)
    vector = (mouse_xPos-xc, mouse_yPos-yb)
    distance = (vector[0]**2 + vector[1]**2)**0.5

    if distance > 0:
        scalar = radius/distance
        satelliteCenter = (int(round(xc + vector[0]*scalar)),
                           int(round(yb + vector[1]*scalar)) )

    if q == 1 and lastQ == 4:
        rotCount += 1
    elif q == 4 and lastQ == 1:
        rotCount -= 1

    lastQ = q

    last = satelliteCenter

    xrel = (mouse_xPos - xa)/50
    yrel = -(mouse_yPos - yb)/50
    xcircle = -2

    x = xrel - xcircle
    y = yrel
    hypotenuse = math.sqrt(x**2 + y**2)

    sin = y/hypotenuse
    angle = math.degrees(math.asin(sin))
    if x >= 0 and y > 0:
        angle = angle + (rotCount*360)
        q = 1
    elif x > 0 and y <= 0:
        angle = angle + 360 + (rotCount*360)
        q = 4
    elif x <= 0 and y < 0:
        angle = 180 - angle + (rotCount*360)
        q = 3
    elif x < 0 and y >= 0:
        angle = 180 - angle + (rotCount*360)
        q = 2

    sinFinal = math.sin(math.radians(angle))

    draw()

    pygame.display.flip()

I have tried to subtract x coordinate of last drawn point and x coordinate of currently drawn one and check if it is greater than a given number (eg. 2 pixels). It seems to fail and is really non-efficient

These are the lines drawing the points:

    sinC = int(yb - (sinFinal * 100))
    angleC = (int(angle*(5/9)*3) + xa)

    point = [angleC, sinC]

    if check4points(angleC, sinC) == False:
        points.append(point)

    for i in range(len(points) - 1):
        pygame.draw.circle(window, red, (points[i][0], points[i][1]), 6, 0)

    pygame.draw.line(window, yellow, (angleC, sinC), (angleC, yb), 2)

If you could, please, tell me how I could make a perception of a smooth line.
Thanks in advance :)

BTW Don't judge me for my spaghetti code, I am just a beginner :D

Body:
Use round instead of int:

sinC   = round(yb - (sinFinal * 100))
angleC = round(angle*(5/9)*3 + xa)

To find existing points in the list (points) it is sufficient to find any point with the same x coordinate:

any([x for x in points if x==point[0]])

Sort (sorted) the list of points, after a new point was added:

point = [angleC, sinC]
if not any([x for x in points if x==point[0]]):
    points.append(point)
    points = sorted(points, key = lambda p : p[0])

When the curve is drawn, then calculate the x-distance of a point to its successor and predecessor:

dist_p = 0 if i==0 else points[i][0]-points[i-1][0]
dist_s = 0 if i>len(points)-2 else points[i+1][0]-points[i][0]

Draw a point, when the distance to the successor and predecessor is acceeded by a certain threshold and draw a line else:

sinC   = round(yb - (sinFinal * 100))
angleC = round(angle*(5/9)*3 + xa)

point = [angleC, sinC]
if not any([x for x in points if x==point[0]]):
    points.append(point)
    points = sorted(points, key = lambda p : p[0])

threshold = 10
for i in range(len(points)):
    dist_p = 0 if i==0 else points[i][0]-points[i-1][0]
    dist_s = 0 if i>len(points)-2 else points[i+1][0]-points[i][0]
    if dist_p > threshold and dist_s > threshold:
        pygame.draw.circle(window, red, points[i], 6, 0)
    elif 0 < dist_p < threshold:
        pygame.draw.line(window, red, points[i-1], points[i], 2)


问:
onClick not invoked when clicking on sidebar
In my main container the layout has this code

```<code>import React, { Component } from 'react';
import Header from '../../components/Navigation/Header/Header';
import SideBar from '../../components/Navigation/SideBar/SideBar';

class Layout extends Component {
    state = {
        showSideBar: true
    }

    sideBarToggleHandler = () => {
        console.log("test");
    }

    render() {

        return (
            <div>
                <Header />
                <div>
                    <SideBar onClick={this.sideBarToggleHandler}/>
                    <main id="main">
                        {this.props.children}
                    </main>
                </div>
            </div>
        )
    }
}

export default Layout;
</code>```

Whenever I click on any element in the side bar I want to console log test

For some reason this is not happening however if I move the onClick method to the header for example or to main it works fine

This is my sidebar:

```<code>import React from 'react';
import classes from './SideBar.module.scss';
import Logo from '../Logo/Logo'
import NavigationItems from './NavigationItems/NavigationItems'
const sideBar = (props) => {

    }
    return (
        <div className={Classes.SideBar}>
            <Logo />
            <nav>
                <NavigationItems />
            </nav>
        </div>
    );
};

export default sideBar;
</code>```

and this is my navigation items:

```<code>import React from 'react';
import classes from './NavigationItems.module.scss';
import Aux from '../../../../hoc/Aux';
import CollapseIcon from '../../../../assets/Images/Icons/collapse.svg'

import { library } from '@fortawesome/fontawesome-svg-core';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faHome } from '@fortawesome/free-solid-svg-icons';
import { faFileAlt } from '@fortawesome/free-solid-svg-icons';
import { faChartLine } from '@fortawesome/free-solid-svg-icons';

library.add(faHome);
library.add(faFileAlt);
library.add(faChartLine);

const navigationItems = (props) => {
    return (
        <Aux>

            <p>CONSUMER</p>
            <ul className={classes.NavigationItems}>
                <li><a href="/"><FontAwesomeIcon className={classes.Icon1Paddig} icon="home" /> Home</a></li>
                <li><a href="/"><FontAwesomeIcon className={classes.Icon2Paddig} icon="file-alt" /> Dashboard</a></li>
                <li><a href="/"><FontAwesomeIcon className={classes.Icon3Paddig} icon="chart-line" /> Statistics</a></li>
            </ul>
            <div className={classes.Divider}></div>
            <div className={classes.ButtonPosition}>

                <button onClick={props.clicked}><img className={classes.CollapseIcon} src={CollapseIcon} alt='icon'></img>Collapse sidebar</button>
            </div>
            <div className={classes.Divider + ' ' + classes.DividerBottom}></div>
            <p className={classes.footer}>Micheal Alfa v 1.0.0</p>
            <p className={classes.footer}>Copyrights @ 2019 All Rights Reserved</p>
        </Aux>

    );
};

export default navigationItems;
</code>```

Any ideas?
Thank you

答:
You are not doing anything with the passed onClick event. You need to put it on something, like so:

```<code>const sideBar = (props) => (
  <div onClick={this.props.onClick} className={Classes.SideBar}>
    <Logo />
    <nav>
      <NavigationItems />
    </nav>
  </div>
);

export default sideBar;
</code>```

This will fire that event when you click on the div. Make sense?

Body:
In my main container the layout has this code

import React, { Component } from 'react';
import Header from '../../components/Navigation/Header/Header';
import SideBar from '../../components/Navigation/SideBar/SideBar';

class Layout extends Component {
    state = {
        showSideBar: true
    }

    sideBarToggleHandler = () => {
        console.log("test");
    }

    render() {

        return (

                    <SideBar onClick={this.sideBarToggleHandler}/>

                        {this.props.children}

        )
    }
}

export default Layout;

Whenever I click on any element in the side bar I want to console log test

For some reason this is not happening however if I move the onClick method to the header for example or to main it works fine

This is my sidebar:

import React from 'react';
import classes from './SideBar.module.scss';
import Logo from '../Logo/Logo'
import NavigationItems from './NavigationItems/NavigationItems'
const sideBar = (props) => {

    }
    return (

            <Logo />

                <NavigationItems />

    );
};

export default sideBar;

and this is my navigation items:

import React from 'react';
import classes from './NavigationItems.module.scss';
import Aux from '../../../../hoc/Aux';
import CollapseIcon from '../../../../assets/Images/Icons/collapse.svg'

import { library } from '@fortawesome/fontawesome-svg-core';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faHome } from '@fortawesome/free-solid-svg-icons';
import { faFileAlt } from '@fortawesome/free-solid-svg-icons';
import { faChartLine } from '@fortawesome/free-solid-svg-icons';

library.add(faHome);
library.add(faFileAlt);
library.add(faChartLine);

const navigationItems = (props) => {
    return (
        <Aux>

CONSUMER

<FontAwesomeIcon className={classes.Icon1Paddig} icon="home" /> Home

<FontAwesomeIcon className={classes.Icon2Paddig} icon="file-alt" /> Dashboard

<FontAwesomeIcon className={classes.Icon3Paddig} icon="chart-line" /> Statistics

                <button onClick={props.clicked}>Collapse sidebar</button>

Micheal Alfa v 1.0.0

Copyrights @ 2019 All Rights Reserved

        </Aux>

    );
};

export default navigationItems;

Any ideas?
Thank you

Body:
You are not doing anything with the passed onClick event. You need to put it on something, like so:

const sideBar = (props) => (
  <div onClick={this.props.onClick} className={Classes.SideBar}>
    <Logo />
    <nav>
      <NavigationItems />
    </nav>
  </div>
);

export default sideBar;

This will fire that event when you click on the div. Make sense?


问:
iOS: Detect if the device is iPhone X family (frameless)
In my app there is some logic for frameless devices (iPhoneX, Xs Xs max, Xr). Currently it works base on the model of the devices, so, I detect the model by DeviceKit framework.

But I want to extend this logic to future frameless devices. Probably in one year we will have some extra frameless devices. So, how can I detect if device is frameless or not? It should cover all current frameless devices and future one.

We can not rely on faceID, safeAreaInset, screen height or size. So, then what?

答:
This is valid for any orientation.
No need to worry about iOS version before 11.0 since iPhone X minimum version is 11.0. Source</p>

```<code>extension UIDevice {

    var hasNotch: Bool {
        if #available(iOS 11.0, *) {
           return UIApplication.shared.keyWindow?.safeAreaInsets.bottom ?? 0 > 0
        }
        return false
   }
}
</code>```

Body:
This is valid for any orientation.
No need to worry about iOS version before 11.0 since iPhone X minimum version is 11.0. Source

extension UIDevice {

    var hasNotch: Bool {
        if #available(iOS 11.0, *) {
           return UIApplication.shared.keyWindow?.safeAreaInsets.bottom ?? 0 > 0
        }
        return false
   }
}


答:
If you are using Maven, add the below in pom.xml file.

```<code><dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.16</version>
</dependency>
</code>```

If you are not using maven, then download the mysql-connector jar file from the below location and put it inside WEB-INF/lib.

http://central.maven.org/maven2/mysql/mysql-connector-java/8.0.16/mysql-connector-java-8.0.16.jar

Title: ClassNotFoundException thrown when trying to find jdbc driver using Vaadin Framework

Body:
If you are using Maven, add the below in pom.xml file.

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.16</version>
</dependency>

If you are not using maven, then download the mysql-connector jar file from the below location and put it inside WEB-INF/lib.

http://central.maven.org/maven2/mysql/mysql-connector-java/8.0.16/mysql-connector-java-8.0.16.jar


问:
sed: Given filename w/ absolute path, do replacement only on filename. Working only when pattern is at start of filename
I'm working on a sed replacement pattern that will take a file name with an absolute path and then print the unaltered input as well as the modified input (which should only be applied to the file name, not the path). Some path is guaranteed to be explicitly defined, so it will never be given something like "test.c", it would be "./test.c" in that instance.

I have some regex that is working, but only when the part to be substituted is at the start of the file name. I'd like it to work with any part of the file name.

To clarify, here's a summary of the current behavior.

```<code>INPUT           PATTERN              CURRENT OUTPUT       DESIRED BEHAVIOR?

./test.c        p;s;\(.*/\)t;\1###;  ./test.c             Yes
                                     ./###est.c

testdir/test.c  p;s;\(.*/\)tes;\1#;  testdir/test.c       Yes
                                     testdir/#t.c

./test.c        p;s;\(.*/\)est;\1#;  ./test.c             NO
                                     ./test.c             Should be ./t#.c
</code>```

As you can see, this is my pattern:

```<code>p;s;\(.*/\)SubstringToFind;\1SubstringToInsert;
</code>```

Here's my logic for this:

p to print the unmodified line

s for substitution (yeah, we all know that)

Capture the path: Any number of characters plus a final "/"

SubstringToFind: Look for a pattern somewhere in the file name.

\1: Recover the unmodified path

SubstringToInsert: Insert the modified file name

I'm sure this just calls for one tiny little addition like one more ".*", which I've tried adding right after the capturing parentheses, but that just replaces the specified pattern along with all file name characters before it. I'm sure the solution is staring me in the face but I'm not seeing it. Any help from someone more seasoned in regex than myself? Thanks!

答:
You were indeed very close.  Your pattern for the last case looks for est immediately after the slash specified in the capture, but est isn't immediately after the slash.

You need:

```<code>$ echo ./test.c | sed -e 'p;s;\(.*/[^/]*\)est;\1#;'
./test.c
./t#.c
$
</code>```

I used the negated character class to avoid matching as much as .* would, but you could also use that (and I'm not sure there's actually any significant benefit to the negated character class).  A slightly more stringent test:

```<code>$ printf '%s\n' ./test.c ./southwest.c ./west-by-southwest.c south/west/southwestern.c |
> sed -e 'p;s;\(.*/[^/]*\)est;\1#;'
./test.c
./t#.c
./southwest.c
./southw#.c
./west-by-southwest.c
./west-by-southw#.c
south/west/southwestern.c
south/west/southw#ern.c
$
</code>```

Body:
I'm working on a sed replacement pattern that will take a file name with an absolute path and then print the unaltered input as well as the modified input (which should only be applied to the file name, not the path). Some path is guaranteed to be explicitly defined, so it will never be given something like "test.c", it would be "./test.c" in that instance.

I have some regex that is working, but only when the part to be substituted is at the start of the file name. I'd like it to work with any part of the file name.

To clarify, here's a summary of the current behavior.

INPUT           PATTERN              CURRENT OUTPUT       DESIRED BEHAVIOR?

./test.c        p;s;\(.*/\)t;\1###;  ./test.c             Yes
                                     ./###est.c

testdir/test.c  p;s;\(.*/\)tes;\1#;  testdir/test.c       Yes
                                     testdir/#t.c

./test.c        p;s;\(.*/\)est;\1#;  ./test.c             NO
                                     ./test.c             Should be ./t#.c

As you can see, this is my pattern:

p;s;\(.*/\)SubstringToFind;\1SubstringToInsert;

Here's my logic for this:

p to print the unmodified line

s for substitution (yeah, we all know that)

Capture the path: Any number of characters plus a final "/"

SubstringToFind: Look for a pattern somewhere in the file name.

\1: Recover the unmodified path

SubstringToInsert: Insert the modified file name

I'm sure this just calls for one tiny little addition like one more ".*", which I've tried adding right after the capturing parentheses, but that just replaces the specified pattern along with all file name characters before it. I'm sure the solution is staring me in the face but I'm not seeing it. Any help from someone more seasoned in regex than myself? Thanks!

Body:
You were indeed very close.  Your pattern for the last case looks for est immediately after the slash specified in the capture, but est isn't immediately after the slash.

You need:

$ echo ./test.c | sed -e 'p;s;\(.*/[^/]*\)est;\1#;'
./test.c
./t#.c
$

I used the negated character class to avoid matching as much as .* would, but you could also use that (and I'm not sure there's actually any significant benefit to the negated character class).  A slightly more stringent test:

$ printf '%s\n' ./test.c ./southwest.c ./west-by-southwest.c south/west/southwestern.c |
> sed -e 'p;s;\(.*/[^/]*\)est;\1#;'
./test.c
./t#.c
./southwest.c
./southw#.c
./west-by-southwest.c
./west-by-southw#.c
south/west/southwestern.c
south/west/southw#ern.c
$