问:
How do I display the db models in the User view of Flask-Admin
I have created an admin panel using Flask-Admin, and created three non admin users. I want to display a database table called as Usertest inside the users section of the panel. Right now for the admin (super user part) I am able to display all the database tables. I want to display one or two tables in the user view of the admin panel, how do i go about it ?

Here is the model_views.py code

```<code>class MyModelView(sqla.ModelView):
    def is_accessible(self):
        if not current_user.is_active or not current_user.is_authenticated:
            return False
        if current_user.has_role('superuser') :
            return True
        return False

    def _handle_view(self, name, **kwargs):
        """
        Override builtin _handle_view in order to redirect users
          when a view is not accessible.
        """
        if not self.is_accessible():
            if current_user.is_authenticated:
                # permission denied
                abort(403)
            else:
                # login
                return redirect(url_for('security.login', next=request.url))

class CarUserView():
    column_display_pk = True
    form_columns = ['id', 'desc']
    column_searchable_list = ['desc']
    column_filters = ['id']
    can_create = True
    can_edit = True
    can_delete = False  # disable model deletion
    can_view_details = True
    page_size = 2  # pagination
    create_modal = True
    edit_modal = True
    can_export = True

class CarAdminView(MyModelView):
    column_display_pk = True
    form_columns = ['id', 'desc']
    column_searchable_list = ['desc']
    column_filters = ['id']
    column_editable_list = ['desc']
    can_create = True
    can_edit = True
    can_delete = True
    can_view_details = True
    page_size = 2
    create_modal = True
    edit_modal = True
    can_export = True

</code>```

and this is the app.py code :

```<code>class Car(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    desc = db.Column(db.String(50))

    def __str__(self):
        return self.desc
class usertest(db.Model):
    id=db.Column(db.Integer, primary_key=True, autoincrement=True)
    desc=db.Column(db.String(50))

# --------------------------------
# MODEL VIEW CLASSES
# --------------------------------
from model_views import (
    CarAdminView, CarUserView, MyModelView
)

# --------------------------------
# FLASK VIEWS / ROUTES
# --------------------------------
@app.route('/')
def index():
    return render_template('index.html')
    #return redirect("/admin")

# --------------------------------
# CREATE FLASK ADMIN
# --------------------------------
admin = flask_admin.Admin(
    app,
    '',
    base_template='my_master.html',
    template_mode='bootstrap3',
)
admin.add_view(CarAdminView(Car, db.session))
admin.add_view(MyModelView(Profile, db.session))
admin.add_view(MyModelView(Username, db.session))
admin.add_view(CarUserView(usertest,db.session))

</code>```

If i change the conditions in MyModelView such that it displays the table for both admin and non admin user all the tables are being displayed, which is not necessary. I expected it to only display the specified tables for the user view. Please help me out. Thank you.

Body:
I have created an admin panel using Flask-Admin, and created three non admin users. I want to display a database table called as Usertest inside the users section of the panel. Right now for the admin (super user part) I am able to display all the database tables. I want to display one or two tables in the user view of the admin panel, how do i go about it ?

Here is the model_views.py code

class MyModelView(sqla.ModelView):
    def is_accessible(self):
        if not current_user.is_active or not current_user.is_authenticated:
            return False
        if current_user.has_role('superuser') :
            return True
        return False

    def _handle_view(self, name, **kwargs):
        """
        Override builtin _handle_view in order to redirect users
          when a view is not accessible.
        """
        if not self.is_accessible():
            if current_user.is_authenticated:
                # permission denied
                abort(403)
            else:
                # login
                return redirect(url_for('security.login', next=request.url))

class CarUserView():
    column_display_pk = True
    form_columns = ['id', 'desc']
    column_searchable_list = ['desc']
    column_filters = ['id']
    can_create = True
    can_edit = True
    can_delete = False  # disable model deletion
    can_view_details = True
    page_size = 2  # pagination
    create_modal = True
    edit_modal = True
    can_export = True

class CarAdminView(MyModelView):
    column_display_pk = True
    form_columns = ['id', 'desc']
    column_searchable_list = ['desc']
    column_filters = ['id']
    column_editable_list = ['desc']
    can_create = True
    can_edit = True
    can_delete = True
    can_view_details = True
    page_size = 2
    create_modal = True
    edit_modal = True
    can_export = True

and this is the app.py code :

class Car(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    desc = db.Column(db.String(50))

    def __str__(self):
        return self.desc
class usertest(db.Model):
    id=db.Column(db.Integer, primary_key=True, autoincrement=True)
    desc=db.Column(db.String(50))

# --------------------------------
# MODEL VIEW CLASSES
# --------------------------------
from model_views import (
    CarAdminView, CarUserView, MyModelView
)

# --------------------------------
# FLASK VIEWS / ROUTES
# --------------------------------
@app.route('/')
def index():
    return render_template('index.html')
    #return redirect("/admin")

# --------------------------------
# CREATE FLASK ADMIN
# --------------------------------
admin = flask_admin.Admin(
    app,
    '',
    base_template='my_master.html',
    template_mode='bootstrap3',
)
admin.add_view(CarAdminView(Car, db.session))
admin.add_view(MyModelView(Profile, db.session))
admin.add_view(MyModelView(Username, db.session))
admin.add_view(CarUserView(usertest,db.session))

If i change the conditions in MyModelView such that it displays the table for both admin and non admin user all the tables are being displayed, which is not necessary. I expected it to only display the specified tables for the user view. Please help me out. Thank you.


来源: stackexchange

问:
how can i disable the button based on mapped inputs validation in react js
i have mapped the inputs and written validation for them based on minimum and maximum value, if i get the error validation in any one of the input in mapping, disable the button that is outside of the mapping, how can i achieve this?

i tried using useState hook, when i get the error in more than one input field it disables the button,but if i solve the error of one field and leaving other fields error as it is, still i got the enabled button, actually i want to enable button, once all the error validation is solved, please help me out from this, thanking you

ContentLicense: CC BY-SA 4.0


问:
Android: BottonNavigation item not being highlighted when returning to it
I have the following scenario:

A user launches the application. Inside the Profile fragment ProfileFragment, a child LoginFragment (which displays a button) is created. In the navigation component this is modeled as a nested graph.

The user selects the Collections tab.

Then, after the user re-selects the Profile tab, the Profile icon does not appear to be checked, even though the child LoginFragment is being shown.

What's going on here? I've tried to check the set BottomNavigationItemView progarmmatically as checked inside the onResume() method in ProfileFragment, with no success.


问:
Axios api call twise with 204 no content
i'm getting error while i'm calling simple post api and it throws 422 with 204. and in my code i used try and catch. it every time going to catch. i'm using laravel as a backend and vue.js 3 as a frontend. for api calling i'm using axios.

204 preflight error

I checked solutions in google but they all asking for sanctumn/csrf-cookie. but i'm not using sanctum in my current flow.


问:
Array to string conversion error - Angular and Laravel
I'm submitting a contact form using Angular and Laravel. In the form, there is some checkboxes. User can select multiple options (services) and the request will go to Laravel controller through API. In console.log, the request is working fine but when I'm trying to access services in Laravel, I'm getting this error in console:

Error: "Array to string conversion"

Angular Component:

```<code>export class ContactComponent {
  contactForm!: FormGroup;
  successMsg: boolean = false;
  warningMsg: boolean = false;
  public isSaving = false;
  Data: Array<any> = [
    {name: 'floor', value: 'Floor Maintenance'},
    {name: 'deep', value: 'Deep Cleaning'},
    {name: 'residential', value: 'Residential Cleaning'},
    {name: 'commercial', value: 'Commercial Cleaning'},
    {name: 'industrial', value: 'Industrial Cleaning'},
    {name: 'sanitization', value: 'Sanitization and Disinfection'}
  ];
ngOnInit(): void {
    this.contactForm = this.fb.group({
      name: ['', [Validators.required, Validators.minLength(3)]],
      email: ['', [Validators.required, Validators.minLength(3)]],
      phone: ['', [Validators.required, Validators.minLength(3)]],
      message: ['', [Validators.required, Validators.minLength(3)]],

      services: this.fb.array([], [Validators.required]),
    })
  }

onCheckboxChange(e: any) {
    const services: FormArray = this.contactForm.get('services') as FormArray;
    if (e.target.checked) {
      services.push(new FormControl(e.target.value));
    } else {
      let i: number = 0;
      services.controls.forEach((item: any) => {
        if (item.value == e.target.value) {
          services.removeAt(i);
          return;
        }
        i++;
      });
    }
  }

onSubmit() {
    this.isSaving = true;
    this._emailService.contact(this.contactForm.value)
    .subscribe(
      response => {
        console.log('Success!', response);
      },
      error => {
        console.error('Error.', error);
      }
    )
  }
}
</code>```

Laravel Controller

```<code>public function submit(Request $request) {
        Mail::to($request->email)->send(new Quotation($request));
        return response()->json($request->all, 200);
    }
</code>```

Quotation.php

```<code>public function build(Request $request)
{
 return $this->markdown('emails.angular')->with([
 'name' => $request->name,
 'email' => $request->email,
 'phone' =>  $request->phone,
 'message'   => $request->message,
 'services'  =>  $request->services
 ]);
}
</code>```

email.blade.php

```<code>@component('mail::message')
# A New Quotation Received

@component('mail::table')

| Details:       |               |                |
| :------------- |:-------------:| --------------:|
| Email          |               | {{ $email }}   |
| Name           |               | {{ $name }}    |
| Phone          |               | {{ $phone }}   |
| Message        |               | {{ $message }} |
| Services       |               | {{ $services}} |

@endcomponent
</code>```

It only happens when I try to send the email. If I access services in Controller like this return response()->json($request->services), I get this response in console.

['Floor Maintenance', 'Deep Cleaning']

But unable to send the email

Body:
I'm submitting a contact form using Angular and Laravel. In the form, there is some checkboxes. User can select multiple options (services) and the request will go to Laravel controller through API. In console.log, the request is working fine but when I'm trying to access services in Laravel, I'm getting this error in console:

Error: "Array to string conversion"

Angular Component:

export class ContactComponent {
  contactForm!: FormGroup;
  successMsg: boolean = false;
  warningMsg: boolean = false;
  public isSaving = false;
  Data: Array<any> = [
    {name: 'floor', value: 'Floor Maintenance'},
    {name: 'deep', value: 'Deep Cleaning'},
    {name: 'residential', value: 'Residential Cleaning'},
    {name: 'commercial', value: 'Commercial Cleaning'},
    {name: 'industrial', value: 'Industrial Cleaning'},
    {name: 'sanitization', value: 'Sanitization and Disinfection'}
  ];
ngOnInit(): void {
    this.contactForm = this.fb.group({
      name: ['', [Validators.required, Validators.minLength(3)]],
      email: ['', [Validators.required, Validators.minLength(3)]],
      phone: ['', [Validators.required, Validators.minLength(3)]],
      message: ['', [Validators.required, Validators.minLength(3)]],

      services: this.fb.array([], [Validators.required]),
    })
  }

onCheckboxChange(e: any) {
    const services: FormArray = this.contactForm.get('services') as FormArray;
    if (e.target.checked) {
      services.push(new FormControl(e.target.value));
    } else {
      let i: number = 0;
      services.controls.forEach((item: any) => {
        if (item.value == e.target.value) {
          services.removeAt(i);
          return;
        }
        i++;
      });
    }
  }

onSubmit() {
    this.isSaving = true;
    this._emailService.contact(this.contactForm.value)
    .subscribe(
      response => {
        console.log('Success!', response);
      },
      error => {
        console.error('Error.', error);
      }
    )
  }
}

Laravel Controller

public function submit(Request $request) {
        Mail::to($request->email)->send(new Quotation($request));
        return response()->json($request->all, 200);
    }

Quotation.php

public function build(Request $request)
{
 return $this->markdown('emails.angular')->with([
 'name' => $request->name,
 'email' => $request->email,
 'phone' =>  $request->phone,
 'message'   => $request->message,
 'services'  =>  $request->services
 ]);
}

email.blade.php

@component('mail::message')
# A New Quotation Received

@component('mail::table')

| Details:       |               |                |
| :------------- |:-------------:| --------------:|
| Email          |               | {{ $email }}   |
| Name           |               | {{ $name }}    |
| Phone          |               | {{ $phone }}   |
| Message        |               | {{ $message }} |
| Services       |               | {{ $services}} |

@endcomponent

It only happens when I try to send the email. If I access services in Controller like this return response()->json($request->services), I get this response in console.

['Floor Maintenance', 'Deep Cleaning']

But unable to send the email


问:
SwiftUI Drag & Drop - NSInternalInconsistencyException: Could not get the cell at indexPath
I have implemented drag & drop between two lists in SwiftUI. Regular drag and drops work fine when dropping it in between list items, but when I do some more advanced drag like dragging it onto the cell itself, my app crashes.
This crash happens even before I drop it (so while I am still dragging it, without releasing drop)

Has anyone occurred this crash ? Is this a SwiftUI bug or am I doing something wrong ?

I have tried removing my code blocks inside dropDestinations and yet crash still exists, so what could I be doing wrong ?

Here is the gif of the crash (crash occurs right after I drag it onto the second cell, without dropping/releasing it):

Code inside dropDestination does not even get called.

SwiftUI Code

```<code>var body2: some View {
HStack {
  VStack {
    Text("title-pending")

    List {
      ForEach(viewModel.pendingOrders) { order in
        RestaurantOrderCardView(order: order) {
          .background(cardBackground)
          .draggable(order)
      }
      .listRowSeparator(.hidden)
      .listRowBackground(Color.clear)
      .padding(.top)
    }
    .listStyle(.plain)
    .background(listBackground)
  }

  VStack {
    Text("title-in-preparation")

    List {
      ForEach(viewModel.inPreparationOrders) { item in
        RestaurantOrderCardView(order: item)
          .background(cardBackground)
      }
      .dropDestination(for: RestaurantOrder.self) { items, offset in
        guard let firstItem = items.first else { return }
        withAnimation {
          viewModel.dropItem(firstItem, offset: offset)
        }
      }
      .listRowSeparator(.hidden)
      .listRowBackground(Color.clear)
      .padding(.top)
    }
    .listStyle(.plain)
    .background {
      if !viewModel.inPreparationOrders.isEmpty {
        listBackground
      }
    }
    .overlay {
      if viewModel.inPreparationOrders.isEmpty {
        RoundedRectangle(cornerRadius: 8)
          .foregroundColor(!inDropArea ? .grayBackgroundColor : .grayBackgroundColor.opacity(0.25))
          .ignoresSafeArea()
          .dropDestination(for: RestaurantOrder.self) { items, location in
            guard let firstItem = items.first else { return false }
            withAnimation {
              viewModel.dropItem(firstItem, offset: 0)
            }
            return true
          } isTargeted: { inDropArea in
            withAnimation {
              self.inDropArea = inDropArea
            }
          }
      }
    }
  }
}
</code>```

}

