问:
Phone Number Mask - Internationals
My Problem

My Customer Contact Database has a variety of customers from around the world in it, and this causes some problems for my telephone numbers - because of the different methods of formating in other countries. So my question is, firstly since I also have a country field - Is it possible to have the type of mask change based of what country the customer is in?

Example:

```<code>In Canada -> (xxx)xxx-xxxx
In Australia -> (xx) xxxx-xxxx
In South Africa -> xx (x) xx-xxx-xxxx
</code>```

x - A placeholder for numbers

Would this be possible?

答:
Hans mentioned he couldn't get the Input Mask to change at runtime - I haven't seen his previous answer, but this seems to work for me. My form has a drop-down for country (cmbCountry), and a text box for phone. My combo box (cmbCountry) is tied to a table (Row Source=SELECT [_ masks].Country, [_ masks].Mask FROM [_ masks];). The "masks" field is hidden by having its' width be zero.

I've also bound the form to a table which stores the countries and phone numbers. When the country changes, or the record changes, I change the ListIndex property.

FYI - I did not give the Input Mask any default value in Design mode.

@HansUp, is this similar to what you had already? Sorry if I'm re-answering the question in the same way.

In the code behind the form:

```<code>Private Sub cmbCountry_Change()
    Dim sMask
    If cmbCountry.ListIndex > -1 Then
        sMask = cmbCountry.Column(1, cmbCountry.ListIndex)
        tbPhone.InputMask = sMask
    End If
End Sub

Private Sub Form_Current()
    cmbCountry_Change
End Sub
</code>```

Title: Phone Number Mask - Internationals

Body:
My Problem

My Customer Contact Database has a variety of customers from around the world in it, and this causes some problems for my telephone numbers - because of the different methods of formating in other countries. So my question is, firstly since I also have a country field - Is it possible to have the type of mask change based of what country the customer is in?

Example:

In Canada -> (xxx)xxx-xxxx
In Australia -> (xx) xxxx-xxxx
In South Africa -> xx (x) xx-xxx-xxxx

x - A placeholder for numbers

Would this be possible?

Body:
Hans mentioned he couldn't get the Input Mask to change at runtime - I haven't seen his previous answer, but this seems to work for me. My form has a drop-down for country (cmbCountry), and a text box for phone. My combo box (cmbCountry) is tied to a table (Row Source=SELECT [_ masks].Country, [_ masks].Mask FROM [_ masks];). The "masks" field is hidden by having its' width be zero.

I've also bound the form to a table which stores the countries and phone numbers. When the country changes, or the record changes, I change the ListIndex property.

FYI - I did not give the Input Mask any default value in Design mode.

@HansUp, is this similar to what you had already? Sorry if I'm re-answering the question in the same way.

In the code behind the form:

Private Sub cmbCountry_Change()
    Dim sMask
    If cmbCountry.ListIndex > -1 Then
        sMask = cmbCountry.Column(1, cmbCountry.ListIndex)
        tbPhone.InputMask = sMask
    End If
End Sub

Private Sub Form_Current()
    cmbCountry_Change
End Sub


来源: stackexchange

问:
How to fill an array of structs when parameter argument is a double pointer
Working on a piece of homework, having issue with filling in a struct array with values as I keep getting a "Invalid write of size 8" error after I fill anything past the first element.

#include <stdio.h>
#include <stdlib.h>

struct DS_t {
    int a;
    double b;
    char c;
};

void f4(struct DS_t ** x) {
    *x = (struct DS_t *) malloc(4 * sizeof(struct DS_t));
    struct DS_t d1 = {3, 2.3};
    *x[0] = d1;
    *x[1] = d1;
}

int main() {
    struct DS_t * ds4_p;
    f4( &ds4_p );
    printf("DS_t[0] = {%d, %f, %s}\n", ds4_p[0].a, ds4_p[0].b, ds4_p[0].c);
    printf("DS_t[1] = {%d, %f, %s}\n", ds4_p[1].a, ds4_p[1].b, ds4_p[1].c);
    printf("DS_t[2] = {%d, %f, %s}\n", ds4_p[2].a, ds4_p[2].b, ds4_p[2].c);
    //etc
}
```

I want to create an array of struct DS_t using the *x to the **x in the function parameter and then fill up that array, which I believe *x = (struct DS_t *)calloc(4, sizeof(struct DS_t)); does. Seeing it through a visualizer, I see that in f4, the x points to ds4_p and then ds4_p points to 4 struct DS_t, which is what I want.

But whenever I go to try and fill it, I get that invalid write of size 8 error. I have no problem with *x[0]= d1, it fills the first element just fine, anything after is where my issue lies.

What is it that I am missing with this? Been working on it for a while and haven't had any luck with it. Maybe I'm going about it the wrong way? Just need to print out each element of the array pointer. The struct and function was all created specifically like this, so can't change any of that.

答:
A number of problems in the code:

[] has higher order of precedence than *. So *x[0] = d1; is actually equivalent to *(x[0]) = d1;. Which is not what you want. Instead, it should be (*x)[0] = d1;. Same for the line after it of course.

You are using malloc rather than calloc as you claim. Which means ds4_p[2] (and ds4_p[3]) are uninitalised. Either use calloc or don't attempt to access ds4_p[2].

%s is for strings. But you only have a single char. Use %c instead. But note that d1.c is set to 0 so %c will not print any visible character.

ContentLicense: CC BY-SA 4.0

Body:
Working on a piece of homework, having issue with filling in a struct array with values as I keep getting a "Invalid write of size 8" error after I fill anything past the first element.

#include <stdio.h>
#include <stdlib.h>

struct DS_t {
    int a;
    double b;
    char c;
};

void f4(struct DS_t ** x) {
    *x = (struct DS_t *) malloc(4 * sizeof(struct DS_t));
    struct DS_t d1 = {3, 2.3};
    *x[0] = d1;
    *x[1] = d1;
}

int main() {
    struct DS_t * ds4_p;
    f4( &ds4_p );
    printf("DS_t[0] = {%d, %f, %s}\n", ds4_p[0].a, ds4_p[0].b, ds4_p[0].c);
    printf("DS_t[1] = {%d, %f, %s}\n", ds4_p[1].a, ds4_p[1].b, ds4_p[1].c);
    printf("DS_t[2] = {%d, %f, %s}\n", ds4_p[2].a, ds4_p[2].b, ds4_p[2].c);
    //etc
}

I want to create an array of struct DS_t using the *x to the **x in the function parameter and then fill up that array, which I believe *x = (struct DS_t *)calloc(4, sizeof(struct DS_t)); does. Seeing it through a visualizer, I see that in f4, the x points to ds4_p and then ds4_p points to 4 struct DS_t, which is what I want.

But whenever I go to try and fill it, I get that invalid write of size 8 error. I have no problem with *x[0]= d1, it fills the first element just fine, anything after is where my issue lies.

What is it that I am missing with this? Been working on it for a while and haven't had any luck with it. Maybe I'm going about it the wrong way? Just need to print out each element of the array pointer. The struct and function was all created specifically like this, so can't change any of that.


问:
I have a double nested list. I would like to remove the second element inside of the nested list. i.e. [[[x,1],[x,2],[x,3]],[[x,1],[x,2],[x,3]]]
```<code>for x in y:
    [z.pop(0) for z in x]
</code>```

IndexError: pop index out of range.

The function seems to keep looping after it has gone through all the values of x. I would like to move on the next value of x after it has done it has completed its work. I understand that the error is occurring due to the changing of my data shape, but how do I avoid this?

答:
First solution:

```<code>nested_list = [[[11,1],[20,2],[300,3]],[[100,1],[202,2],[303,3]]]
for lst in nested_list:
    for j in lst:
        j.pop(1)
print(nested_list)
</code>```

The above solution will give you the following output:

```<code>[[[11], [20], [300]], [[100], [202], [303]]]
</code>```

Second Solution

```<code>nested_list = [[[11,1],[20,2],[300,3]],[[100,1],[202,2],[303,3]]]
result = []
for lst in nested_list:
    for j in lst:
        result.append(j[0])
print(result)
del nested_list
</code>```

The above solution will give you the following output:

```<code>[11, 20, 300, 100, 202, 303]
</code>```

If you are familiar with python then you can also go with the following:

```<code>nested_list = [[[11,1],[20,2],[300,3]],[[100,1],[202,2],[303,3]]]
def return_first(lst):
    return [j[0] for i in lst for j in i]
print(return_first(nested_list))
del nested_list
</code>```

The above solution will give you the following output:

```<code>[11, 20, 300, 100, 202, 303]
</code>```

Body:
for x in y:
    [z.pop(0) for z in x]

IndexError: pop index out of range.

The function seems to keep looping after it has gone through all the values of x. I would like to move on the next value of x after it has done it has completed its work. I understand that the error is occurring due to the changing of my data shape, but how do I avoid this?

Body:
First solution:

nested_list = [[[11,1],[20,2],[300,3]],[[100,1],[202,2],[303,3]]]
for lst in nested_list:
    for j in lst:
        j.pop(1)
print(nested_list)

The above solution will give you the following output:

[[[11], [20], [300]], [[100], [202], [303]]]

Second Solution

nested_list = [[[11,1],[20,2],[300,3]],[[100,1],[202,2],[303,3]]]
result = []
for lst in nested_list:
    for j in lst:
        result.append(j[0])
print(result)
del nested_list

The above solution will give you the following output:

[11, 20, 300, 100, 202, 303]

If you are familiar with python then you can also go with the following:

nested_list = [[[11,1],[20,2],[300,3]],[[100,1],[202,2],[303,3]]]
def return_first(lst):
    return [j[0] for i in lst for j in i]
print(return_first(nested_list))
del nested_list

The above solution will give you the following output:

[11, 20, 300, 100, 202, 303]


问:
Laravel_php terminate the request by sending a response at any given condition
I built a login backend where I want to check some conditions before allowing the login.

I could check all conditions in one shoot but I need to send a different response for every failed attempt.

In the index method below all check methods are called, the specific thing I need is that if any condition is true then the request should terminate and the response should be sent back without calling other methods after it.

Currently the return at every method seems not respected.

```<code>public function index(LoginRequest $request){
    $user = User::select('leave','role','id','isActive')->find(request('username'));
    $this->checkRole($user);
    $this->checkAnnualLeave($user);
    $this->checkAccountDisabled($user);
}

public function checkRole($user){
    $Condition1=true;

    if($Condition1){
       return response()->json(['message'=>'user is anauthorized !']);
    }
}

public function checkAnnualLeave($user){
    $Condition2=true;

    if($Condition2){
        return response()->json(['message'=>'user is in Annual leave']);
    }
}

public function checkAccountDisabled($user){
    $ConditioN3=true;

    if($ConditioN3){
       return response()->json(['message'=>'user account is disabled']);
    }
}
</code>```

答:
You can abort within every conditional returning the wanted error code and message.</p>
```<code>public function index(LoginRequest $request){
    $user = User::select('leave','role','id','isActive')->find(request('username'));
    $this->checkRole($user);
    $this->checkAnnualLeave($user);
    $this->checkAccountDisabled($user);
}