Crash Log

```<code>2023-01-06 11:25:05.995303+0100 SimplifyStayAdmin[78761:2158775] *** Assertion failure in -[_UICollectionViewDragAndDropController _beginDragAndDropInsertingItemAtIndexPath:], _UICollectionViewDragAndDropController.m:620

2023-01-06 11:25:06.074407+0100 SimplifyStayAdmin[78761:2158775] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not get the cell at indexPath <NSIndexPath: 0x8846e25efd6dfbf1> {length = 2, path = 0 - 0} to start the reording portion of the Drag-and-drop'

*** First throw call stack:

(

    0   CoreFoundation                      0x000000018040e7c8 __exceptionPreprocess + 172

    1   libobjc.A.dylib                     0x0000000180051144 objc_exception_throw + 56

    2   Foundation                          0x0000000180b13b98 _userInfoForFileAndLine + 0

    3   UIKitCore                           0x0000000109a546ec -[_UICollectionViewDragAndDropController _beginDragAndDropInsertingItemAtIndexPath:] + 540

    4   UIKitCore                           0x0000000109a53064 -[_UICollectionViewDragAndDropController beginReorderingForItemAtIndexPath:cell:] + 204

    5   UIKitCore                           0x0000000109a1bad0 -[UICollectionView _beginInteractiveMovementForItemAtIndexPath:] + 196

    6   UIKit                               0x000000011803040c -[UICollectionViewAccessibility beginInteractiveMovementForItemAtIndexPath:] + 80

    7   UIKitCore                           0x0000000109a5c55c -[_UICollectionViewDragDestinationController _reorderingDisplayLinkDidTick] + 912

    8   QuartzCore                          0x0000000187dd04f8 _ZN2CA7Display11DisplayLink14dispatch_itemsEyyy + 808

    9   QuartzCore                          0x0000000187ec89a8 _ZL22display_timer_callbackP12__CFMachPortPvlS1_ + 336

    10  CoreFoundation                      0x000000018033ee94 __CFMachPortPerform + 172

    11  CoreFoundation                      0x000000018037387c __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 56

    12  CoreFoundation                      0x0000000180372e9c __CFRunLoopDoSource1 + 496

    13  CoreFoundation                      0x000000018036d43c __CFRunLoopRun + 2176

    14  CoreFoundation                      0x000000018036c7a4 CFRunLoopRunSpecific + 584

    15  GraphicsServices                    0x0000000188ff7c98 GSEventRunModal + 160

    16  UIKitCore                           0x000000010a1f237c -[UIApplication _run] + 868

    17  UIKitCore                           0x000000010a1f6374 UIApplicationMain + 124

    18  SwiftUI                             0x000000010e6150d4 OUTLINED_FUNCTION_51 + 496

    19  SwiftUI                             0x000000010e614f7c OUTLINED_FUNCTION_51 + 152

    20  SwiftUI                             0x000000010dd7ab60 OUTLINED_FUNCTION_10 + 88

    21  SimplifyStayAdmin                   0x000000010044d0c4 $s17SimplifyStayAdmin0abC3AppV5$mainyyFZ + 40

    22  SimplifyStayAdmin                   0x000000010044d378 main + 12

    23  dyld                                0x00000001080c1fa0 start_sim + 20

    24  ???                                 0x00000001081c9e50 0x0 + 4431060560

    25  ???                                 0x0869800000000000 0x0 + 606156362346397696

)

libc++abi: terminating with uncaught exception of type NSException

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not get the cell at indexPath <NSIndexPath: 0x8846e25efd6dfbf1> {length = 2, path = 0 - 0} to start the reording portion of the Drag-and-drop'

terminating with uncaught exception of type NSException

CoreSimulator 857.14 - Device: iPad (10th generation) (D79A0AD8-4970-4F84-A5F9-078DAFB697A3) - Runtime: iOS 16.2 (20C52) - DeviceType: iPad (10th generation)
</code>```

Body:
I have implemented drag & drop between two lists in SwiftUI. Regular drag and drops work fine when dropping it in between list items, but when I do some more advanced drag like dragging it onto the cell itself, my app crashes.
This crash happens even before I drop it (so while I am still dragging it, without releasing drop)

Has anyone occurred this crash ? Is this a SwiftUI bug or am I doing something wrong ?

I have tried removing my code blocks inside dropDestinations and yet crash still exists, so what could I be doing wrong ?

Here is the gif of the crash (crash occurs right after I drag it onto the second cell, without dropping/releasing it):

Code inside dropDestination does not even get called.

SwiftUI Code

var body2: some View {
HStack {
  VStack {
    Text("title-pending")

    List {
      ForEach(viewModel.pendingOrders) { order in
        RestaurantOrderCardView(order: order) {
          .background(cardBackground)
          .draggable(order)
      }
      .listRowSeparator(.hidden)
      .listRowBackground(Color.clear)
      .padding(.top)
    }
    .listStyle(.plain)
    .background(listBackground)
  }

  VStack {
    Text("title-in-preparation")

    List {
      ForEach(viewModel.inPreparationOrders) { item in
        RestaurantOrderCardView(order: item)
          .background(cardBackground)
      }
      .dropDestination(for: RestaurantOrder.self) { items, offset in
        guard let firstItem = items.first else { return }
        withAnimation {
          viewModel.dropItem(firstItem, offset: offset)
        }
      }
      .listRowSeparator(.hidden)
      .listRowBackground(Color.clear)
      .padding(.top)
    }
    .listStyle(.plain)
    .background {
      if !viewModel.inPreparationOrders.isEmpty {
        listBackground
      }
    }
    .overlay {
      if viewModel.inPreparationOrders.isEmpty {
        RoundedRectangle(cornerRadius: 8)
          .foregroundColor(!inDropArea ? .grayBackgroundColor : .grayBackgroundColor.opacity(0.25))
          .ignoresSafeArea()
          .dropDestination(for: RestaurantOrder.self) { items, location in
            guard let firstItem = items.first else { return false }
            withAnimation {
              viewModel.dropItem(firstItem, offset: 0)
            }
            return true
          } isTargeted: { inDropArea in
            withAnimation {
              self.inDropArea = inDropArea
            }
          }
      }
    }
  }
}

}

Crash Log

2023-01-06 11:25:05.995303+0100 SimplifyStayAdmin[78761:2158775] *** Assertion failure in -[_UICollectionViewDragAndDropController _beginDragAndDropInsertingItemAtIndexPath:], _UICollectionViewDragAndDropController.m:620

2023-01-06 11:25:06.074407+0100 SimplifyStayAdmin[78761:2158775] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not get the cell at indexPath <NSIndexPath: 0x8846e25efd6dfbf1> {length = 2, path = 0 - 0} to start the reording portion of the Drag-and-drop'

*** First throw call stack:

(

    0   CoreFoundation                      0x000000018040e7c8 __exceptionPreprocess + 172

    1   libobjc.A.dylib                     0x0000000180051144 objc_exception_throw + 56

    2   Foundation                          0x0000000180b13b98 _userInfoForFileAndLine + 0

    3   UIKitCore                           0x0000000109a546ec -[_UICollectionViewDragAndDropController _beginDragAndDropInsertingItemAtIndexPath:] + 540

    4   UIKitCore                           0x0000000109a53064 -[_UICollectionViewDragAndDropController beginReorderingForItemAtIndexPath:cell:] + 204

    5   UIKitCore                           0x0000000109a1bad0 -[UICollectionView _beginInteractiveMovementForItemAtIndexPath:] + 196

    6   UIKit                               0x000000011803040c -[UICollectionViewAccessibility beginInteractiveMovementForItemAtIndexPath:] + 80

    7   UIKitCore                           0x0000000109a5c55c -[_UICollectionViewDragDestinationController _reorderingDisplayLinkDidTick] + 912

    8   QuartzCore                          0x0000000187dd04f8 _ZN2CA7Display11DisplayLink14dispatch_itemsEyyy + 808

    9   QuartzCore                          0x0000000187ec89a8 _ZL22display_timer_callbackP12__CFMachPortPvlS1_ + 336

    10  CoreFoundation                      0x000000018033ee94 __CFMachPortPerform + 172

    11  CoreFoundation                      0x000000018037387c __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 56

    12  CoreFoundation                      0x0000000180372e9c __CFRunLoopDoSource1 + 496

    13  CoreFoundation                      0x000000018036d43c __CFRunLoopRun + 2176

    14  CoreFoundation                      0x000000018036c7a4 CFRunLoopRunSpecific + 584

    15  GraphicsServices                    0x0000000188ff7c98 GSEventRunModal + 160

    16  UIKitCore                           0x000000010a1f237c -[UIApplication _run] + 868

    17  UIKitCore                           0x000000010a1f6374 UIApplicationMain + 124

    18  SwiftUI                             0x000000010e6150d4 OUTLINED_FUNCTION_51 + 496

    19  SwiftUI                             0x000000010e614f7c OUTLINED_FUNCTION_51 + 152

    20  SwiftUI                             0x000000010dd7ab60 OUTLINED_FUNCTION_10 + 88

    21  SimplifyStayAdmin                   0x000000010044d0c4 $s17SimplifyStayAdmin0abC3AppV5$mainyyFZ + 40

    22  SimplifyStayAdmin                   0x000000010044d378 main + 12

    23  dyld                                0x00000001080c1fa0 start_sim + 20

    24  ???                                 0x00000001081c9e50 0x0 + 4431060560

    25  ???                                 0x0869800000000000 0x0 + 606156362346397696

)

libc++abi: terminating with uncaught exception of type NSException

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not get the cell at indexPath <NSIndexPath: 0x8846e25efd6dfbf1> {length = 2, path = 0 - 0} to start the reording portion of the Drag-and-drop'

terminating with uncaught exception of type NSException

CoreSimulator 857.14 - Device: iPad (10th generation) (D79A0AD8-4970-4F84-A5F9-078DAFB697A3) - Runtime: iOS 16.2 (20C52) - DeviceType: iPad (10th generation)


问:
Vanilla JS xmlhttp request errors 500, but results still appear on form submit?
I've got a little bit of a conundrum here.

I've got a simple FAQs section running in WordPress, and for styling reasons I need to filter the array through PHP. The problem I'm currently having is that the XML request I'm making through JS is coming out with an error 500, but after the form submits, the data filters.
I want to avoid the submit refresh, and get the data like ajax. Ajax hasn't worked in the ways that I've tried it, so looking for some implementation.

The PHP display

This script is just for displaying the form, and also displaying the results. But I want to get these results asynchronously to display them.

<?php

function faqs_display() {

    include( dirname(__FILE__, 2) . '/faq-results.php');

    ?>

        <form method="post" name="faqs-search-form" id="faqs-search-form">
            <select name="category" id="category">
                <option value="" disabled selected>Select a category...</option>
                <option value="none">None</option>
                <option value="web-dev">Web Dev</option>
                <option value="ecommerce">Ecommerce</option>
                <option value="paid-ads">Paid Ads</option>
                <option value="branding">Branding</option>
            </select>
        </form>

            <?php foreach($faqs as $key => $faq) {
                if($key % 2 == 0) { ?>
                <div class="single-faq <?php foreach($faq['categories'] as $key => $cat) { echo $cat . ' '; } ?>">

<?php echo $faq['question']; ?>

<?php echo $faq['answer']; ?>

                <?php }
            } ?>

            <?php foreach($faqs as $key => $faq) {
                if($key % 2 != 0) { ?>
                <div class="single-faq <?php foreach($faq['categories'] as $key => $cat) { echo $cat . ' '; } ?>">

<?php echo $faq['question']; ?>

<?php echo $faq['answer']; ?>

                <?php }
            } ?>

    <?php

}

add_shortcode('faqs-display', 'faqs_display');

?>
```
<h2>The JS</h2>
<p>This is the script that does the request. When we change the "category" select, I want to run this async function to force a data sort.</p>
<pre class="lang-js prettyprint-override"><code>window.addEventListener('DOMContentLoaded', (event) => {
    /* ========== Global Functions JS ========== */
    document.getElementById("category").addEventListener("change", filterFAQs)
    setTimeout(function(){

    }, 1000);
    /* ========== Global Functions JS END ========== */
});

async function filterFAQs() {
    // e.preventDefault;
    var category = document.getElementById('category').value;
    var faqs = document.getElementsByClassName('single-faq');
    var form = document.getElementById('faqs-search-form');

    var http = new XMLHttpRequest();
    http.open("POST", "faq-results.php", true);
    var params = "category=" + category;
    http.send(params);
    http.onload = function () {
        alert(http.status.toString() + ': ' + http.statusText);
    }

    form.submit()
    return false;
}
</code>```

The PHP script to parse

This is the PHP that the JS calls on, as well as the one that's included in the display PHP.

<?php

    $faqs = [];
    $i = 0;

    $query = new WP_Query(array(
        'post_type' => 'faq',
        'post_status' => 'publish',
        'posts_per_page' => -1
    ));

    while($query->have_posts()) {
        $query->the_post();
        $post_id = get_the_ID();
        $question = get_post_meta( get_the_ID(), 'question', true );
        $answer = get_post_meta( get_the_ID(), 'answers', true );
        $categories = [];

        if(
            str_contains(strtolower($question), 'web dev') || str_contains(strtolower($answer), 'web dev')
        ) {
            array_push($categories, 'web-dev');
        }
        if(
            str_contains(strtolower($question), 'branding') || str_contains(strtolower($answer), 'branding') ||
            str_contains(strtolower($question), 'logo') || str_contains(strtolower($answer), 'logo')
        ) {
            array_push($categories, 'branding');
        }
        if(
            str_contains(strtolower($question), 'paid ad') || str_contains(strtolower($answer), 'paid ad') ||
            str_contains(strtolower($question), 'keywords') || str_contains(strtolower($answer), 'keywords')
        ) {
            array_push($categories, 'paid-ads');
        }
        if(
            str_contains(strtolower($question), 'ecommerce') || str_contains(strtolower($answer), 'ecommerce') ||
            str_contains(strtolower($question), 'e-commerce') || str_contains(strtolower($answer), 'e-commerce')
        ) {
            array_push($categories, 'ecommerce');
        }

        $faqs[$i]['question'] = $question;
        $faqs[$i]['answer'] = $answer;
        $faqs[$i]['categories'] = $categories;

        $i++;

        if(isset($_POST['category'])) {
            $faqs_filtered = [];
            $j = 0;
            foreach($faqs as $key => $faq) {
                if(in_array($_POST['category'], $faq['categories'])) {
                    $faqs_filtered[$j]['question'] = $faq['question'];
                    $faqs_filtered[$j]['answer'] = $faq['answer'];
                    $faqs_filtered[$j]['categories'] = $faq['categories'];
                }
                $j++;
            }
            $faqs = $faqs_filtered;
        }
    }
    echo json_encode($faqs);
?>
```

What happens is that when I send the alert, I get "500: " which means I've got an error 500. But when the alert is closed and the page is refreshed by the submit (which I don't want it to refresh, but we'll worry about that later), the results JSON appears as it should. I just want to skip the refreshing part, and have the results display when the select is changed.

Any and all help is appreciated.

Body:
I've got a little bit of a conundrum here.

I've got a simple FAQs section running in WordPress, and for styling reasons I need to filter the array through PHP. The problem I'm currently having is that the XML request I'm making through JS is coming out with an error 500, but after the form submits, the data filters.
I want to avoid the submit refresh, and get the data like ajax. Ajax hasn't worked in the ways that I've tried it, so looking for some implementation.

The PHP display

This script is just for displaying the form, and also displaying the results. But I want to get these results asynchronously to display them.

<?php

function faqs_display() {

    include( dirname(__FILE__, 2) . '/faq-results.php');

    ?>

        <form method="post" name="faqs-search-form" id="faqs-search-form">
            <select name="category" id="category">
                <option value="" disabled selected>Select a category...</option>
                <option value="none">None</option>
                <option value="web-dev">Web Dev</option>
                <option value="ecommerce">Ecommerce</option>
                <option value="paid-ads">Paid Ads</option>
                <option value="branding">Branding</option>
            </select>
        </form>

            <?php foreach($faqs as $key => $faq) {
                if($key % 2 == 0) { ?>
                <div class="single-faq <?php foreach($faq['categories'] as $key => $cat) { echo $cat . ' '; } ?>">

<?php echo $faq['question']; ?>

<?php echo $faq['answer']; ?>

                <?php }
            } ?>

            <?php foreach($faqs as $key => $faq) {
                if($key % 2 != 0) { ?>
                <div class="single-faq <?php foreach($faq['categories'] as $key => $cat) { echo $cat . ' '; } ?>">

<?php echo $faq['question']; ?>

<?php echo $faq['answer']; ?>

                <?php }
            } ?>

    <?php

}

add_shortcode('faqs-display', 'faqs_display');

?>

The JS

This is the script that does the request. When we change the "category" select, I want to run this async function to force a data sort.

window.addEventListener('DOMContentLoaded', (event) => {
    /* ========== Global Functions JS ========== */
    document.getElementById("category").addEventListener("change", filterFAQs)
    setTimeout(function(){

    }, 1000);
    /* ========== Global Functions JS END ========== */
});

async function filterFAQs() {
    // e.preventDefault;
    var category = document.getElementById('category').value;
    var faqs = document.getElementsByClassName('single-faq');
    var form = document.getElementById('faqs-search-form');

    var http = new XMLHttpRequest();
    http.open("POST", "faq-results.php", true);
    var params = "category=" + category;
    http.send(params);
    http.onload = function () {
        alert(http.status.toString() + ': ' + http.statusText);
    }

    form.submit()
    return false;
}

The PHP script to parse

This is the PHP that the JS calls on, as well as the one that's included in the display PHP.

<?php

    $faqs = [];
    $i = 0;

    $query = new WP_Query(array(
        'post_type' => 'faq',
        'post_status' => 'publish',
        'posts_per_page' => -1
    ));

    while($query->have_posts()) {
        $query->the_post();
        $post_id = get_the_ID();
        $question = get_post_meta( get_the_ID(), 'question', true );
        $answer = get_post_meta( get_the_ID(), 'answers', true );
        $categories = [];

        if(
            str_contains(strtolower($question), 'web dev') || str_contains(strtolower($answer), 'web dev')
        ) {
            array_push($categories, 'web-dev');
        }
        if(
            str_contains(strtolower($question), 'branding') || str_contains(strtolower($answer), 'branding') ||
            str_contains(strtolower($question), 'logo') || str_contains(strtolower($answer), 'logo')
        ) {
            array_push($categories, 'branding');
        }
        if(
            str_contains(strtolower($question), 'paid ad') || str_contains(strtolower($answer), 'paid ad') ||
            str_contains(strtolower($question), 'keywords') || str_contains(strtolower($answer), 'keywords')
        ) {
            array_push($categories, 'paid-ads');
        }
        if(
            str_contains(strtolower($question), 'ecommerce') || str_contains(strtolower($answer), 'ecommerce') ||
            str_contains(strtolower($question), 'e-commerce') || str_contains(strtolower($answer), 'e-commerce')
        ) {
            array_push($categories, 'ecommerce');
        }

        $faqs[$i]['question'] = $question;
        $faqs[$i]['answer'] = $answer;
        $faqs[$i]['categories'] = $categories;

        $i++;

        if(isset($_POST['category'])) {
            $faqs_filtered = [];
            $j = 0;
            foreach($faqs as $key => $faq) {
                if(in_array($_POST['category'], $faq['categories'])) {
                    $faqs_filtered[$j]['question'] = $faq['question'];
                    $faqs_filtered[$j]['answer'] = $faq['answer'];
                    $faqs_filtered[$j]['categories'] = $faq['categories'];
                }
                $j++;
            }
            $faqs = $faqs_filtered;
        }
    }
    echo json_encode($faqs);
?>

What happens is that when I send the alert, I get "500: " which means I've got an error 500. But when the alert is closed and the page is refreshed by the submit (which I don't want it to refresh, but we'll worry about that later), the results JSON appears as it should. I just want to skip the refreshing part, and have the results display when the select is changed.

Any and all help is appreciated.


问:
25 second load time on inital network request to my website
When debugging using the chrome's performance profiler i recorded a reload of my own page. The following is the result.

chrome performance profiler screenshot

After reloading the page, there is a 25 second network request that first happens, then the website loads really ast. I've been searching the internet for an answer on how to debug this further or why this could happen but honestly I can't figure it out.

I've tried using another network, my 4G on mobile, flushing DNS, using other browsers/incognito, clearing cache. Nothing works.

My hosting company says that this is a problem on my end and GTmetrix also show very good results. But I'm not sure i trust it since it happens on both my phone and computer. (4G roaming on phone)


问:
Microsoft graph token refresh azure app service
I have used this https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2/tree/master/2-WebApp-graph-user/2-1-Call-MSGraph,
but when I publish it to Azure I get an error after some time (probably 1 hour) with http error 500. It seems the token isn't refreshing automatically? When running the app locally it doesn't happen as often, but it have happened there as well. What can be done to fix this issue?
Redirect URIs are set as shown in the github example (https://websitename.azurewebsites.net/signin-oidc).</p>


问:
Unable to find pg_hba.conf file in postgres docker image?
I am using postgres:15.1 docker image and unable to find the pg_bha.conf file inside the docker container. The find command returns nothing:

```<code>find . -name "pg_hba.conf"
</code>```

Where do I find it in the docker image? Or, how do I configure it when running postgres via docker?

Body:
I am using postgres:15.1 docker image and unable to find the pg_bha.conf file inside the docker container. The find command returns nothing:

find . -name "pg_hba.conf"

Where do I find it in the docker image? Or, how do I configure it when running postgres via docker?


问:
Active Campaign Simple Form embed using Tinymce
I'm trying to embed a 'simple embed' form from Active Campaign on a Laravel Platform. I have a below embed code.

While placing above embed code within code it is working fine and is showing exact place where I have placed the embed code.
But I have a admin panel and page is created using Tinymce. Now, While I place Active Campaign embed code within Tinymce editor using </> i.e. source code, Embed Form is showing at the end of the page instead of where I have placed.

Hope, someone can help me out.

The expected result should be embeded form should be display where you have placed.


问:
Typescript React - IntrinsicAttributes Error when passing props
I never had this error before. When I want to pass a props to my SearchItem component I get this error message:

Type '{ item: HotelModel; key: string; }' is not assignable to type
'IntrinsicAttributes'.   Property 'item' does not exist on type
'IntrinsicAttributes'.

HotelModel is an interface with different attributes: {_id: string, name: string, rating: number. ...}

Here is the part of the code:

```<code>function List(): JSX.Element {

  const { data, loading, error } = useFetch(`hotel?city=${destination}`);

  return (
    <div>
          <div className="listResult">
            {loading ? (
              'Loading'
            ) : (
              <>
                {data.map((item: HotelModel) => {
                  return <SearchItem item={item} key={item._id} />;
                })}
              </>
            )}
          </div>
    </div>
  );
}
</code>```

I'm new to Typescript, is there a best practice when it comes to passing props while iterating over an array? Thank you.

Body:
I never had this error before. When I want to pass a props to my SearchItem component I get this error message:

Type '{ item: HotelModel; key: string; }' is not assignable to type
'IntrinsicAttributes'.   Property 'item' does not exist on type
'IntrinsicAttributes'.

HotelModel is an interface with different attributes: {_id: string, name: string, rating: number. ...}

Here is the part of the code:

function List(): JSX.Element {

  const { data, loading, error } = useFetch(`hotel?city=${destination}`);

  return (

            {loading ? (
              'Loading'
            ) : (
              <>
                {data.map((item: HotelModel) => {
                  return <SearchItem item={item} key={item._id} />;
                })}
              </>
            )}

  );
}

I'm new to Typescript, is there a best practice when it comes to passing props while iterating over an array? Thank you.


问:
Material UI Data grid optional values in menu list
I'm trying to display custom values in a menu. When a column is sortable it will automatically add in a menu list

Unsort

Sort by ASC

Sort by DESC

Filter

I want to hide those values in the menu and leave only Filter. Going through the material ui documentation but couldn't find any solution to that. I still want the column to be sortable but don't display the related items to sorting in the menu.


问:
trying to connect html and js file with browsify ,but getting this error "not a function at HTMLButtonElement.onclick"
I was trying to connect my smart contract to frontend with two file index.html and index.js . As the require () in javascript is not readable for browser I used bundle. Using bundle I mapped index.js to html src file.But I'm getting "not a function at HTMLButtonElement.onclick".
I've attached both html and js file kindly take a look and help me out to make function.If I dont use bundle it stop the execution at the very first line require() in .js file.

index.html

```<code>`<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Metamask Connectivity</title>
  </head>
  <body>
    <button id="conectButton" onclick="bundle.connect()">connect</button>
    <button id="executeButton" onclick="bundle.execute()">Execute</button>
  </body>
  <script src="./dist/bundle.js" type="text/javascript"></script>
</html>
`
</code>```

index.js

```<code>const { ethers } = require("ethers");
async function connect() {
  if (window.ethereum) {
    ethereum.request({ method: "eth_requestAccounts" });
  }
}
async function execute() {
  /* to execute any task we need couple of things
  address
  contract ABI
  function✅
  node connections✅--> connect function to connect to metamask wallet accounts

  */
  const contractAddress = "0x58d012E56f23F86384B775144F909F5d5EB060d1";
  const abi="MY_ABI";
  const providers = new ethers.providers.Web3Provider("window.ethereum");
  const signer = providers.getSigner();
  const contract = new ethers.Contract(contractAddress, abi, signer);
  await contract.buyToken(1);
}
module.exports = {
  connect,
  execute,
};
</code>```

Error:

```<code> Uncaught TypeError: bundle.connect_ is not a function
    at HTMLButtonElement.onclick (index.html:7:66)
onclick @ index.html:7
</code>```

I want to make use of the functions in index.js and make transaction in samrt contract

Body:
I was trying to connect my smart contract to frontend with two file index.html and index.js . As the require () in javascript is not readable for browser I used bundle. Using bundle I mapped index.js to html src file.But I'm getting "not a function at HTMLButtonElement.onclick".
I've attached both html and js file kindly take a look and help me out to make function.If I dont use bundle it stop the execution at the very first line require() in .js file.

index.html

`<!DOCTYPE html>

    <title>Metamask Connectivity</title>

    <button id="conectButton" onclick="bundle.connect()">connect</button>
    <button id="executeButton" onclick="bundle.execute()">Execute</button>

`

index.js

const { ethers } = require("ethers");
async function connect() {
  if (window.ethereum) {
    ethereum.request({ method: "eth_requestAccounts" });
  }
}
async function execute() {
  /* to execute any task we need couple of things
  address
  contract ABI
  function✅
  node connections✅--> connect function to connect to metamask wallet accounts

  */
  const contractAddress = "0x58d012E56f23F86384B775144F909F5d5EB060d1";
  const abi="MY_ABI";
  const providers = new ethers.providers.Web3Provider("window.ethereum");
  const signer = providers.getSigner();
  const contract = new ethers.Contract(contractAddress, abi, signer);
  await contract.buyToken(1);
}
module.exports = {
  connect,
  execute,
};

Error:

 Uncaught TypeError: bundle.connect_ is not a function
    at HTMLButtonElement.onclick (index.html:7:66)
onclick @ index.html:7

I want to make use of the functions in index.js and make transaction in samrt contract


问:
MemoryStream.TryGetBuffer to get the underlying byte array instead of calling ToArray
I have the following code where I am trying to compress the byte[]. Right now I am using ToArray() to return the compressed byte[] but I would like to leverage MemoryStream.TryGetBuffer  to get the underlying byte array instead of calling  ToArray.This will avoid the additional copy of the data in the buffer.

```<code>public static byte[] Compress(byte[] bytes)
{
    using (var memoryStream = new MemoryStream())
    {
        using (var gzipStream = new GZipStream(memoryStream, CompressionLevel.Optimal))
        {
            gzipStream.Write(bytes, 0, bytes.Length);
        }

        return memoryStream.TryGetBuffer(out ArraySegment<byte> buff);
    }
}
</code>```

I am getting an error in the above code.

Can anyone help me here by providing some guidance?

Body:
I have the following code where I am trying to compress the byte[]. Right now I am using ToArray() to return the compressed byte[] but I would like to leverage MemoryStream.TryGetBuffer  to get the underlying byte array instead of calling  ToArray.This will avoid the additional copy of the data in the buffer.

public static byte[] Compress(byte[] bytes)
{
    using (var memoryStream = new MemoryStream())
    {
        using (var gzipStream = new GZipStream(memoryStream, CompressionLevel.Optimal))
        {
            gzipStream.Write(bytes, 0, bytes.Length);
        }

        return memoryStream.TryGetBuffer(out ArraySegment<byte> buff);
    }
}

I am getting an error in the above code.

Can anyone help me here by providing some guidance?


问:
Issue with my odbc connector 8.0 that connects to mysql8 in centos7
I tried to connect using isql command (Both are AWS EC2)

```<code>#  isql -v WebDB
[S1000][unixODBC][MySQL][ODBC 8.0(w) Driver]Can't connect to MySQL server on 'ip:3306' (110)
[ISQL]ERROR: Could not SQLConnect
</code>```

But I can able connect manually

```<code>~**]# mysql -h ip -u useranme -p $pwd**
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MySQL connection id is 304
Server version: 8.0.29 MySQL Community Server - GPL

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MySQL [(none)]>
</code>```

I tried to restart opensips that need to connect remote mysql8

```<code> /usr/local/sbin/opensips[2905]: ERROR:db_mysql:db_mysql_connect: driver error(2003): Can't connect to MySQL server on 'ip'
 /usr/local/sbin/opensips[2905]: ERROR:db_mysql:db_mysql_new_connection: initial connect failed
 /usr/local/sbin/opensips[2905]: ERROR:core:db_do_init: could not add connection to the pool