public function checkRole($user){
    $Condition1=true;

    if($Condition1){
        abort(403, 'user is anauthorized !');
    }
}

public function checkAnnualLeave($user){
    $Condition2=true;

    if($Condition2){
        abort(404, 'user is in Annual leave');
    }
}

public function checkAccountDisabled($user){
    $ConditioN3=true;

    if($ConditioN3){
        abort(401, 'user account is disabled');
    }
}
</code>```

Body:
I built a login backend where I want to check some conditions before allowing the login.

I could check all conditions in one shoot but I need to send a different response for every failed attempt.

In the index method below all check methods are called, the specific thing I need is that if any condition is true then the request should terminate and the response should be sent back without calling other methods after it.

Currently the return at every method seems not respected.

public function index(LoginRequest $request){
    $user = User::select('leave','role','id','isActive')->find(request('username'));
    $this->checkRole($user);
    $this->checkAnnualLeave($user);
    $this->checkAccountDisabled($user);
}

public function checkRole($user){
    $Condition1=true;

    if($Condition1){
       return response()->json(['message'=>'user is anauthorized !']);
    }
}

public function checkAnnualLeave($user){
    $Condition2=true;

    if($Condition2){
        return response()->json(['message'=>'user is in Annual leave']);
    }
}

public function checkAccountDisabled($user){
    $ConditioN3=true;

    if($ConditioN3){
       return response()->json(['message'=>'user account is disabled']);
    }
}

Body:
You can abort within every conditional returning the wanted error code and message.

public function index(LoginRequest $request){
    $user = User::select('leave','role','id','isActive')->find(request('username'));
    $this->checkRole($user);
    $this->checkAnnualLeave($user);
    $this->checkAccountDisabled($user);
}

public function checkRole($user){
    $Condition1=true;

    if($Condition1){
        abort(403, 'user is anauthorized !');
    }
}

public function checkAnnualLeave($user){
    $Condition2=true;

    if($Condition2){
        abort(404, 'user is in Annual leave');
    }
}

public function checkAccountDisabled($user){
    $ConditioN3=true;

    if($ConditioN3){
        abort(401, 'user account is disabled');
    }
}


问:
How to create a form named button in C # and display the form by pressing it
I wrote a program in which I can create a shortcut from the side forms to the main form. But when I click on each button, the relevant form does not open.

Why?

Because the amount of type to be sent is sent as null.

I will send you the relevant code. Can you help me solve the problem?

```<code>public void CreatShortCut(string idForm, string nameForm)
    {
        if (string.IsNullOrWhiteSpace(nameForm))
        {
            return;
        }
        else
        {
            button =
                new System.Windows.Forms.Button();

            button.Name = $"{idForm}Button";
            button.Text = nameForm;
            button.Size = new System.Drawing.Size(100, 30);
            button.TabIndex = 0;
            button.UseVisualStyleBackColor = true;
            button.ContextMenuStrip = contextMenuStrip;
            button.Click += Button_Click;
            button.MouseEnter += Button_MouseEnter;

            shortcutPanel.Controls.Add(button);
        }
    }

private void Button_Click(object sender, System.EventArgs e)
    {
        try
        {
            System.Windows.Forms.Button button = sender as System.Windows.Forms.Button;

            string typeName =
                button.Name.Replace("Button", string.Empty).Trim();

            var form =
                (System.Windows.Forms.Form)System.Activator.CreateInstance(System.Type.GetType(GetType().Name + "." + typeName));

            form.ShowDialog();
        }
        catch (System.Exception ex)
        {
            System.Windows.Forms.MessageBox.Show($"{ex.Message}");
        }
    }
</code>```

答:
You're better off not passing around strings and you should avoid activators. Instead you should use generics.

Try this:

```<code>public void CreatShortCut<F>(string nameForm) where F : Form, new()
{
    if (string.IsNullOrWhiteSpace(nameForm))
    {
        return;
    }
    else
    {
        var button = new System.Windows.Forms.Button();
        button.Text = nameForm;
        button.Size = new System.Drawing.Size(100, 30);
        button.TabIndex = 0;
        button.UseVisualStyleBackColor = true;
        button.ContextMenuStrip = contextMenuStrip;
        button.Click += (s, e) =>
        {
            var form = new F();
            form.ShowDialog();
        }
        shortcutPanel.Controls.Add(button);
    }
}
</code>```

Body:
I wrote a program in which I can create a shortcut from the side forms to the main form. But when I click on each button, the relevant form does not open.

Why?

Because the amount of type to be sent is sent as null.

I will send you the relevant code. Can you help me solve the problem?

public void CreatShortCut(string idForm, string nameForm)
    {
        if (string.IsNullOrWhiteSpace(nameForm))
        {
            return;
        }
        else
        {
            button =
                new System.Windows.Forms.Button();

            button.Name = $"{idForm}Button";
            button.Text = nameForm;
            button.Size = new System.Drawing.Size(100, 30);
            button.TabIndex = 0;
            button.UseVisualStyleBackColor = true;
            button.ContextMenuStrip = contextMenuStrip;
            button.Click += Button_Click;
            button.MouseEnter += Button_MouseEnter;

            shortcutPanel.Controls.Add(button);
        }
    }

private void Button_Click(object sender, System.EventArgs e)
    {
        try
        {
            System.Windows.Forms.Button button = sender as System.Windows.Forms.Button;

            string typeName =
                button.Name.Replace("Button", string.Empty).Trim();

            var form =
                (System.Windows.Forms.Form)System.Activator.CreateInstance(System.Type.GetType(GetType().Name + "." + typeName));

            form.ShowDialog();
        }
        catch (System.Exception ex)
        {
            System.Windows.Forms.MessageBox.Show($"{ex.Message}");
        }
    }

Body:
You're better off not passing around strings and you should avoid activators. Instead you should use generics.

Try this:

public void CreatShortCut<F>(string nameForm) where F : Form, new()
{
    if (string.IsNullOrWhiteSpace(nameForm))
    {
        return;
    }
    else
    {
        var button = new System.Windows.Forms.Button();
        button.Text = nameForm;
        button.Size = new System.Drawing.Size(100, 30);
        button.TabIndex = 0;
        button.UseVisualStyleBackColor = true;
        button.ContextMenuStrip = contextMenuStrip;
        button.Click += (s, e) =>
        {
            var form = new F();
            form.ShowDialog();
        }
        shortcutPanel.Controls.Add(button);
    }
}


问:
What to use instead of threads with quart
I want to make a discord bot dashboard with replit and I want to use quart, there is my keep_alive function:

def run():
  app.run(host="0.0.0.0", port=8080)

def keep_alive():
  server = Thread(target=run)
  server.start()
```

There is just one little problem, I don't know what to use instead of thread because Quart is an asynchronous library.

答:
Quart run takes the following arguments. if you want to reload on file changes then it does the job by default.

```<code>def run(
    self,
    host: Optional[str] = None,
    port: Optional[int] = None,
    debug: Optional[bool] = None,
    use_reloader: bool = True,
    loop: Optional[asyncio.AbstractEventLoop] = None,
    ca_certs: Optional[str] = None,
    certfile: Optional[str] = None,
    keyfile: Optional[str] = None,
    **kwargs: Any,
) -> None:
</code>```

Body:
I want to make a discord bot dashboard with replit and I want to use quart, there is my keep_alive function:

def run():
  app.run(host="0.0.0.0", port=8080)

def keep_alive():
  server = Thread(target=run)
  server.start()

There is just one little problem, I don't know what to use instead of thread because Quart is an asynchronous library.

Body:
Quart run takes the following arguments. if you want to reload on file changes then it does the job by default.

def run(
    self,
    host: Optional[str] = None,
    port: Optional[int] = None,
    debug: Optional[bool] = None,
    use_reloader: bool = True,
    loop: Optional[asyncio.AbstractEventLoop] = None,
    ca_certs: Optional[str] = None,
    certfile: Optional[str] = None,
    keyfile: Optional[str] = None,
    **kwargs: Any,
) -> None:


问:
The argument type 'List<DropdownMenuItem<dynamic>>' can't be assigned to the parameter type 'List<DropdownMenuItem<String>>?'
DropdownButton(
value: value,
items: locationItems,
onChanged: (value) => setState(() {
this.value = value;
print(value);
}),
),

for(int i = 0;i<widget.locationLength;i++){
locationItems.add(
DropdownMenuItem(
child: Text(
widget.locationName
),
value: "${widget.locationName}",
)
);
}

答:
you need to add type to the dropdown button

DropdownButton<String>( value: value,
 items: locationItems,
 onChanged: (value) => setState(() {
         this.value = value;
         print(value);
       }),
 ),
```
<p>and you also must ensure that <code>locationItems</code> is of type <code>List<DropdownMenuItem<String>>?</code>. you can do this by adding type to <code>DropdownMenuItem</code> when adding to list like this:</p>
<pre class="lang-dart prettyprint-override"><code>locationItems.add( DropdownMenuItem<String>(
   child: Text( widget.locationName ),
    value: "${widget.locationName}",
   )
);
</code>```

or by strongly type locationItems when declaring it.