[2905]: ERROR:dialog:init_dlg_db: unable to connect to the database
 /usr/local/sbin/opensips[2905]: ERROR:dialog:mod_init: failed to initialize the DB support
</code>```

Body:
I tried to connect using isql command (Both are AWS EC2)

#  isql -v WebDB
[S1000][unixODBC][MySQL][ODBC 8.0(w) Driver]Can't connect to MySQL server on 'ip:3306' (110)
[ISQL]ERROR: Could not SQLConnect

But I can able connect manually

~**]# mysql -h ip -u useranme -p $pwd**
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MySQL connection id is 304
Server version: 8.0.29 MySQL Community Server - GPL

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MySQL [(none)]>

I tried to restart opensips that need to connect remote mysql8

 /usr/local/sbin/opensips[2905]: ERROR:db_mysql:db_mysql_connect: driver error(2003): Can't connect to MySQL server on 'ip'
 /usr/local/sbin/opensips[2905]: ERROR:db_mysql:db_mysql_new_connection: initial connect failed
 /usr/local/sbin/opensips[2905]: ERROR:core:db_do_init: could not add connection to the pool
[2905]: ERROR:dialog:init_dlg_db: unable to connect to the database
 /usr/local/sbin/opensips[2905]: ERROR:dialog:mod_init: failed to initialize the DB support


问:
How to change widget's child layout at runtime using python kivy?
How can I change layout of MDBoxLayout, id: body_box in MsgCard, remove MDLabel, id: msg_count then add Checkbox, id: flagged in place at runtime? Here's the kivy file...

```<code><MsgCard@MDBoxLayout>:
  id: msg_container
  adaptive_height: True
  spacing: dp(10)
  padding: (dp(5),)*4

  FitImage:
    id: msg_image
    source: root.avatar
    size_hint: 0.09, None
    height: dp(30)
    pos_hint: {"top": 1}
    radius: (10,)*4

  MDBoxLayout:
    orientation: "vertical"

    MDBoxLayout:

      MDLabel:
        text: root.sender
        font_style: "Subtitle2"

      MDLabel:
        text: root.received
        font_size: "12sp"
        halign: "right"
        size_hint_x: 0.25

    MDBoxLayout:
      id: body_box

      MDLabel:
        text: root.body
        shorten: True
        shorten_from: "right"
        font_style: "Caption"

      MDLabel:
        id: msg_count
        text: root.count
        size_hint: None, None
        post_hint: {"center_y": 0.5}
        size: (dp(17),)*2
        font_size: "12sp"
        halign: "center"
        theme_text_color: "Custom"
        text_color: 1,1,1,1
        opacity: 1 if root.count != "0" else 0

        canvas.before:
          Color:
            rgba: 1,0,0,1
          RoundedRectangle:
            size: self.size
            pos: self.pos
            radius: (dp(3),)*2

<Checkbox@MDCheckbox>
  id: flagged
  size_hint: None, None
  size: (dp(17),)*2
</code>```

Body:
How can I change layout of MDBoxLayout, id: body_box in MsgCard, remove MDLabel, id: msg_count then add Checkbox, id: flagged in place at runtime? Here's the kivy file...

<MsgCard@MDBoxLayout>:
  id: msg_container
  adaptive_height: True
  spacing: dp(10)
  padding: (dp(5),)*4

  FitImage:
    id: msg_image
    source: root.avatar
    size_hint: 0.09, None
    height: dp(30)
    pos_hint: {"top": 1}
    radius: (10,)*4

  MDBoxLayout:
    orientation: "vertical"

    MDBoxLayout:

      MDLabel:
        text: root.sender
        font_style: "Subtitle2"

      MDLabel:
        text: root.received
        font_size: "12sp"
        halign: "right"
        size_hint_x: 0.25

    MDBoxLayout:
      id: body_box

      MDLabel:
        text: root.body
        shorten: True
        shorten_from: "right"
        font_style: "Caption"

      MDLabel:
        id: msg_count
        text: root.count
        size_hint: None, None
        post_hint: {"center_y": 0.5}
        size: (dp(17),)*2
        font_size: "12sp"
        halign: "center"
        theme_text_color: "Custom"
        text_color: 1,1,1,1
        opacity: 1 if root.count != "0" else 0

        canvas.before:
          Color:
            rgba: 1,0,0,1
          RoundedRectangle:
            size: self.size
            pos: self.pos
            radius: (dp(3),)*2

<Checkbox@MDCheckbox>
  id: flagged
  size_hint: None, None
  size: (dp(17),)*2


问:
Lesson 9 hardhat raffle staging test error: No Contract deployed with name VRFCoordinatorV2Mock
when I test my tests on GOERLI network, it shows an Error that reads: 1) Raffle Unit Tests
"before each" hook for "works with live Chainlink Keepers and Chainlink VRF, we get a random winner":
Error: No Contract deployed with name VRFCoordinatorV2Mock
at Object.getContract (node_modules/@nomiclabs/hardhat-ethers/src/internal/helpers.ts:447:11)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at Context. (test/staging/Raffle.staging.test.js:15:38)

```<code>const { inputToConfig } = require("@ethereum-waffle/compiler")
const { assert, expect } = require("chai")
const { network, getNamedAccounts, deployments, ethers } = require("hardhat")
const { developmentChains, networkConfig } = require("../../helper-hardhat-config")