List<DropdownMenuItem<String>>? locationItems;
```

Body:
you need to add type to the dropdown button

DropdownButton<String>( value: value,
 items: locationItems,
 onChanged: (value) => setState(() {
         this.value = value;
         print(value);
       }),
 ),

and you also must ensure that locationItems is of type List<DropdownMenuItem<String>>?. you can do this by adding type to DropdownMenuItem when adding to list like this:

locationItems.add( DropdownMenuItem<String>(
   child: Text( widget.locationName ),
    value: "${widget.locationName}",
   )
);

or by strongly type locationItems when declaring it.

List<DropdownMenuItem<String>>? locationItems;


问:
Creating DateTime in C#
How would I dynamically create a DateTime object, that always has what the current month/day/year is, but always has the 16:00 time component?

答:
You can do this:

```<code> var today = DateTime.Today.AddHours(16);
</code>```

That should be whatever today is at 16:00 (4pm)

ContentLicense: CC BY-SA 3.0

Title: Creating DateTime in C#

Body:
You can do this:

 var today = DateTime.Today.AddHours(16);

That should be whatever today is at 16:00 (4pm)


问:
What is MVC? and what UI does it use?
I see a lot of jobs asking for MVC experience.
I am assuming the roles are talking about asp.net MVC as they are generally .NET jobs I have been looking at.
A few questions:
1.Generally when people say MVC are they talking about it as a general design pattern or as asp.net MVC? is it important to be specific here?
2.What is the UI in asp.net MVC? is it just razor views? is webforms another option? blazor? Can other UI's like javascript frameworks be used?
3. Typically when a job is asking for MVC experience what are they asking for? razor views experience? is this different in a .Net context?</p>

答:
Generally, MVC is a design pattern. Every tech stack has specific
frameworks to support that design pattern. Asp.Net MVC for .Net,
Spring MVC for Java. etc.

If you are talking about job descriptions, yes, it is important to
be a specific framework. Net developers will be interested in using
Asp.Net MVC. Java developers will be interested in using Spring
MVC.etc. The concept is similar. The difference is the knowledge of
using these frameworks.

UI in asp.net MVC can be Razor, blazor or javascript frameworks
(Angular, ReactJs..etc). For webforms, since MVC is a design
pattern, of course, we can implement MVC with webforms too. However,
we need to custom a lot for implementation of Models/Controllers...The
webform was designed to bring the concept of windows form to the
web. It does not support MVC by default.

It depends on the job and the projects they are working on whether
they require Asp.Net MVC with razor views or javascript frameworks
(Angular, ReactJS) as views.

There are different implementations of views in Asp.Net MVC. Some projects will use Razor for views, others will use Angular for examples. Usually, for .Net developer roles, they will expect you know at least one of them or be able to learn them.

Title: What is MVC? and what UI does it use?


问:
Table Testing Go Generics
I'm excited for Go 1.18 and wanted to test the new generics feature.
Feels pretty neat to use, but I stumbled over an issue:

How do you table test generic functions?

I came up with this code, but I need to redeclare my testing logic over each function since I can't instantiate T values.
(Inside my project I use structs instead of string and int. Just didn't want to include them because it's already enough code)

How would you approach this problem?

Edit:
Here's the code:

package main

import (
    "testing"

    "github.com/stretchr/testify/assert"
)

type Item interface {
    int | string
}

type store[T Item] map[int64]T

// add adds an Item to the map if the id of the Item isn't present already
func (s store[T]) add(key int64, val T) {
    _, exists := s[key]
    if exists {
        return
    }
    s[key] = val
}

func TestStore(t *testing.T) {
    t.Run("ints", testInt)
    t.Run("strings", testString)
}

type testCase[T Item] struct {
    name     string
    start    store[T]
    key      int64
    val      T
    expected store[T]
}

func testString(t *testing.T) {
    t.Parallel()
    tests := []testCase[string]{
        {
            name:  "empty map",
            start: store[string]{},
            key:   123,
            val:   "test",
            expected: store[string]{
                123: "test",
            },
        },
        {
            name: "existing key",
            start: store[string]{
                123: "test",
            },
            key: 123,
            val: "newVal",
            expected: store[string]{
                123: "test",
            },
        },
    }
    for _, tc := range tests {
        t.Run(tc.name, runTestCase(tc))
    }
}

func testInt(t *testing.T) {
    t.Parallel()
    tests := []testCase[int]{
        {
            name:  "empty map",
            start: store[int]{},
            key:   123,
            val:   456,
            expected: store[int]{
                123: 456,
            },
        },
        {
            name: "existing key",
            start: store[int]{
                123: 456,
            },
            key: 123,
            val: 999,
            expected: store[int]{
                123: 456,
            },
        },
    }
    for _, tc := range tests {
        t.Run(tc.name, runTestCase(tc))
    }
}

func runTestCase[T Item](tc testCase[T]) func(t *testing.T) {
    return func(t *testing.T) {
        tc.start.add(tc.key, tc.val)
        assert.Equal(t, tc.start, tc.expected)
    }
}

```

答:
I need to redeclare my testing logic over each function

Correct.

Your function runTestCase[T Item](tc testCase[T]) already provides a reasonable level of abstraction. As you did, you can put there some common logic about starting the test and verifying the expected outcome. However that's about it.

A generic type (or function) under test has to be instantiated with some concrete type sooner or later, and one single test table can only include either one of those types — or interface{}/any, which you can not use to satisfy a specific constraint like int | string.

However, you do not need to always test every possible type parameter. The purpose of generics is to write code that works with arbitrary types, and in particular the purpose of constraints is to write code with arbitrary types that support the same operations.

I'd advise to write unit tests for different types only if the code makes use of operators that have different meanings. For example:

the + operator for numbers (sum) and strings (concatenation)

the < and > for numbers (greater, lesser) and strings (lexicographically before or after)

See also this where the OP was attempting to do something similar

Title: Table Testing Go Generics


答: With hypercorn.asyncio.serve, you can turn an ASGI server (i.e., Quart here) to an asnycio.Future object, which allows you to push the Future to event loop (by asyncio.create_task or something else) and run it at background.

Title: What to use instead of threads with quart


问:
Only run code if on a certain version of Xcode
I'm making a library that uses the variants variable of AVAsset. That's less important; the significant part is that it has an Xcode 13+ requirement. This library may be used by apps running Xcode 12. Is there a compiler flag that can run code only if on a certain version of Xcode?

Something like how you would do this for a Swift version:

```<code>#if swift(>=5.0)
   // code
#else
   // code
#endif
</code>```

I'd want to do

```<code>#if xcode(>=13.0)

   // use variants

#endif
</code>```

答:
From what I know, there’s no way of directly checking the Xcode version. However, Xcode 13 supports iOS 15, Xcode 12 doesn’t. You can use that as a workaround to check if Xcode version is 13 or higher.

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 150000 // iOS 15 or greater
// Xcode 12 will not see this code.
#else
// Xcode 12 and lower will see this
#endif
```

Body:
I'm making a library that uses the variants variable of AVAsset. That's less important; the significant part is that it has an Xcode 13+ requirement. This library may be used by apps running Xcode 12. Is there a compiler flag that can run code only if on a certain version of Xcode?

Something like how you would do this for a Swift version:

#if swift(>=5.0)
   // code
#else
   // code
#endif

I'd want to do

#if xcode(>=13.0)

   // use variants

#endif


问:
Splitting an array into sequential groups
I have an array with elements [2, 3, 4, 5, 6, 7, 8, 9, 10, ...]. I wish to split this up as follows: [[2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], ...]. I am not sure how to do this because the elements in each split must be repeated, and I am unsure of how to create these repeated elements. Any help will be much appreciated.

答:
There's a module "more_itertools" that has method that creates triples from a list:

```<code>import more_itertools
out = list(more_itertools.triplewise(lst))
</code>```

Output:

```<code>[(2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7), (6, 7, 8), (7, 8, 9), (8, 9, 10)]
</code>```

It's not a built-in module, so you'll have to install it (pip or conda or whatever you use) beforehand however.

Body:
There's a module "more_itertools" that has method that creates triples from a list:

import more_itertools
out = list(more_itertools.triplewise(lst))

Output:

[(2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7), (6, 7, 8), (7, 8, 9), (8, 9, 10)]

It's not a built-in module, so you'll have to install it (pip or conda or whatever you use) beforehand however.


问:
Axios.post sends request two times
I have a problem with axios.post sending two times the same request with the same body. I have tried to Google the problem but find nothing. How can I fix it?

App.js

```<code>import logo from './logo.svg';
import './App.css';
import Register from "./register";
import SendToken from "./sendToken";
import {BrowserRouter, Routes, Route} from "react-router-dom";
import Confirmation from "./Confirmation";

import {useParams} from "react-router-dom";

function App() {
  return (
      <BrowserRouter>
          <div>
              <Routes>
                  <Route path="/registration" element={<Register/>}/>
                  <Route path="/confirmation" element={<Confirmation/>}/>
                  <Route path="/account/registrationConfirm/:data" element={<SendToken/>}/>
              </Routes>
          </div>
      </BrowserRouter>

  );
}

export default App;
</code>```

sendToken.js

```<code>import axios from 'axios';

const SendToken = () => {
    let parts = window.location.href.split('/');
    let length = parts.length;
    let token = parts[length - 1] == '' ? parts[length - 2] : parts[length - 1]

    axios.post("http://localhost:8080/api/v1/registration/registrationConfirm", {token}).then((data) => {
        console.log(data.status)
        console.log(data.data)
        console.log(token);
        }
    }).catch(() => {
        alert("An error occurred on the server")
    })

    return (
        <div>
            Token send
        </div>
    )
}

export default SendToken;
</code>```

答:
You might need to use useEffect() with a second argument as an empty array in your SendToken component.

import {useEffect} from "react";

useEffect(() => {
  fetchData();
  }, []);
```

To make sure that it runs only once.

Title: Axios.post sends request two times

Body:
I have a problem with axios.post sending two times the same request with the same body. I have tried to Google the problem but find nothing. How can I fix it?

App.js

import logo from './logo.svg';
import './App.css';
import Register from "./register";
import SendToken from "./sendToken";
import {BrowserRouter, Routes, Route} from "react-router-dom";
import Confirmation from "./Confirmation";

import {useParams} from "react-router-dom";

function App() {
  return (
      <BrowserRouter>

              <Routes>
                  <Route path="/registration" element={<Register/>}/>
                  <Route path="/confirmation" element={<Confirmation/>}/>
                  <Route path="/account/registrationConfirm/:data" element={<SendToken/>}/>
              </Routes>

      </BrowserRouter>

  );
}

export default App;

sendToken.js

import axios from 'axios';

const SendToken = () => {
    let parts = window.location.href.split('/');
    let length = parts.length;
    let token = parts[length - 1] == '' ? parts[length - 2] : parts[length - 1]

    axios.post("http://localhost:8080/api/v1/registration/registrationConfirm", {token}).then((data) => {
        console.log(data.status)
        console.log(data.data)
        console.log(token);
        }
    }).catch(() => {
        alert("An error occurred on the server")
    })

    return (

            Token send

    )
}

export default SendToken;

Body:
You might need to use useEffect() with a second argument as an empty array in your SendToken component.

import {useEffect} from "react";

useEffect(() => {
  fetchData();
  }, []);

To make sure that it runs only once.


问:
How to make a container extend to the bottom without adding more length

body {
@import url('https://fonts.googleapis.com/css2?family=Roboto+Mono:ital,wght@1,300&display=swap');

background: linear-gradient(to right, yellow, black);

}
.middle-checklist-box-social {
    position: relative;
    top: 0;
    margin: 0 auto;
    height: 35%;
    width: 50%;
    background-color: white;
    padding: 10px 10px 10px 10px;
    bottom: 0%;
}

.checkbox-label-class {
    font-size: 20px;
    font-family: 'Roboto Mono', monospace;
    vertical-align: text-bottom;
}

.giannisCheckbox {
    height: 18px;
    width: 18px;
}