developmentChains.includes(network.name)
    ? describe.skip
    : describe("Raffle Unit Tests", function () {
          let raffle, raffleEntranceFee, deployer

          beforeEach(async function () {
              deployer = (await getNamedAccounts()).deployer
              await deployments.fixture(["all"])
              raffle = await ethers.getContract("Raffle", deployer)
              vrfCoordinatorV2Mock = await ethers.getContract("VRFCoordinatorV2Mock", deployer)
              raffleEntranceFee = await raffle.getEntranceFee()
          })
          describe("fulfillRandomWords", function () {
              it("works with live Chainlink Keepers and Chainlink VRF, we get a random winner", async function () {
                  // enter the raffle
                  console.log("Setting up test...")
                  await deployments.fixture(["mocks"])
                  const startingTimeStamp = await raffle.getLastTimeStamp()
                  const accounts = await ethers.getSigners()

                  console.log("Setting up Listener...")
                  await new Promise(async (resolve, reject) => {
                      // setup listener before we enter the raffle
                      // Just in case the blockchain moves REALLY fast
                      raffle.once("WinnerPicked", async () => {
                          console.log("WinnerPicked event fired!")
                          try {

                              const recentWinner = await raffle.getRecentWinner()
                              const raffleState = await raffle.getRaffleState()
                              const winnerEndingBalance = await accounts[0].getBalance()
                              const endingTimeStamp = await raffle.getLastTimeStamp()

                              await expect(raffle.getPlayer(0)).to.be.reverted
                              assert.equal(recentWinner.toString(), accounts[0].address)
                              assert.equal(raffleState, 0)
                              assert.equal(
                                  winnerEndingBalance.toString(),
                                  winnerStartingBalance.add(raffleEntranceFee).toString()
                              )
                              assert(endingTimeStamp > startingTimeStamp)
                              resolve()
                          } catch (error) {
                              console.log(error)
                              reject(error)
                          }
                      })
                      // Then entering the raffle
                      console.log("Entering Raffle...")
                      const tx = await raffle.enterRaffle({ value: raffleEntranceFee })
                      await tx.wait(1)
                      console.log("Ok, time to wait...")
                      const winnerStartingBalance = await accounts[0].getBalance()

                      // and this code WONT complete until our listener has finished listening!
                  })
              })
          })
      })
</code>```

Can anyone help me out with these, here's the link to my repo: https://github.com/anooj1/hardhat-raffle

Body:
when I test my tests on GOERLI network, it shows an Error that reads: 1) Raffle Unit Tests
"before each" hook for "works with live Chainlink Keepers and Chainlink VRF, we get a random winner":
Error: No Contract deployed with name VRFCoordinatorV2Mock
at Object.getContract (node_modules/@nomiclabs/hardhat-ethers/src/internal/helpers.ts:447:11)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at Context. (test/staging/Raffle.staging.test.js:15:38)

const { inputToConfig } = require("@ethereum-waffle/compiler")
const { assert, expect } = require("chai")
const { network, getNamedAccounts, deployments, ethers } = require("hardhat")
const { developmentChains, networkConfig } = require("../../helper-hardhat-config")

developmentChains.includes(network.name)
    ? describe.skip
    : describe("Raffle Unit Tests", function () {
          let raffle, raffleEntranceFee, deployer

          beforeEach(async function () {
              deployer = (await getNamedAccounts()).deployer
              await deployments.fixture(["all"])
              raffle = await ethers.getContract("Raffle", deployer)
              vrfCoordinatorV2Mock = await ethers.getContract("VRFCoordinatorV2Mock", deployer)
              raffleEntranceFee = await raffle.getEntranceFee()
          })
          describe("fulfillRandomWords", function () {
              it("works with live Chainlink Keepers and Chainlink VRF, we get a random winner", async function () {
                  // enter the raffle
                  console.log("Setting up test...")
                  await deployments.fixture(["mocks"])
                  const startingTimeStamp = await raffle.getLastTimeStamp()
                  const accounts = await ethers.getSigners()

                  console.log("Setting up Listener...")
                  await new Promise(async (resolve, reject) => {
                      // setup listener before we enter the raffle
                      // Just in case the blockchain moves REALLY fast
                      raffle.once("WinnerPicked", async () => {
                          console.log("WinnerPicked event fired!")
                          try {

                              const recentWinner = await raffle.getRecentWinner()
                              const raffleState = await raffle.getRaffleState()
                              const winnerEndingBalance = await accounts[0].getBalance()
                              const endingTimeStamp = await raffle.getLastTimeStamp()

                              await expect(raffle.getPlayer(0)).to.be.reverted
                              assert.equal(recentWinner.toString(), accounts[0].address)
                              assert.equal(raffleState, 0)
                              assert.equal(
                                  winnerEndingBalance.toString(),
                                  winnerStartingBalance.add(raffleEntranceFee).toString()
                              )
                              assert(endingTimeStamp > startingTimeStamp)
                              resolve()
                          } catch (error) {
                              console.log(error)
                              reject(error)
                          }
                      })
                      // Then entering the raffle
                      console.log("Entering Raffle...")
                      const tx = await raffle.enterRaffle({ value: raffleEntranceFee })
                      await tx.wait(1)
                      console.log("Ok, time to wait...")
                      const winnerStartingBalance = await accounts[0].getBalance()

                      // and this code WONT complete until our listener has finished listening!
                  })
              })
          })
      })

Can anyone help me out with these, here's the link to my repo: https://github.com/anooj1/hardhat-raffle


问:
Nattable tree hierarchy change to show children modules first
I want a particular desired behavior for my Nattable tree structure. In the following diagram, contents of Row no 36, 37 are children of content in Row 20.

Row 21, 23, 23 … 34 are in turn children of Row 20.

Row 22 is a child of Row 21. (you could say it is grandchild of 20)

I want Row 36, 37 to be shown first ie. In place of Row 21 and so on, that is I want to change the order in which it is shown as a child of Row 20.

I am currently using a treelist implementation to render my data in the Nattable.

My current nattable:

 private List<ISectionInfo> getFlatList(List<ISectionInfo> inputList)
 {
     List<ISectionInfo> flatList = new ArrayList<ISectionInfo>();

     for (ISectionInfo node : inputList)
     {

         if (node instanceof SectionInfo)
         {
             SectionInfo secNode = (SectionInfo) node;

             if (!hasChildren(secNode))
             {
                 flatList.add(secNode);
                 flatList.addAll(secNode.getModuleInfoList());

             }
             if (hasChildren(secNode))
             {
                 flatList.addAll(secNode.getModuleInfoList());
                 flatList.add(secNode);

                 for (ISectionInfo iternode : secNode.getChildren())
                 {
                     flatList.addAll(((SectionInfo) iternode).getModuleInfoList());
                     flatList.add(iternode);

                 }

             }
         }

     }

     return flatList;

 }
```


问:
Why does kivy keep freezing when using python sockets?
I'm working on a basic client-server desktop app project using kivy & sockets & threading.
The client & server work on it's own, however when I try to integrate it with kivy, python & kivy don't want to respond & yet no definitive error pops up.

Could i have some ideas as to how to fix this?

This is the code that freezes when i run it, if i take away the import server_sock it works as a general gui and doesnt freeze.

```<code>import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.clock import Clock
import server_sock
import sys
kivy.require("2.1.0") #latest version

class ConnectPage(GridLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.cols = 2

        self.add_widget(Label(text="IP:"))
        self.ip = TextInput(multiline=False)
        self.add_widget(self.ip)

        self.add_widget(Label(text="PORT:"))
        self.port = TextInput(multiline=False)
        self.add_widget(self.port)

        self.add_widget(Label(text="USERNAME:"))
        self.user = TextInput(multiline=False)
        self.add_widget(self.user)

        self.join = Button(text="Join")
        self.join.bind(on_press=self.join_button)
        self.add_widget(Label())
        self.add_widget(self.join)

    def join_button(self, instance):
        port = self.port.text
        ip = self.ip.text
        user = self.user.text

        info = f"Attempting to join {ip}:{port} as {user}"
        chat_app.info_page.update_info(info)
        chat_app.screen_manager.current = "Info"
        Clock.shedule_once(self.connect,1)

    def connect(self, _):
        port = int(self.port.text)
        ip = self.ip.text
        user = self.user.text

        try:
            server_sock.connect(ip, port)
            chat_app.create_chat_page()
            chat_app.screen_manager.current = "Chat"

        except:
            show_error(message="not gonna happen")

class InfoPage(GridLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.cols = 1
        self.message = Label(halign="center", valign="middle", font_size="30")
        self.message.bind(width=self.update_text_width)
        self.add_widget(self.message)
    def update_info(self,message):
        self.message.text = message

    def update_text_width(self, *_):
        self.message.text_size = (self.message.width*0.9, None)

class ChatPage(GridLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.cols = 1
        self.add_widget(Label(text="Hey at least it works till now"))

class ChatApp(App):
    def build(self):
        self.screen_manager = ScreenManager()
        self.connect_page = ConnectPage()
        screen = Screen(name="Connect")
        screen.add_widget(self.connect_page)
        self.screen_manager.add_widget(screen)

        self.info_page = InfoPage()
        screen= Screen(name="Info")
        screen.add_widget(self.info_page)
        self.screen_manager.add_widget(screen)

        return self.screen_manager

    def create_chat_page(self):
        self.chat_page = ChatPage()
        screen = Screen(name="Chat")
        screen.add_widget(self.chat_page)
        self.screen_manager.add_widget(screen)

def show_error(message):
    chat_app.info_page.update_info(message)
    chat_app.screen_manager.current = "Info"
    Clock.shedule_once(sys.exit, 10)

if __name__ == "__main__":
    chat_app =ChatApp()
    chat_app.run()

</code>```

This is the server_sock file

```<code>import socket
import threading

import socket
HOST = '127.0.0.1'
PORT = 55555

server = socket.socket(
    socket.AF_INET,
    socket.SOCK_STREAM
)

try:
     server.bind((HOST, PORT))
except:
    print(f'unable to bind to {HOST} and {PORT}')

server.listen()
print(f"Listening for connections on {HOST}: {PORT}")
clients = []
nicknames = []

def broadcast(message):
        for client in clients:
            client.send(message)

def message_recv(client):
    while True:
        try:
            message = client.recv(2048)
            broadcast(message)
        except:
            index = clients.index(client)
            clients.remove(client)
            nickname = nicknames[index]
            broadcast(f'{nickname} left the chat'.encode('ascii'))
            nicknames.remove(nickname)
            break

def recieve():
    while True:
        client, address = server.accept()
        print(f"Connected with {str(address)}")

        client.send("SOMETHING".encode('ascii'))
        nickname = client.recv(2048).decode('ascii')
        nicknames.append(nickname)
        clients.append(client)

        print(f"Nickname of the client is {nickname}")
        broadcast(f"{nickname} joined the chat".encode('ascii'))
        client.send("Connected to the server".encode('ascii'))

        thread = threading.Thread(target=message_recv, args=(client,))
        thread.start()

print("Server is listening")
recieve()
</code>```

Body:
I'm working on a basic client-server desktop app project using kivy & sockets & threading.
The client & server work on it's own, however when I try to integrate it with kivy, python & kivy don't want to respond & yet no definitive error pops up.

Could i have some ideas as to how to fix this?

This is the code that freezes when i run it, if i take away the import server_sock it works as a general gui and doesnt freeze.

import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.clock import Clock
import server_sock
import sys
kivy.require("2.1.0") #latest version