.chkbxLowerLine {
    position: initial;
    height: 2px;
    width: 90%;
    background-color: grey;
    margin-top: 5px;
    margin-bottom: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="middle-checklist-box-social">

    <div class="middle-checklist-box-social">
        <label class="container" >
            <input id="chkbx001" class="giannisCheckbox" type="checkbox" >
            <span class="checkbox-label-class">Social Studies Unit 8 Review (Graded)</span>
        </label>
        <!-- Put in a grey line that seperates the checkbox from the others  -->
        <p class="chkbxLowerLine"></p>
        <!-- New Checkbox here under the line  -->
        <label class="container" >
            <input id="chkbx002" class="giannisCheckbox" type="checkbox">
            <span class="checkbox-label-class">Georgia 3.2.1. GO Project</span>
        </label>

    </div>

</div></code>```

I want a column in the middle to extend to the bottom of the page.  without adding more page content or space where you don't have to scroll to the bottom. I looked around for clues or if anyone has solved this, but of no luck.

I have tried 100vh, but it adds more content making me scroll down which I don't want.

Here is the picture because there is a lot of code in it, but I have position relative,

But I want the end of the white box with the checkbox to reach the bottom of the page

答:
You should set height: 100% to body and html also margin: 0 to body for fit that:

body {
  @import url('https://fonts.googleapis.com/css2?family=Roboto+Mono:ital,wght@1,300&display=swap');
  background: linear-gradient(to right, yellow, black);
  margin: 0;
  height: 100%;
}

* {
  box-sizing: border-box;
}

html {
  height: 100%;
}

.middle-checklist-box-social1 {
  margin: 0 auto;
  height: 100%;
  width: 50%;
  background-color: white;
  padding: 10px;
  border: solid;
}

.middle-checklist-box-social2 {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.checkbox-label-class {
  font-size: 20px;
  font-family: 'Roboto Mono', monospace;
  vertical-align: text-bottom;
}

.giannisCheckbox {
  height: 18px;
  width: 18px;
}

.chkbxLowerLine {
  position: initial;
  height: 2px;
  width: 90%;
  background-color: grey;
  margin-top: 5px;
  margin-bottom: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="middle-checklist-box-social1">

  <div class="middle-checklist-box-social2">
    <label class="container">
            <input id="chkbx001" class="giannisCheckbox" type="checkbox" >
            <span class="checkbox-label-class">Social Studies Unit 8 Review (Graded)</span>
        </label>
    <!-- Put in a grey line that seperates the checkbox from the others  -->
    <p class="chkbxLowerLine"></p>
    <!-- New Checkbox here under the line  -->
    <label class="container">
            <input id="chkbx002" class="giannisCheckbox" type="checkbox">
            <span class="checkbox-label-class">Georgia 3.2.1. GO Project</span>
        </label>
  </div>

</div></code>```

Body:
body {
@import url('https://fonts.googleapis.com/css2?family=Roboto+Mono:ital,wght@1,300&display=swap');

background: linear-gradient(to right, yellow, black);

}
.middle-checklist-box-social {
    position: relative;
    top: 0;
    margin: 0 auto;
    height: 35%;
    width: 50%;
    background-color: white;
    padding: 10px 10px 10px 10px;
    bottom: 0%;
}

.checkbox-label-class {
    font-size: 20px;
    font-family: 'Roboto Mono', monospace;
    vertical-align: text-bottom;
}

.giannisCheckbox {
    height: 18px;
    width: 18px;
}

.chkbxLowerLine {
    position: initial;
    height: 2px;
    width: 90%;
    background-color: grey;
    margin-top: 5px;
    margin-bottom: 5px;
}

            <input id="chkbx001" class="giannisCheckbox" type="checkbox" >
            Social Studies Unit 8 Review (Graded)

            <input id="chkbx002" class="giannisCheckbox" type="checkbox">
            Georgia 3.2.1. GO Project

I want a column in the middle to extend to the bottom of the page.  without adding more page content or space where you don't have to scroll to the bottom. I looked around for clues or if anyone has solved this, but of no luck.

I have tried 100vh, but it adds more content making me scroll down which I don't want.

Here is the picture because there is a lot of code in it, but I have position relative,

But I want the end of the white box with the checkbox to reach the bottom of the page

Body:
You should set height: 100% to body and html also margin: 0 to body for fit that:

body {
  @import url('https://fonts.googleapis.com/css2?family=Roboto+Mono:ital,wght@1,300&display=swap');
  background: linear-gradient(to right, yellow, black);
  margin: 0;
  height: 100%;
}

* {
  box-sizing: border-box;
}

html {
  height: 100%;
}

.middle-checklist-box-social1 {
  margin: 0 auto;
  height: 100%;
  width: 50%;
  background-color: white;
  padding: 10px;
  border: solid;
}

.middle-checklist-box-social2 {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.checkbox-label-class {
  font-size: 20px;
  font-family: 'Roboto Mono', monospace;
  vertical-align: text-bottom;
}

.giannisCheckbox {
  height: 18px;
  width: 18px;
}

.chkbxLowerLine {
  position: initial;
  height: 2px;
  width: 90%;
  background-color: grey;
  margin-top: 5px;
  margin-bottom: 5px;
}

<div class="middle-checklist-box-social1">

  <div class="middle-checklist-box-social2">
    <label class="container">
            <input id="chkbx001" class="giannisCheckbox" type="checkbox" >
            <span class="checkbox-label-class">Social Studies Unit 8 Review (Graded)</span>
        </label>
    <!-- Put in a grey line that seperates the checkbox from the others  -->
    <p class="chkbxLowerLine"></p>
    <!-- New Checkbox here under the line  -->
    <label class="container">
            <input id="chkbx002" class="giannisCheckbox" type="checkbox">
            <span class="checkbox-label-class">Georgia 3.2.1. GO Project</span>
        </label>
  </div>

</div>


问:
How do you remove and add then a class to two list elements on click
How do you remove and add a class to both the below lists simultaneously for the coresponding list item in order on click. eg click the 2nd list item and the change occurs on the second list item on the other list

At the moment using the below I can only get this to happen on one of the li tags on any one click

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

  $("ul.control li, ul.markers li").click(function() {
      $("ul.control li").removeClass("active");
      $(this).addClass("active");
      $("ul.markers li").removeClass("active");
      $(this).addClass("active");

});
</code>```

Here is the markup for the two lists

```<code><ul id="tabs" class="control">
    <li class="active"><a href="#tab1">Tab1</a></li>
    <li><a href="#tab2">Tab2</a></li>
    <li><a href="#tab3">Tab3</a></li>
    <li><a href="#tab4">Tab4</a></li>
</ul>

<ul id="tabs" class="markers">
  <li class="active">1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
</ul>
</code>```

Many thanks in advance for any help.

答:
since jquery is kind enough to expose the index function, you could consider this: </p>

```<code>$(document).ready(function()
{
    $("ul.control li, ul.markers li").click(function()
    {
      var index = $(this).index();
      $("ul.control li").removeClass("active");
      $("ul.markers li").removeClass("active");
      $("ul.control li:eq("+index+")").addClass('active');
      $("ul.markers li:eq("+index+")").addClass('active');
    });
});
</code>```

Body:
How do you remove and add a class to both the below lists simultaneously for the coresponding list item in order on click. eg click the 2nd list item and the change occurs on the second list item on the other list

At the moment using the below I can only get this to happen on one of the li tags on any one click

$(document).ready(function() {

  $("ul.control li, ul.markers li").click(function() {
      $("ul.control li").removeClass("active");
      $(this).addClass("active");
      $("ul.markers li").removeClass("active");
      $(this).addClass("active");

});

Here is the markup for the two lists

Tab1

Tab2

Tab3

Tab4

1

2

3

4

Many thanks in advance for any help.

Body:
since jquery is kind enough to expose the index function, you could consider this:

$(document).ready(function()
{
    $("ul.control li, ul.markers li").click(function()
    {
      var index = $(this).index();
      $("ul.control li").removeClass("active");
      $("ul.markers li").removeClass("active");
      $("ul.control li:eq("+index+")").addClass('active');
      $("ul.markers li:eq("+index+")").addClass('active');
    });
});


问:
What are CGI scripts used for these days?
I'm pretty well up to speed on general web programming languages, but one of the tools I'm working with right now is in CGI. All I can tell is that CGI scripts are quite slow.

Is CGI still commonly used today? If not, what has it been replaced by?

Are there any niche functions in which CGI is still alive and actively used?

答:
CGI and newer technologies are not mutually exclusive. They can be complementary.

My Extreme Precision Binomial Probability Calculator (written in 2020 - 2021) is implemented using both PHP and CGI Perl, working together along with GMP, and a tiny bit of JavaScript.

Perl's support for arbitrary precision arithmetic, and its interface to the GNU Multiple Precision Arithmetic Library (GMP), make it a good language for implementing a tool like this. The same code runs both as a Perl command-line tool and as a CGI module. (In fact, on my server the download link for the binomcalc.pl command-line tool is actually just a Linux symlink to the binomcalc.cgi module.)

PHP (and HTML, CSS & JavaScript) are better for creating the Web interface.

The PHP code generates a CGI include directive, passing parameters to the Perl code. The Perl & GMP code then do the calculations, and generate the results, which appear on the web page.

ContentLicense: CC BY-SA 2.5


问:
I can't figure out the errors in my sql file
I'm using replit for making databases and executing sql statements. I was good at it but now that I'm working with SQL after a long time, I can't recall most of the things I have learned. This file was a part of my lab manual for DBMS. I wrote it all myself but I have no idea why these errors are happening. This are syntactical errors and I tried reading about them but I can't figure out what's actually wrong with this.

Any help will be much appreciated. As I will be able to finish this part of my lab exercise.

Thank you!

The errors are:

Error: near line 27: near "Cat_code": syntax error

Error: near line 38: near "ticket_no": syntax error

Error: near line 61: near "name": syntax error

Error: near line 71: near "place_id": syntax error

The code is here:

```<code>CREATE TABLE Category_Header
(
    Cat_code INTEGER PRIMARY KEY NOT NULL,
    Cate_desc TEXT NOT NULL
);

CREATE TABLE route_header
(
    Route_id INTEGER PRIMARY KEY NOT NULL,
    Route_no INTEGER NOT NULL,
    Cat_code INTEGER NOT NULL,
    Origin TEXT NOT NULL,
    Destination TEXT NOT NULL,
    Fare INTEGER NOT NULL,
    Distance INTEGER NOT NULL,
    Capacity INTEGER NOT NULL,

    FOREIGN KEY (Cat_code)
        REFERENCES Category_Header(Cat_code)
);

CREATE TABLE place_header
(
    place_id int PRIMARY KEY NOT NULL,
    place_name text NOT NULL,
    place_address varchar(100) NOT NULL,
    bus_station text NOT NULL
);

CREATE TABLE fleet_header
(
    fleet_id int PRIMARY KEY NOT NULL,
    day date NOT NULL,
    Route_id int NOT NULL,

    FOREIGN KEY (Route_id)
        REFERENCES route_header(Route_id),

    Cat_code integer NOT NULL,

    FOREIGN KEY (Cat_code)
        REFERENCES Category_Header(Cat_code)
);

CREATE TABLE ticket_Header
(
    fleet_id int NOT NULL,

    FOREIGN KEY (fleet_id)
        REFERENCES fleet_header(fleet_id),

    ticket_no int PRIMARY KEY NOT NULL,
    doi date NOT NULL,
    dot date NOT NULL,
    time_travel time NOT NULL,
    board_place text NOT NULL,
    origin text NOT NULL,

    FOREIGN KEY(origin)
         REFERENCES route_header(origin),

    destination text NOT NULL,

    FOREIGN KEY(destination)
        REFERENCES route_header(destination),
    adults int NOT NULL,
    children int NOT NULL,
    total_fare int NOT NULL,
    Route_id int NOT NULL,

    FOREIGN KEY (Route_id)
        REFERENCES route_header(Route_id)
);

CREATE TABLE ticket_detail
(
    ticket_no int NOT NULL,
    FOREIGN KEY(ticket_no)
        REFERENCES ticket_Header(ticket_no),
    name text NOT NULL,
    sex char NOT NULL,
    age int NOT NULL,
    fare float NOT NULL
);

CREATE TABLE route_detail
(
    Route_id int NOT NULL,
    FOREIGN KEY (Route_id)
         REFERENCES route_header (Route_id),
    place_id int NOT NULL,
    FOREIGN KEY (place_id)
         REFERENCES place_header (place_id),
    nonstop char NOT NULL
);
</code>```

答:
Try moving your FOREIGN KEY after your variables.

```<code>CREATE TABLE Category_Header
(
    Cat_code INTEGER PRIMARY KEY NOT NULL,
    Cate_desc TEXT NOT NULL
);

CREATE TABLE route_header
(
    Route_id INTEGER PRIMARY KEY NOT NULL,
    Route_no INTEGER NOT NULL,
    Cat_code INTEGER NOT NULL,
    Origin TEXT NOT NULL,
    Destination TEXT NOT NULL,
    Fare INTEGER NOT NULL,
    Distance INTEGER NOT NULL,
    Capacity INTEGER NOT NULL,

    FOREIGN KEY (Cat_code)
        REFERENCES Category_Header(Cat_code)
);

CREATE TABLE place_header
(
    place_id int PRIMARY KEY NOT NULL,
    place_name text NOT NULL,
    place_address varchar(100) NOT NULL,
    bus_station text NOT NULL
);

CREATE TABLE fleet_header
(
    fleet_id int PRIMARY KEY NOT NULL,
    day date NOT NULL,
    Route_id int NOT NULL,
    Cat_code integer NOT NULL,
 FOREIGN KEY (Route_id)
        REFERENCES route_header(Route_id)
    FOREIGN KEY (Cat_code)
        REFERENCES Category_Header(Cat_code)
);

CREATE TABLE ticket_Header
(
    fleet_id int NOT NULL,
    ticket_no int PRIMARY KEY NOT NULL,
    doi date NOT NULL,
    dot date NOT NULL,
    time_travel time NOT NULL,
    board_place text NOT NULL,
    origin text NOT NULL,
    destination text NOT NULL,
    adults int NOT NULL,
    children int NOT NULL,
    total_fare int NOT NULL,
    Route_id int NOT NULL,

    FOREIGN KEY (fleet_id)
        REFERENCES fleet_header(fleet_id)
    FOREIGN KEY(origin)
         REFERENCES route_header(origin)
    FOREIGN KEY(destination)
        REFERENCES route_header(destination)
    FOREIGN KEY (Route_id)
        REFERENCES route_header(Route_id)
);

CREATE TABLE ticket_detail
(
    ticket_no int NOT NULL,

    name text NOT NULL,
    sex char NOT NULL,
    age int NOT NULL,
    fare float NOT NULL,
    FOREIGN KEY(ticket_no)
        REFERENCES ticket_Header(ticket_no)
);

CREATE TABLE route_detail
(
    Route_id int NOT NULL,
    place_id int NOT NULL,
    nonstop char NOT NULL,

    FOREIGN KEY (Route_id)
         REFERENCES route_header (Route_id)
    FOREIGN KEY (place_id)
         REFERENCES place_header (place_id)
);
</code>```

Body:
I'm using replit for making databases and executing sql statements. I was good at it but now that I'm working with SQL after a long time, I can't recall most of the things I have learned. This file was a part of my lab manual for DBMS. I wrote it all myself but I have no idea why these errors are happening. This are syntactical errors and I tried reading about them but I can't figure out what's actually wrong with this.

Any help will be much appreciated. As I will be able to finish this part of my lab exercise.

Thank you!

The errors are:

Error: near line 27: near "Cat_code": syntax error

Error: near line 38: near "ticket_no": syntax error

Error: near line 61: near "name": syntax error

Error: near line 71: near "place_id": syntax error

The code is here:

CREATE TABLE Category_Header
(
    Cat_code INTEGER PRIMARY KEY NOT NULL,
    Cate_desc TEXT NOT NULL
);

CREATE TABLE route_header
(
    Route_id INTEGER PRIMARY KEY NOT NULL,
    Route_no INTEGER NOT NULL,
    Cat_code INTEGER NOT NULL,
    Origin TEXT NOT NULL,
    Destination TEXT NOT NULL,
    Fare INTEGER NOT NULL,
    Distance INTEGER NOT NULL,
    Capacity INTEGER NOT NULL,

    FOREIGN KEY (Cat_code)
        REFERENCES Category_Header(Cat_code)
);

CREATE TABLE place_header
(
    place_id int PRIMARY KEY NOT NULL,
    place_name text NOT NULL,
    place_address varchar(100) NOT NULL,
    bus_station text NOT NULL
);

CREATE TABLE fleet_header
(
    fleet_id int PRIMARY KEY NOT NULL,
    day date NOT NULL,
    Route_id int NOT NULL,

    FOREIGN KEY (Route_id)
        REFERENCES route_header(Route_id),

    Cat_code integer NOT NULL,

    FOREIGN KEY (Cat_code)
        REFERENCES Category_Header(Cat_code)
);

CREATE TABLE ticket_Header
(
    fleet_id int NOT NULL,

    FOREIGN KEY (fleet_id)
        REFERENCES fleet_header(fleet_id),

    ticket_no int PRIMARY KEY NOT NULL,
    doi date NOT NULL,
    dot date NOT NULL,
    time_travel time NOT NULL,
    board_place text NOT NULL,
    origin text NOT NULL,

    FOREIGN KEY(origin)
         REFERENCES route_header(origin),

    destination text NOT NULL,

    FOREIGN KEY(destination)
        REFERENCES route_header(destination),
    adults int NOT NULL,
    children int NOT NULL,
    total_fare int NOT NULL,
    Route_id int NOT NULL,

    FOREIGN KEY (Route_id)
        REFERENCES route_header(Route_id)
);

CREATE TABLE ticket_detail
(
    ticket_no int NOT NULL,
    FOREIGN KEY(ticket_no)
        REFERENCES ticket_Header(ticket_no),
    name text NOT NULL,
    sex char NOT NULL,
    age int NOT NULL,
    fare float NOT NULL
);

CREATE TABLE route_detail
(
    Route_id int NOT NULL,
    FOREIGN KEY (Route_id)
         REFERENCES route_header (Route_id),
    place_id int NOT NULL,
    FOREIGN KEY (place_id)
         REFERENCES place_header (place_id),
    nonstop char NOT NULL
);

Body:
Try moving your FOREIGN KEY after your variables.

CREATE TABLE Category_Header
(
    Cat_code INTEGER PRIMARY KEY NOT NULL,
    Cate_desc TEXT NOT NULL
);

CREATE TABLE route_header
(
    Route_id INTEGER PRIMARY KEY NOT NULL,
    Route_no INTEGER NOT NULL,
    Cat_code INTEGER NOT NULL,
    Origin TEXT NOT NULL,
    Destination TEXT NOT NULL,
    Fare INTEGER NOT NULL,
    Distance INTEGER NOT NULL,
    Capacity INTEGER NOT NULL,

    FOREIGN KEY (Cat_code)
        REFERENCES Category_Header(Cat_code)
);

CREATE TABLE place_header
(
    place_id int PRIMARY KEY NOT NULL,
    place_name text NOT NULL,
    place_address varchar(100) NOT NULL,
    bus_station text NOT NULL
);

CREATE TABLE fleet_header
(
    fleet_id int PRIMARY KEY NOT NULL,
    day date NOT NULL,
    Route_id int NOT NULL,
    Cat_code integer NOT NULL,
 FOREIGN KEY (Route_id)
        REFERENCES route_header(Route_id)
    FOREIGN KEY (Cat_code)
        REFERENCES Category_Header(Cat_code)
);

CREATE TABLE ticket_Header
(
    fleet_id int NOT NULL,
    ticket_no int PRIMARY KEY NOT NULL,
    doi date NOT NULL,
    dot date NOT NULL,
    time_travel time NOT NULL,
    board_place text NOT NULL,
    origin text NOT NULL,
    destination text NOT NULL,
    adults int NOT NULL,
    children int NOT NULL,
    total_fare int NOT NULL,
    Route_id int NOT NULL,

    FOREIGN KEY (fleet_id)
        REFERENCES fleet_header(fleet_id)
    FOREIGN KEY(origin)
         REFERENCES route_header(origin)
    FOREIGN KEY(destination)
        REFERENCES route_header(destination)
    FOREIGN KEY (Route_id)
        REFERENCES route_header(Route_id)
);

CREATE TABLE ticket_detail
(
    ticket_no int NOT NULL,

    name text NOT NULL,
    sex char NOT NULL,
    age int NOT NULL,
    fare float NOT NULL,
    FOREIGN KEY(ticket_no)
        REFERENCES ticket_Header(ticket_no)
);

CREATE TABLE route_detail
(
    Route_id int NOT NULL,
    place_id int NOT NULL,
    nonstop char NOT NULL,

    FOREIGN KEY (Route_id)
         REFERENCES route_header (Route_id)
    FOREIGN KEY (place_id)
         REFERENCES place_header (place_id)
);


问:
Custom Sort using Java 8
Consider the dto class below -

```<code>public class RoleDto {

  private String name;

  RoleDto(String name) {
    this.name = name;
  }
}
</code>```

Its instances would contain names like -

```<code>Business Practitioner - Expert
Developer - Expert
Developer - Master
Business Practitioner - Master
Business Practitioner
Developer
Developer - Professional
Business Practitioner - Professional
</code>```

I want to sort the instances such that the order is -

```<code>Business Practitioner - Expert
Business Practitioner - Master
Business Practitioner - Professional
Business Practitioner

Developer - Expert
Developer - Master
Developer - Professional
Developer
</code>```

I have used the code below -

```<code>ArrayList<RoleDto> roles = new ArrayList<>();
roles.add(new RoleDto("Business Practitioner - Expert"));
roles.add(new RoleDto("Developer - Expert"));
roles.add(new RoleDto("Developer - Master"));
roles.add(new RoleDto("Business Practitioner - Master"));
roles.add(new RoleDto("Business Practitioner"));
roles.add(new RoleDto("Developer"));
roles.add(new RoleDto("Developer - Professional"));
roles.add(new RoleDto("Business Practitioner - Professional"));

List<RoleDto> sorted = roles.stream().sorted(comparing(r -> r.getName(),
    comparing((String s) -> !s.contains("-")))).collect(toList());

for(RoleDto r : sorted)
System.out.println(r.getName());
</code>```

However the output is

```<code>Business Practitioner - Expert
Developer - Expert
Developer - Master
Business Practitioner - Master
Developer - Professional
Business Practitioner - Professional
Business Practitioner
Developer
</code>```

Can someone please help me achieve the expected result

答:
It seems you have two dimensions of data at play here.

Business function
"Business Practitioner" & "Programmer".

Level of proficiency
"Expert", "Master", "Professional", and implicitly "Standard", "Basic", "Novice", or some such (shown as no text).

Trying to represent such values as text is clumsy, and ignores the features built into Java for such a purpose.

If all the values are known at compile-time, make an enum for each dimension. An enum is a class defined in such a way as to automatically instantiate and name several objects when the class is loaded.

```<code>public enum Function { BUSINESS_PRACTITIONER, PROGRAMMER ; }
public enum Proficiency { EXPERT, MASTER, PROFESSIONAL, NOVICE; }
</code>```

Pull those together into a single class. The primary purpose of this class is to carry data transparently and immutably. So we can define briefly as a record.

```<code>public record Role( Function function , Proficiency proficiency ) { }
</code>```

We want instances of Role to sort in two levels, first by Function, then by Proficiency. So we need to implement the Comparable interface on our record Role.

```<code>public record Role( Function function , Proficiency proficiency ) implements Comparable<Role> { … }
</code>```

The sort order of each is the order in which the named objects are declared. So we can write the necessary compareTo method using a Comparator object. We define that Comparator object using convenience methods comparing and thenComparing, passing each a method reference. We mark this object as a singleton using static, for frequent re-use.

```<code>private static Comparator < Role > comparator =
        Comparator
                .comparing( Role :: function )
                .thenComparing( Role :: proficiency );
</code>```

We use that comparator in our compareTo method.

```<code>@Override public int compareTo ( Role other ) { return Role.comparator.compare( this , other ); }
</code>```

We instantiate a role object like this:

```<code>Role progPro = new Role( Function.PROGRAMMER , Proficiency.PROFESSIONAL );
</code>```

If need be, we can make a set of all possible roles.

NavigableSet < Role > allPossibleRoles = new TreeSet();
for ( Function function : Function.values() )
{
    for ( Proficiency proficiency : Proficiency.values() )
    {
        allPossibleRoles.add( new Role( function , proficiency ) );
    }
}
System.out.println( "allPossibleRoles = " + allPossibleRoles );
```
<p>We can see these are listed in the order dictated by the Question.</p>
<blockquote>
<p>allPossibleRoles = [Role[function=BUSINESS_PRACTITIONER, proficiency=EXPERT], Role[function=BUSINESS_PRACTITIONER, proficiency=MASTER], Role[function=BUSINESS_PRACTITIONER, proficiency=PROFESSIONAL], Role[function=BUSINESS_PRACTITIONER, proficiency=NOVICE], Role[function=PROGRAMMER, proficiency=EXPERT], Role[function=PROGRAMMER, proficiency=MASTER], Role[function=PROGRAMMER, proficiency=PROFESSIONAL], Role[function=PROGRAMMER, proficiency=NOVICE]]</p>
</blockquote>
<p>Lastly, we need to emit the text seen in the Question.</p>
<p>Modify the enum classes to take an argument for a display name.</p>
<pre class="lang-java prettyprint-override"><code>public enum Function
{
    BUSINESS_PRACTITIONER( "Business Practitioner" ), PROGRAMMER( "Programmer" );

    private final String displayName;

    // Constructor
    Function ( final String displayName ) { this.displayName = displayName; }

    public String getDisplayName ( ) { return displayName; }
}
</code>```

And the other enum.

public enum Proficiency
{
    EXPERT( "Expert" ), MASTER( "Master" ), PROFESSIONAL( "Professional" ), NOVICE( "" );

    private final String displayName;

    // Constructor
    Proficiency ( String displayName ) { this.displayName = displayName; }

    public String getDisplayName ( ) { return displayName; }
}
```
<p>Modify the <code>Role</code> record to generate text in desired format with a <code>getDisplayName</code> method.</p>
<pre class="lang-java prettyprint-override"><code>import java.util.Comparator;

public record Role( Function function , Proficiency proficiency ) implements Comparable < Role >
{
    @Override
    public int compareTo ( Role other ) { return Role.comparator.compare( this , other ); }

    private static Comparator < Role > comparator =
            Comparator
                    .comparing( Role :: function )
                    .thenComparing( Role :: proficiency );

    public String getDisplayName ( )
    {
        String x = this.function.getDisplayName();
        String y = this.proficiency.getDisplayName().isBlank() ? "" : " - ";
        String z = this.proficiency.getDisplayName();
        return x + y + z;
    }
}
</code>```

Example usage.

NavigableSet < Role > allPossibleRoles = new TreeSet();  // NavigableSet/TreeSet keeps elements sorted.
for ( Function function : Function.values() )
{
    for ( Proficiency proficiency : Proficiency.values() )
    {
        allPossibleRoles.add( new Role( function , proficiency ) );
    }
}

// Dump to console.
for ( Role role : allPossibleRoles )
{
    System.out.println( "role.getDisplayName() = " + role.getDisplayName() );
}
```
<pre class="lang-none prettyprint-override"><code>role.getDisplayName() = Business Practitioner - Expert
role.getDisplayName() = Business Practitioner - Master
role.getDisplayName() = Business Practitioner - Professional
role.getDisplayName() = Business Practitioner
role.getDisplayName() = Programmer - Expert
role.getDisplayName() = Programmer - Master
role.getDisplayName() = Programmer - Professional
role.getDisplayName() = Programmer
</code>```

Title: Custom Sort using Java 8

Body:
Consider the dto class below -

public class RoleDto {

  private String name;

  RoleDto(String name) {
    this.name = name;
  }
}

Its instances would contain names like -

Business Practitioner - Expert
Developer - Expert
Developer - Master
Business Practitioner - Master
Business Practitioner
Developer
Developer - Professional
Business Practitioner - Professional

I want to sort the instances such that the order is -

Business Practitioner - Expert
Business Practitioner - Master
Business Practitioner - Professional
Business Practitioner

Developer - Expert
Developer - Master
Developer - Professional
Developer

I have used the code below -

ArrayList<RoleDto> roles = new ArrayList<>();
roles.add(new RoleDto("Business Practitioner - Expert"));
roles.add(new RoleDto("Developer - Expert"));
roles.add(new RoleDto("Developer - Master"));
roles.add(new RoleDto("Business Practitioner - Master"));
roles.add(new RoleDto("Business Practitioner"));
roles.add(new RoleDto("Developer"));
roles.add(new RoleDto("Developer - Professional"));
roles.add(new RoleDto("Business Practitioner - Professional"));

List<RoleDto> sorted = roles.stream().sorted(comparing(r -> r.getName(),
    comparing((String s) -> !s.contains("-")))).collect(toList());

for(RoleDto r : sorted)
System.out.println(r.getName());

However the output is

Business Practitioner - Expert
Developer - Expert
Developer - Master
Business Practitioner - Master
Developer - Professional
Business Practitioner - Professional
Business Practitioner
Developer

Can someone please help me achieve the expected result

Body:
It seems you have two dimensions of data at play here.

Business function
"Business Practitioner" & "Programmer".

Level of proficiency
"Expert", "Master", "Professional", and implicitly "Standard", "Basic", "Novice", or some such (shown as no text).

Trying to represent such values as text is clumsy, and ignores the features built into Java for such a purpose.

If all the values are known at compile-time, make an enum for each dimension. An enum is a class defined in such a way as to automatically instantiate and name several objects when the class is loaded.

public enum Function { BUSINESS_PRACTITIONER, PROGRAMMER ; }
public enum Proficiency { EXPERT, MASTER, PROFESSIONAL, NOVICE; }

Pull those together into a single class. The primary purpose of this class is to carry data transparently and immutably. So we can define briefly as a record.

public record Role( Function function , Proficiency proficiency ) { }

We want instances of Role to sort in two levels, first by Function, then by Proficiency. So we need to implement the Comparable interface on our record Role.

public record Role( Function function , Proficiency proficiency ) implements Comparable<Role> { … }

The sort order of each is the order in which the named objects are declared. So we can write the necessary compareTo method using a Comparator object. We define that Comparator object using convenience methods comparing and thenComparing, passing each a method reference. We mark this object as a singleton using static, for frequent re-use.

private static Comparator < Role > comparator =
        Comparator
                .comparing( Role :: function )
                .thenComparing( Role :: proficiency );

We use that comparator in our compareTo method.

@Override public int compareTo ( Role other ) { return Role.comparator.compare( this , other ); }

We instantiate a role object like this:

Role progPro = new Role( Function.PROGRAMMER , Proficiency.PROFESSIONAL );

If need be, we can make a set of all possible roles.

NavigableSet < Role > allPossibleRoles = new TreeSet();
for ( Function function : Function.values() )
{
    for ( Proficiency proficiency : Proficiency.values() )
    {
        allPossibleRoles.add( new Role( function , proficiency ) );
    }
}
System.out.println( "allPossibleRoles = " + allPossibleRoles );

We can see these are listed in the order dictated by the Question.

allPossibleRoles = [Role[function=BUSINESS_PRACTITIONER, proficiency=EXPERT], Role[function=BUSINESS_PRACTITIONER, proficiency=MASTER], Role[function=BUSINESS_PRACTITIONER, proficiency=PROFESSIONAL], Role[function=BUSINESS_PRACTITIONER, proficiency=NOVICE], Role[function=PROGRAMMER, proficiency=EXPERT], Role[function=PROGRAMMER, proficiency=MASTER], Role[function=PROGRAMMER, proficiency=PROFESSIONAL], Role[function=PROGRAMMER, proficiency=NOVICE]]

Lastly, we need to emit the text seen in the Question.

Modify the enum classes to take an argument for a display name.

public enum Function
{
    BUSINESS_PRACTITIONER( "Business Practitioner" ), PROGRAMMER( "Programmer" );

    private final String displayName;

    // Constructor
    Function ( final String displayName ) { this.displayName = displayName; }

    public String getDisplayName ( ) { return displayName; }
}

And the other enum.

public enum Proficiency
{
    EXPERT( "Expert" ), MASTER( "Master" ), PROFESSIONAL( "Professional" ), NOVICE( "" );

    private final String displayName;

    // Constructor
    Proficiency ( String displayName ) { this.displayName = displayName; }

    public String getDisplayName ( ) { return displayName; }
}

Modify the Role record to generate text in desired format with a getDisplayName method.

import java.util.Comparator;

public record Role( Function function , Proficiency proficiency ) implements Comparable < Role >
{
    @Override
    public int compareTo ( Role other ) { return Role.comparator.compare( this , other ); }

    private static Comparator < Role > comparator =
            Comparator
                    .comparing( Role :: function )
                    .thenComparing( Role :: proficiency );

    public String getDisplayName ( )
    {
        String x = this.function.getDisplayName();
        String y = this.proficiency.getDisplayName().isBlank() ? "" : " - ";
        String z = this.proficiency.getDisplayName();
        return x + y + z;
    }
}

Example usage.

NavigableSet < Role > allPossibleRoles = new TreeSet();  // NavigableSet/TreeSet keeps elements sorted.
for ( Function function : Function.values() )
{
    for ( Proficiency proficiency : Proficiency.values() )
    {
        allPossibleRoles.add( new Role( function , proficiency ) );
    }
}

// Dump to console.
for ( Role role : allPossibleRoles )
{
    System.out.println( "role.getDisplayName() = " + role.getDisplayName() );
}

role.getDisplayName() = Business Practitioner - Expert
role.getDisplayName() = Business Practitioner - Master
role.getDisplayName() = Business Practitioner - Professional
role.getDisplayName() = Business Practitioner
role.getDisplayName() = Programmer - Expert
role.getDisplayName() = Programmer - Master
role.getDisplayName() = Programmer - Professional
role.getDisplayName() = Programmer


问:
RubyMine dont support rbs
I want to try RBS in RubyMine,so I follow this link: https://www.jetbrains.com/help/ruby/rbs.html

but in my RubyMine,rbs not work
rbs not work

in video there's new rbs file but no in my RubyMine
no menu

my RubyMine version: 2021.3.2
ruby version:3.10
OS:MacOS 12.1

thanks

答: this is the error image,looks like the RubyMine dont recognize rbs file

Title: RubyMine dont support rbs


问:
 tags showing different behaviour
When I'm using
 tags to create horizontal rows then the behavior is not uniform i.e. all the
s (in my case) are displaying alternate background color.

Also, I've tested in Chrome and opera and the zoom level was 100% at the time of testing.

For reference, below is the image:-

hr{
    border-style: none;
    width: 10%;
    height: 2px;
    background-color: rgba(0, 0, 0, 0.253) ;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><hr>
<br>

<hr>
<br>

<hr>
<br>

<hr>
<br>

<hr></code>```

答:
Try use relative units like EM instead of PX, it magically works.

hr{
    border-style: none;
    width: 10%;
    height: 0.1rem;
    background-color: rgba(0, 0, 0, 0.253) ;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><hr>
<br>

<hr>
<br>

<hr>
<br>

<hr>
<br>

<hr></code>```

You can use https://www.w3schools.com/cssref/css_pxtoemconversion.asp to convert PX to EM. Using relative units make your site more user-friendly to most of the displays.

Title: <hr> tags showing different behaviour

Body:
Try use relative units like EM instead of PX, it magically works.

hr{
    border-style: none;
    width: 10%;
    height: 0.1rem;
    background-color: rgba(0, 0, 0, 0.253) ;
}

<hr>
<br>

<hr>
<br>

<hr>
<br>

<hr>
<br>

<hr>

You can use https://www.w3schools.com/cssref/css_pxtoemconversion.asp to convert PX to EM. Using relative units make your site more user-friendly to most of the displays.


问:
Is it possible to trigger a Livewire modal component with Bootstrap?
I'm trying to render a modal that gets triggered by a button, so that I can then include payment elements in this modal and allow the user to begin to make payment. However, most Livewire modals I've seen - here, for example - use Livewire events to do the toggling of the model, which both requires adding ugly logic to the view and seems like it would still be slower than anything client-side.

It seems to me like it would be faster to allow Bootstrap to trigger the modal via its own JavaScript (using data-bs-* attributes), and only make use of Livewire when actually loading the content into the modal. Is this approach possible, or do Livewire components have to be loaded via Livewire in order to be populated by it?

答: Using the LiveWire is logical when you need to exchange information with the server and need to request and respond via HTTP protocol. LiveWire has replaced ajax or something like axios. So it’s better you use a modal bootstrap or any element handled on front and use livewire when you want to do something on the server for example fetch or save data via database. You can use livewire components in any blade as any part of your project.</p>


问:
Read txt file in Resorces folder using vb.net
My goal is to store a txt file in the Resources folder of a VB.Net application

I added the Dir.txt file with Project > Project Properties > Resources > Add Resources > Add Existing File.

I can see the file and can read it using a very odd few lines of code that involve using a hard coded path. Not ideal.

I have included some code that I have tested with NO RESULTS

I can use the OpenFileDialog but I do not want to go Fishing for the file!

Just Click a Button and display the file in the RichTextBox

Because the Project has a SQLite I have considered adding the file to its own table during the DB creation function

My two Questions are

If the file is in the Resources Folder when I package it with Inno Setup will the file be in the exe file?

Can we explain a better way to accomplish clicking a button and adding the file to the RichTextBox?

And YES these are imported

```<code>Imports System.IO
Imports System.Reflection

  Private Sub btnGetCode_Click(sender As Object, e As EventArgs) Handles btnGetCode.Click
    'Dim openFileDialog As OpenFileDialog = New OpenFileDialog()
    'Dim dr As DialogResult = openFileDialog.ShowDialog()
    'If dr = System.Windows.Forms.DialogResult.OK Then
    '    Dim openPath As String = OpenFileDialog.FileName
    '    rtbViewCode.Text = File.ReadAllText(openPath)
    'End If '' This works but I do not want to go Fishing for the File

    'Why Does this code BELOW FAIL
    'Dim openPath = Path.Combine(Application.StartupPath, "Resource.Dir.txt")
    'rtbViewCode.Text = File.ReadAllText(openPath)

    'Why Does this code BELOW FAIL
    'Dim assmbly As Assembly = Assembly.GetExecutingAssembly()
    'Dim reader As New StreamReader(assmbly.GetManifestResourceStream("frmViewFile.vb.Dir.txt"))
    'rtbViewCode.Text = reader.ReadToEnd

    'While this Code WORKS
    Dim openP As String = "C:\Users\Dwight\source\repos\TestTwoGrids\TestTwoGrids\Resources\Dir.txt"
    rtbViewCode.Text = File.ReadAllText(openP)

    'End If
End Sub
</code>```

答:
If you have already added the Dir.txt resource file (Project > Project Properties > Resources > Add Resources > Add Existing File) and assigned an Alias, let's say DirTxt

The only thing left to do is to insert its content to the RichBox as follows:

```<code>Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    RichTextBox1.Text = My.Resources.DirTxt
End Sub
</code>```

And yes, once you compile it, the resources are embodied inside the executable file.

If this helps you, please mark it as the answer.

Body:
My goal is to store a txt file in the Resources folder of a VB.Net application

I added the Dir.txt file with Project > Project Properties > Resources > Add Resources > Add Existing File.

I can see the file and can read it using a very odd few lines of code that involve using a hard coded path. Not ideal.

I have included some code that I have tested with NO RESULTS

I can use the OpenFileDialog but I do not want to go Fishing for the file!

Just Click a Button and display the file in the RichTextBox

Because the Project has a SQLite I have considered adding the file to its own table during the DB creation function

My two Questions are

If the file is in the Resources Folder when I package it with Inno Setup will the file be in the exe file?

Can we explain a better way to accomplish clicking a button and adding the file to the RichTextBox?

And YES these are imported

Imports System.IO
Imports System.Reflection

  Private Sub btnGetCode_Click(sender As Object, e As EventArgs) Handles btnGetCode.Click
    'Dim openFileDialog As OpenFileDialog = New OpenFileDialog()
    'Dim dr As DialogResult = openFileDialog.ShowDialog()
    'If dr = System.Windows.Forms.DialogResult.OK Then
    '    Dim openPath As String = OpenFileDialog.FileName
    '    rtbViewCode.Text = File.ReadAllText(openPath)
    'End If '' This works but I do not want to go Fishing for the File

    'Why Does this code BELOW FAIL
    'Dim openPath = Path.Combine(Application.StartupPath, "Resource.Dir.txt")
    'rtbViewCode.Text = File.ReadAllText(openPath)

    'Why Does this code BELOW FAIL
    'Dim assmbly As Assembly = Assembly.GetExecutingAssembly()
    'Dim reader As New StreamReader(assmbly.GetManifestResourceStream("frmViewFile.vb.Dir.txt"))
    'rtbViewCode.Text = reader.ReadToEnd

    'While this Code WORKS
    Dim openP As String = "C:\Users\Dwight\source\repos\TestTwoGrids\TestTwoGrids\Resources\Dir.txt"
    rtbViewCode.Text = File.ReadAllText(openP)

    'End If
End Sub

Body:
If you have already added the Dir.txt resource file (Project > Project Properties > Resources > Add Resources > Add Existing File) and assigned an Alias, let's say DirTxt

The only thing left to do is to insert its content to the RichBox as follows:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    RichTextBox1.Text = My.Resources.DirTxt
End Sub

And yes, once you compile it, the resources are embodied inside the executable file.

If this helps you, please mark it as the answer.


问:
Java add new functions to library class
The problem:
application uses some library. Like:

```<code>ClassA a=new ClassA();
</code>```

In this library classA uses classB - e.g. call some method from classB.
I need to change how this method works.
Is it possible do without using AOP?
Thanks.

答: You can subclass ClassA if ClassA is not final.  You should probably download the source for the library and look at the internals to see how it works -- only create a subclass as a last resort -- you don't want to break the library.</p>

Title: Java add new functions to library class

Body:
The problem:
application uses some library. Like:

ClassA a=new ClassA();

In this library classA uses classB - e.g. call some method from classB.
I need to change how this method works.
Is it possible do without using AOP?
Thanks.


问:
Where should I put the complex queries using the Repository Pattern?
I have an application in which I use Entity Framework, and I have a class called BaseRepository<T> with a few basic CRUD methods, such as (Get, GetAll, Update, Delete, Insert), and from this class I generate my specific repositories, such like BaseRepository <Products>, BaseRepository<People>, BaseRepository<Countries> and many more.

The problem is that, when I have a complex logic in the service, that involves making joins of several tables and that does not return an entity, but an object that is handled in the service (it is neither a DB entity nor a DTO), I find that repositories don't help me much with just basic CRUD operations.

Where should I put this query complex? in which of the repositories should it be? How do I join these repositories? The problem is that I see that the repositories handle a single entity, what should I do in this case? I've been doing some research and read that returning IQueryable<T> is bad practice, so I rule out that possibility of sending IQueryable<T> of the tables I'm going to join the service and do it there.

I've researched and found no clear answer. I would like to know how and where these complex queries are organized, since I also want to respect the responsibility of each repository with its respective entity.

答:
Its hard to answer without having a code to understand what you want to achieve, hopefully my answer gives you an idea on how you can use abstract classes to override your Queryable Collection. If your requirement is more complex, can you provide more information with example code.

Create your BaseRepository like this -

```<code>public abstract class BaseRepository<T>
{
    public IQueryable<T> Collection { get; set; }
    public readonly DbContext _context;

    public BaseRepository(DbContext context)
    {
        _context = context;
        Collection = SetQueryableCollection();
    }

    public virtual IQueryable<T> SetQueryableCollection() => _context.Set<T>();

    // CRUD Operations here for e.g. -
    public virtual async Task<List<T>> Get()
    {
        return await Collection.ToListAsync();
    }
}
</code>```

Now, the class that inherits this -

```<code>public class ProductRepository : BaseRepository<Product>
{
    public ProductRepository(MyContext context) : base(context)
    {
    }

    //now override the method that sets the collection
    public override IQueryable<Product> SetQueryableCollection() =>
        _context.Set<Product>().Include(p => p.Brand).ThenInclude(...);

    // things to keep in mind, the _context is public in the way I've done it. You can change that and directly expose the Collection and set it to your need per entity type.
}
</code>```

So now your GET method uses the overriden method to set the Collection.

Body:
Its hard to answer without having a code to understand what you want to achieve, hopefully my answer gives you an idea on how you can use abstract classes to override your Queryable Collection. If your requirement is more complex, can you provide more information with example code.

Create your BaseRepository like this -

public abstract class BaseRepository<T>
{
    public IQueryable<T> Collection { get; set; }
    public readonly DbContext _context;

    public BaseRepository(DbContext context)
    {
        _context = context;
        Collection = SetQueryableCollection();
    }

    public virtual IQueryable<T> SetQueryableCollection() => _context.Set<T>();

    // CRUD Operations here for e.g. -
    public virtual async Task<List<T>> Get()
    {
        return await Collection.ToListAsync();
    }
}

Now, the class that inherits this -

public class ProductRepository : BaseRepository<Product>
{
    public ProductRepository(MyContext context) : base(context)
    {
    }

    //now override the method that sets the collection
    public override IQueryable<Product> SetQueryableCollection() =>
        _context.Set<Product>().Include(p => p.Brand).ThenInclude(...);

    // things to keep in mind, the _context is public in the way I've done it. You can change that and directly expose the Collection and set it to your need per entity type.
}

So now your GET method uses the overriden method to set the Collection.


问:
Getting Logs from GCP Alerting
I am setting up alerting for GCP VMs. It works fine for email, but I'm trying to use the webhook option.  It shows the incident was caught and the webhook triggered.  But I don't see an alert on the receiving end.  I don't know how to debug since GCP webhooks seems like a blackbox.  Does anybody know where I can see the log for the actual webhook call?  I'm not sure it is receiving an alert ID from the webhook call.

I'm using this document:

https://cloud.google.com/monitoring/alerts/using-channels-api#api-create-channels

Thanks!

Gary

答:
You configure a webhook notification channel and expect to be notified when incidents occur, but you might not receive any notifications because of following reasons:

1.Private endpoint

You can't use webhooks for notifications unless the endpoint is public.
To resolve this situation, use Pub/Sub notifications combined with a pull subscription  to that notification topic.

When you configure a Pub/Sub notification channel, incident notifications are sent to a Pub/Sub queue that has Identity and Access Management controls. Any service that can query for, or listen to, a Pub/Sub topic can consume these notifications. For example, applications running on App Engine, Cloud Run, or Compute Engine virtual machines can consume these notifications.

2.Public endpoint

To identify why the delivery failed, examine your Cloud Logging log entries for failure information.

For example, you can search for log entries for the notification channel resource by using the Logs Explorer, with a filter like the following:

```<code>resource.type="stackdriver_notification_channel"
</code>```

NOTE : Also check whether you have been mentioned in the recipient list, if not mentioned you will not be able to see the alert on the receiving end.

Refer Troubleshooting Alerting policies for information.

Title: Getting Logs from GCP Alerting

Body:
You configure a webhook notification channel and expect to be notified when incidents occur, but you might not receive any notifications because of following reasons:

1.Private endpoint

You can't use webhooks for notifications unless the endpoint is public.
To resolve this situation, use Pub/Sub notifications combined with a pull subscription  to that notification topic.

When you configure a Pub/Sub notification channel, incident notifications are sent to a Pub/Sub queue that has Identity and Access Management controls. Any service that can query for, or listen to, a Pub/Sub topic can consume these notifications. For example, applications running on App Engine, Cloud Run, or Compute Engine virtual machines can consume these notifications.

2.Public endpoint

To identify why the delivery failed, examine your Cloud Logging log entries for failure information.

For example, you can search for log entries for the notification channel resource by using the Logs Explorer, with a filter like the following:

resource.type="stackdriver_notification_channel"

NOTE : Also check whether you have been mentioned in the recipient list, if not mentioned you will not be able to see the alert on the receiving end.

Refer Troubleshooting Alerting policies for information.


问:
How to add ripple effect?
How can I achieve ripple effect like this in PyQt5?

答:
try this :)</p>
```<code>import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

class Button(QPushButton):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.r = 0
        self.timer = QTimer(interval=70, timeout=self.set_radius)
        self.countr = 0
    def set_radius(self):
        self.countr += 1
        if self.r < self.width() / 2:
            self.r += self.width() /10
        else:
            self.timer.stop()
            self.r = 0
            self.countr = 0
        self.update()
    def mousePressEvent(self,event):
        super().mousePressEvent(event)
        self.x,self.y = event.x(),event.y()
        self.timer.start()
    def paintEvent(self, event):
        super().paintEvent(event)
        if self.r:
            self.qp = QPainter(self)
            self.qp.setBrush(QColor(255, 255, 255, 127))
            self.qp.setRenderHint(QPainter.Antialiasing)
            # delete this lines if don't like light effect
            #///
            if self.countr == 4:
                self.qp.setOpacity(0.8)

            else:
                self.qp.setOpacity(0.3)
                self.qp.setPen(QPen(QColor(Qt.transparent), 0))
            #\\\
            #self.qp.setOpacity(0.3)
            #self.qp.setPen(QPen(QColor(Qt.transparent), 0))
            self.qp.drawEllipse(QPoint(self.x,self.y), self.r, self.r)
            self.qp.end()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = QWidget()
    layout = QVBoxLayout(window)
    layout.addWidget(Button('Start'))
    window.setStyleSheet('''
    QPushButton {
        color: #fff;
        background-color: #09e;
        padding: 20px;
        font-size: 24pt;
        border: none;
    }
    QPushButton:pressed {
        color: #ddd;
    }''')
    window.show()
    sys.exit(app.exec_())
</code>```

Title: How to add ripple effect?

Body:
try this :)

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

class Button(QPushButton):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.r = 0
        self.timer = QTimer(interval=70, timeout=self.set_radius)
        self.countr = 0
    def set_radius(self):
        self.countr += 1
        if self.r < self.width() / 2:
            self.r += self.width() /10
        else:
            self.timer.stop()
            self.r = 0
            self.countr = 0
        self.update()
    def mousePressEvent(self,event):
        super().mousePressEvent(event)
        self.x,self.y = event.x(),event.y()
        self.timer.start()
    def paintEvent(self, event):
        super().paintEvent(event)
        if self.r:
            self.qp = QPainter(self)
            self.qp.setBrush(QColor(255, 255, 255, 127))
            self.qp.setRenderHint(QPainter.Antialiasing)
            # delete this lines if don't like light effect
            #///
            if self.countr == 4:
                self.qp.setOpacity(0.8)

            else:
                self.qp.setOpacity(0.3)
                self.qp.setPen(QPen(QColor(Qt.transparent), 0))
            #\\\
            #self.qp.setOpacity(0.3)
            #self.qp.setPen(QPen(QColor(Qt.transparent), 0))
            self.qp.drawEllipse(QPoint(self.x,self.y), self.r, self.r)
            self.qp.end()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = QWidget()
    layout = QVBoxLayout(window)
    layout.addWidget(Button('Start'))
    window.setStyleSheet('''
    QPushButton {
        color: #fff;
        background-color: #09e;
        padding: 20px;
        font-size: 24pt;
        border: none;
    }
    QPushButton:pressed {
        color: #ddd;
    }''')
    window.show()
    sys.exit(app.exec_())


问:
Why a PHP warning appearing in Chrome but not in any other browser?
I'm writing a web application in PHP, and I'm getting the following warning in Google Chrome only:

Warning: Cannot use a scalar value as an array in
  M:\xampp\htdocs\MyProjectTitle\php\classes.php on line 18

Background: Please note that the web app works just fine in all browsers I tested (Firefox, Chrome, IE), but the warning appearing in Chrome is bugging the hell outta me.

Notes: I have tried restarting Chrome and clearing the Chrome cache. I have tried restarting the computer. I have tried searching the source code in FF and IE to see if the warning was just hidden, but to no avail. The warning is only popping up in Google Chrome, and I have no idea why.

UPDATE: Even though Safari also uses WebKit, it does not show the PHP warning. For some reason, Chrome is the only one that has the PHP warning. Weird stuff!

UPDATE: Here's the first 21 lines of code:

```<code>class Presenter {
    public function includeFile($filePath) {
        if (is_readable($filePath)) {
            include $filePath;
        } else {
            echo '<p><strong>ERROR 404</strong></p>';
            echo '<p>The resource you requested could not be located.</p>';
        }
    }

    public function sanitize($string) {
        return preg_replace("/\s/","_",$string);
    }

    public function set($varname,$value) {
        $this->$varname = $value;
        $_SESSION[$this->name][$varname] = $value;

        return $this;   // enables chaining!
    }

    // And there's more code after this, but I have cut it out here.
}
</code>```

Note: The above code is inside a PHP class.

UPDATE: I know exactly what lines of code are causing the warning in Chrome (although I still have no clue why Chrome is the only browser that shows the warning). Since my webapp works perfectly despite the warning in Chrome, I have used @ to suppress the warnings in Chrome (I'll fix the warning later).

答: This usually happens because you do something browser-specific(maybe you do something IE specific, and firerfox-specific, but forgot to add a "default" case for other browsers?)</p>

Body:
I'm writing a web application in PHP, and I'm getting the following warning in Google Chrome only:

Warning: Cannot use a scalar value as an array in
  M:\xampp\htdocs\MyProjectTitle\php\classes.php on line 18

Background: Please note that the web app works just fine in all browsers I tested (Firefox, Chrome, IE), but the warning appearing in Chrome is bugging the hell outta me.

Notes: I have tried restarting Chrome and clearing the Chrome cache. I have tried restarting the computer. I have tried searching the source code in FF and IE to see if the warning was just hidden, but to no avail. The warning is only popping up in Google Chrome, and I have no idea why.

UPDATE: Even though Safari also uses WebKit, it does not show the PHP warning. For some reason, Chrome is the only one that has the PHP warning. Weird stuff!

UPDATE: Here's the first 21 lines of code:

class Presenter {
    public function includeFile($filePath) {
        if (is_readable($filePath)) {
            include $filePath;
        } else {
            echo '
ERROR 404
';
            echo '
The resource you requested could not be located.
';
        }
    }

    public function sanitize($string) {
        return preg_replace("/\s/","_",$string);
    }

    public function set($varname,$value) {
        $this->$varname = $value;
        $_SESSION[$this->name][$varname] = $value;

        return $this;   // enables chaining!
    }

    // And there's more code after this, but I have cut it out here.
}

Note: The above code is inside a PHP class.

UPDATE: I know exactly what lines of code are causing the warning in Chrome (although I still have no clue why Chrome is the only browser that shows the warning). Since my webapp works perfectly despite the warning in Chrome, I have used @ to suppress the warnings in Chrome (I'll fix the warning later).


问:
p4python check if any actions are being run
I have a threaded timer running to disconnect from p4 after a certain amount of time (because perforce will auto timeout in our application and fails to reconnect).  I want to make sure that I do not disconnect if any long action is running (like downloading a large file).  Are there any p4 commands that can check if there are currently commands being run.

Thanks

答:
You can run p4 monitor show to check from the server side if any commands are running.

For your use case, though, it would be more straightforward for your script to simply keep track of its own run() calls, since anything you care about will take place in the context of one of those calls.  It's generally good practice to close your connection once you're done invoking commands with run(), since holding idle connections open can potentially DDoS the server if enough client instances do it.