class ConnectPage(GridLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.cols = 2

        self.add_widget(Label(text="IP:"))
        self.ip = TextInput(multiline=False)
        self.add_widget(self.ip)

        self.add_widget(Label(text="PORT:"))
        self.port = TextInput(multiline=False)
        self.add_widget(self.port)

        self.add_widget(Label(text="USERNAME:"))
        self.user = TextInput(multiline=False)
        self.add_widget(self.user)

        self.join = Button(text="Join")
        self.join.bind(on_press=self.join_button)
        self.add_widget(Label())
        self.add_widget(self.join)

    def join_button(self, instance):
        port = self.port.text
        ip = self.ip.text
        user = self.user.text

        info = f"Attempting to join {ip}:{port} as {user}"
        chat_app.info_page.update_info(info)
        chat_app.screen_manager.current = "Info"
        Clock.shedule_once(self.connect,1)

    def connect(self, _):
        port = int(self.port.text)
        ip = self.ip.text
        user = self.user.text

        try:
            server_sock.connect(ip, port)
            chat_app.create_chat_page()
            chat_app.screen_manager.current = "Chat"

        except:
            show_error(message="not gonna happen")

class InfoPage(GridLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.cols = 1
        self.message = Label(halign="center", valign="middle", font_size="30")
        self.message.bind(width=self.update_text_width)
        self.add_widget(self.message)
    def update_info(self,message):
        self.message.text = message

    def update_text_width(self, *_):
        self.message.text_size = (self.message.width*0.9, None)

class ChatPage(GridLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.cols = 1
        self.add_widget(Label(text="Hey at least it works till now"))

class ChatApp(App):
    def build(self):
        self.screen_manager = ScreenManager()
        self.connect_page = ConnectPage()
        screen = Screen(name="Connect")
        screen.add_widget(self.connect_page)
        self.screen_manager.add_widget(screen)

        self.info_page = InfoPage()
        screen= Screen(name="Info")
        screen.add_widget(self.info_page)
        self.screen_manager.add_widget(screen)

        return self.screen_manager

    def create_chat_page(self):
        self.chat_page = ChatPage()
        screen = Screen(name="Chat")
        screen.add_widget(self.chat_page)
        self.screen_manager.add_widget(screen)

def show_error(message):
    chat_app.info_page.update_info(message)
    chat_app.screen_manager.current = "Info"
    Clock.shedule_once(sys.exit, 10)

if __name__ == "__main__":
    chat_app =ChatApp()
    chat_app.run()

This is the server_sock file

import socket
import threading

import socket
HOST = '127.0.0.1'
PORT = 55555

server = socket.socket(
    socket.AF_INET,
    socket.SOCK_STREAM
)

try:
     server.bind((HOST, PORT))
except:
    print(f'unable to bind to {HOST} and {PORT}')

server.listen()
print(f"Listening for connections on {HOST}: {PORT}")
clients = []
nicknames = []

def broadcast(message):
        for client in clients:
            client.send(message)

def message_recv(client):
    while True:
        try:
            message = client.recv(2048)
            broadcast(message)
        except:
            index = clients.index(client)
            clients.remove(client)
            nickname = nicknames[index]
            broadcast(f'{nickname} left the chat'.encode('ascii'))
            nicknames.remove(nickname)
            break

def recieve():
    while True:
        client, address = server.accept()
        print(f"Connected with {str(address)}")

        client.send("SOMETHING".encode('ascii'))
        nickname = client.recv(2048).decode('ascii')
        nicknames.append(nickname)
        clients.append(client)

        print(f"Nickname of the client is {nickname}")
        broadcast(f"{nickname} joined the chat".encode('ascii'))
        client.send("Connected to the server".encode('ascii'))

        thread = threading.Thread(target=message_recv, args=(client,))
        thread.start()

print("Server is listening")
recieve()


问:
Im following the Spring MySql data access walkthrough and I keep getting "Unable to determine Dialect without JDBC metadata."
During the walkthrough I have added the specified model, controller and repo. I have added all the required dependencies through spring boot (I beleive) as well as creating the DB through the MySql shell.

The db is the same as the example as well as the basic root user until I can get this to work then will add another user.

Any help would be appreciated as I have had this same issue every single time I have tried to set up a db.

My model

```<code>package com.avorion.dndwiki.Model;

import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id;

@Entity // This tells Hibernate to make a table out of this class public class User {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO) private Integer id;

private String name;

private String email;

public Integer getId() { return id;
    }

public void setId(Integer id) { this.id = id;
    }

public String getName() { return name;
    }

public void setName(String name) { this.name = name;
    }

public String getEmail() { return email;
    }

public void setEmail(String email) { this.email = email;
    } }
</code>```

My Controller

```<code>package com.avorion.dndwiki.Controller;

import com.avorion.dndwiki.Model.User; import com.avorion.dndwiki.Repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody;

@Controller // This means that this class is a Controller @RequestMapping(path="/demo") // This means URL's start with /demo (after Application path) public class MainController {
    @Autowired // This means to get the bean called userRepository Which is auto-generated by Spring, we will use it to handle the data private UserRepository userRepository;

    @PostMapping(path="/add") // Map ONLY POST Requests public @ResponseBody String addNewUser (@RequestParam String name
            , @RequestParam String email) {
        // @ResponseBody means the returned String is the response, not a view name
        // @RequestParam means it is a parameter from the GET or POST request

User n = new User(); n.setName(name); n.setEmail(email); userRepository.save(n); return "Saved";
    }

    @GetMapping(path="/all") public @ResponseBody Iterable<User> getAllUsers() { This returns a JSON or XML with the users return userRepository.findAll();
    } }
</code>```

My Repo

```<code>package com.avorion.dndwiki.Repository;

import com.avorion.dndwiki.Model.User; import org.springframework.data.repository.CrudRepository;

//This will be AUTO IMPLEMENTED by Spring into a Bean called userRepository CRUD refers Create, Read, Update, Delete

public interface UserRepository extends CrudRepository<User, Integer> {

}
</code>```

My application properties

```<code>spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/db_example
spring.datasource.username=root@localhost
spring.datasource.password=thisIsntMyActualPassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#spring.jpa.show-sql: true
</code>```

My Pom(Theres a lot here,im just practicing)

```<code><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.Avorion</groupId>
    <artifactId>DnDWiki</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>DnDWiki</name>
    <description>DnDWiki</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.kafka</groupId>
            <artifactId>spring-kafka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-core</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.kafka</groupId>
            <artifactId>spring-kafka-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

I have tried to set up a number of db with diffrent users and naming conventions. I have reset MySql as well as asking other software engineers.

Body:
During the walkthrough I have added the specified model, controller and repo. I have added all the required dependencies through spring boot (I beleive) as well as creating the DB through the MySql shell.

The db is the same as the example as well as the basic root user until I can get this to work then will add another user.

Any help would be appreciated as I have had this same issue every single time I have tried to set up a db.

My model

package com.avorion.dndwiki.Model;

import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id;

@Entity // This tells Hibernate to make a table out of this class public class User {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO) private Integer id;

private String name;

private String email;

public Integer getId() { return id;
    }

public void setId(Integer id) { this.id = id;
    }

public String getName() { return name;
    }

public void setName(String name) { this.name = name;
    }

public String getEmail() { return email;
    }

public void setEmail(String email) { this.email = email;
    } }

My Controller

package com.avorion.dndwiki.Controller;

import com.avorion.dndwiki.Model.User; import com.avorion.dndwiki.Repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody;

@Controller // This means that this class is a Controller @RequestMapping(path="/demo") // This means URL's start with /demo (after Application path) public class MainController {
    @Autowired // This means to get the bean called userRepository Which is auto-generated by Spring, we will use it to handle the data private UserRepository userRepository;

    @PostMapping(path="/add") // Map ONLY POST Requests public @ResponseBody String addNewUser (@RequestParam String name
            , @RequestParam String email) {
        // @ResponseBody means the returned String is the response, not a view name
        // @RequestParam means it is a parameter from the GET or POST request

User n = new User(); n.setName(name); n.setEmail(email); userRepository.save(n); return "Saved";
    }

    @GetMapping(path="/all") public @ResponseBody Iterable<User> getAllUsers() { This returns a JSON or XML with the users return userRepository.findAll();
    } }

My Repo

package com.avorion.dndwiki.Repository;

import com.avorion.dndwiki.Model.User; import org.springframework.data.repository.CrudRepository;

//This will be AUTO IMPLEMENTED by Spring into a Bean called userRepository CRUD refers Create, Read, Update, Delete

public interface UserRepository extends CrudRepository<User, Integer> {

}

My application properties

spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/db_example
spring.datasource.username=root@localhost
spring.datasource.password=thisIsntMyActualPassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#spring.jpa.show-sql: true

My Pom(Theres a lot here,im just practicing)

<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.1</version>
        <relativePath/>
    </parent>
    <groupId>com.Avorion</groupId>
    <artifactId>DnDWiki</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>DnDWiki</name>
    <description>DnDWiki</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.kafka</groupId>
            <artifactId>spring-kafka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-core</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.kafka</groupId>
            <artifactId>spring-kafka-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

I have tried to set up a number of db with diffrent users and naming conventions. I have reset MySql as well as asking other software engineers.


问:
How can I add generic types to createAsyncThunk?
I am attempting to add generic types to a call to createAsyncFunc in the following way;

export const myFunction = createAsyncThunk<
  { property: TypedResponse<T> } | undefined,
  Array<keyof T>
>("my/feature", async (param, thunkAPI) => {})
```
<p>However I cannot figure out where to put the generic type <code>T</code> which is then passed to <code>createAsyncFunc</code>'s types.</p>
<p>Is this possible without wrapping the function? Otherwise I would wrap it with;</p>
<pre class="lang-js prettyprint-override"><code>export const myFunction = (param: Array<keyof T>) => createAsyncThunk<
  { property: TypedResponse<T> } | undefined,
  Array<keyof T>
>("my/feature", async (param, thunkAPI) => {})()
</code>```

Body:
I am attempting to add generic types to a call to createAsyncFunc in the following way;

export const myFunction = createAsyncThunk<
  { property: TypedResponse<T> } | undefined,
  Array<keyof T>
>("my/feature", async (param, thunkAPI) => {})

However I cannot figure out where to put the generic type T which is then passed to createAsyncFunc's types.

Is this possible without wrapping the function? Otherwise I would wrap it with;

export const myFunction = (param: Array<keyof T>) => createAsyncThunk<
  { property: TypedResponse<T> } | undefined,
  Array<keyof T>
>("my/feature", async (param, thunkAPI) => {})()


问:
Why is a GET request mapped to "/error" in Spring-Boot?
When I send a GET request to /todo-list/user/list
it was mapped to /error.

Code

Interceptor:

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    HandlerMethod handlerMethod = (HandlerMethod) handler;

    RequestMapping classMapping = handlerMethod.getMethod().getDeclaringClass().getAnnotation(RequestMapping.class);
    // when debugging: classMapping.value() was "${server.error.path:${error.path:/error}}"
    RequestMapping methodMapping = handlerMethod.getMethodAnnotation(RequestMapping.class);

    //some other codes
```
<p>Controller:</p>
<pre class="lang-java prettyprint-override"><code>//the contexPath is "/todo-list"
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController
</code>```

Method

@GetMapping(value = "/list")
public @ResponseBody Page<UserProjection> listGrid() {
    return userService.listGrid();
}
```

I checked the address and method and whatever I think is the reason.
When debugging my code, classMapping.value() was equal to "${server.error.path:${error.path:/error}}".

What is the problem?

Body:
When I send a GET request to /todo-list/user/list
it was mapped to /error.

Code

Interceptor:

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    HandlerMethod handlerMethod = (HandlerMethod) handler;

    RequestMapping classMapping = handlerMethod.getMethod().getDeclaringClass().getAnnotation(RequestMapping.class);
    // when debugging: classMapping.value() was "${server.error.path:${error.path:/error}}"
    RequestMapping methodMapping = handlerMethod.getMethodAnnotation(RequestMapping.class);

    //some other codes

Controller:

//the contexPath is "/todo-list"
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController

Method

@GetMapping(value = "/list")
public @ResponseBody Page<UserProjection> listGrid() {
    return userService.listGrid();
}

I checked the address and method and whatever I think is the reason.
When debugging my code, classMapping.value() was equal to "${server.error.path:${error.path:/error}}".

What is the problem?


问:
Blazor EditForm: How to handle empty values same as undefined
I am using an EditForm component with validations in Blazor WASM app.
The problem I have is that if I enter an input to InputText and then later decide remove it, the form acts as if I entered empty value. The consequences are either

The field turns red since the value is invalid due to constraints such as [MinLength]

The field turns green if there is no constraint on length

I would like it to act the same as if the input was never entered. So, basically, skip the validation. In ideal world, I would also like to have null instead of empty string in the bind model, but that is not as critical, since I can arrange that in submit action.

Any ideas how to simply achieve this?


问:
Pointer events don't support simultaneous mouse buttons
While mousedown/mouseup can handel multiple mouse buttons and pointerdown/pointerup can handle multitouch, pointerdown/pointerup can not handle two or more simultaneous mouse buttons. (Tested in Chrome/Firefox on Windows)

As expected mouse events:

```<code>mousedown, button: 0
mousedown, button: 1
mouseup, button: 0
mouseup, button: 1
</code>```

Unexpected with pointer events:

```<code>pointerdown, button: 0
// button 1 pressed, nothing
// button 0 release, nothing
pointerup, button: 1
</code>```

Demo:

window.addEventListener('pointerdown', (e) => {
  console.log('pointerdown', e.pointerId, e.pointerType, e.button)
})
window.addEventListener('pointerup', (e) => {
  console.log('pointerup', e.pointerId, e.pointerType, e.button)
})
window.addEventListener('mousedown', (e) => {
  console.log('mousedown', e.button)
})
window.addEventListener('mouseup', (e) => {
  console.log('mouseup', e.button)
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Click anywhere</code>```

Is this to be expected or a (known) bug?

When do you need this? E.g. panning a surface with middle mouse button, while selecting with left mouse button.

Body:
While mousedown/mouseup can handel multiple mouse buttons and pointerdown/pointerup can handle multitouch, pointerdown/pointerup can not handle two or more simultaneous mouse buttons. (Tested in Chrome/Firefox on Windows)

As expected mouse events:

mousedown, button: 0
mousedown, button: 1
mouseup, button: 0
mouseup, button: 1

Unexpected with pointer events:

pointerdown, button: 0
// button 1 pressed, nothing
// button 0 release, nothing
pointerup, button: 1

Demo:

window.addEventListener('pointerdown', (e) => {
  console.log('pointerdown', e.pointerId, e.pointerType, e.button)
})
window.addEventListener('pointerup', (e) => {
  console.log('pointerup', e.pointerId, e.pointerType, e.button)
})
window.addEventListener('mousedown', (e) => {
  console.log('mousedown', e.button)
})
window.addEventListener('mouseup', (e) => {
  console.log('mouseup', e.button)
})

Click anywhere

Is this to be expected or a (known) bug?

When do you need this? E.g. panning a surface with middle mouse button, while selecting with left mouse button.


问:
routes: match '*path' does not catch POST /
I am using this rule:

match '*path', via: :all, to: 'application#index'
```
<p>to redirect all unknown routes to <code>application#index</code>.</p>
<p>However, it does not catch <code>POST /</code>, it returns the following error:</p>
```No route matches [POST] "/"
```

Is there a way to include this path without adding more rules?

Body:
I am using this rule:

match '*path', via: :all, to: 'application#index'

to redirect all unknown routes to application#index.

However, it does not catch POST /, it returns the following error:

No route matches [POST] "/"

Is there a way to include this path without adding more rules?


问:
Django - Disable editing via view button
I am making a customer portal on django and on the admin panel i have created a list for all the users in the database.

Apart from that i have also added 3 buttons in my table to View, Edit and Delete as shown:

Now the problem is that when i click edit or delete button the code runs as it is intended to do.
But when i click the view button it still allows the person to modify the details. I only want to use it as read-only.

Can someone please help?

This is my admin.py

```<code>    from django.contrib import admin
    from .models import Customer
    from .forms import CustomerForm
    from django.http import HttpResponse
    from django.utils.html import format_html

    # Write your models here
    class CustomerAdmin(admin.ModelAdmin):
        form=CustomerForm
        list_display = ['id','first_name','last_name','profile_picture', 'gender', 'date_of_birth', 'email', 'phone_number', 'address', 'marry_status','country','state','city','view_button', 'edit_button', 'delete_button']
        list_display_links = ['id']
        ordering = ('id',)

        def view_button(self, obj):
            return format_html('<a class="button" style="background-color: darkgreen;" " href="/admin/customer_form/customer/{}/">View</a>'.format(obj.id))
        view_button.allow_tags = True
        view_button.short_description = 'View'

        def edit_button(self, obj):
            return format_html ('<a class="button" style="color: black; background-color: yellow;" href="/admin/customer_form/customer/{}/change/">Edit</a>'.format(obj.id))
        edit_button.allow_tags = True
        edit_button.short_description = 'Edit'

        def delete_button(self, obj):
            return format_html('<a class="button" style="background-color: #ba2121;" href="/admin/customer_form/customer/{}/delete/">Delete</a>'.format(obj.id))
        delete_button.allow_tags = True
        delete_button.short_description = 'Delete'

admin.site.register(Customer, CustomerAdmin)
</code>```

Body:
I am making a customer portal on django and on the admin panel i have created a list for all the users in the database.

Apart from that i have also added 3 buttons in my table to View, Edit and Delete as shown:

Now the problem is that when i click edit or delete button the code runs as it is intended to do.
But when i click the view button it still allows the person to modify the details. I only want to use it as read-only.

Can someone please help?

This is my admin.py

    from django.contrib import admin
    from .models import Customer
    from .forms import CustomerForm
    from django.http import HttpResponse
    from django.utils.html import format_html

    # Write your models here
    class CustomerAdmin(admin.ModelAdmin):
        form=CustomerForm
        list_display = ['id','first_name','last_name','profile_picture', 'gender', 'date_of_birth', 'email', 'phone_number', 'address', 'marry_status','country','state','city','view_button', 'edit_button', 'delete_button']
        list_display_links = ['id']
        ordering = ('id',)

        def view_button(self, obj):
            return format_html('View'.format(obj.id))
        view_button.allow_tags = True
        view_button.short_description = 'View'

        def edit_button(self, obj):
            return format_html ('Edit'.format(obj.id))
        edit_button.allow_tags = True
        edit_button.short_description = 'Edit'

        def delete_button(self, obj):
            return format_html('Delete'.format(obj.id))
        delete_button.allow_tags = True
        delete_button.short_description = 'Delete'

admin.site.register(Customer, CustomerAdmin)