问:
flutter Carousel probem
I crated flutter Carousel, but it is look like that,Moto 40 mobile display look like

every Property I changed and re check that,

Title: flutter Carousel probem


来源: stackexchange

问:
Legend boxes are not changing colour
I have a legend for a bar series chart.  The boxes (they could be known as something else) stay the original colour instead of changing when a bar changes colour.  The same program has another bar chart with a legend that works correctly.  I have tried a lot of setting changes.  I can't see any difference between my two charts.

I have tried many settings and still can't get it working.

ContentLicense: CC BY-SA 4.0

Title: Legend boxes are not changing colour


问:
Error message: Error in data$CVDSTRK3 : object of type 'closure' is not subsettable
```<code>Q<-patients_with_stroke <- data[data$CVDSTRK3==1,]
max_numwomen<-max(patients_with_stroke$NUMWOMEN, na.rm = TRUE)
max_numwomen
</code>```

Please help. I tried to find the highest value for number of adult women in the household where someone has ever had a stroke and then summarise the value in a variable called max_numwomen   thank you

Body:
Q<-patients_with_stroke <- data[data$CVDSTRK3==1,]
max_numwomen<-max(patients_with_stroke$NUMWOMEN, na.rm = TRUE)
max_numwomen

Please help. I tried to find the highest value for number of adult women in the household where someone has ever had a stroke and then summarise the value in a variable called max_numwomen   thank you


问:
AutoFilter.Sort.SortFields.Clear is not clearing the sort fields
I have VBA code that uses the columns (values in the Rows section) of a Pivot table on one worksheet to sort another worksheet's data and then summarize that data.  Whenever the Pivot table changes the summarized data is recalculated by users pushing a command button.  After I run the AutoFilter.Sort.SortFields.Clear I'm still getting 13 sorts exist.  These are combinations of the previous sorts.  This continues to build up until I get a XLSM file is corrupt message.

```<code>Function SortTab(pSheet As String, pCol As String) As Boolean
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Sort entire tab by 1 to 5 columns
'
'Code examples from recording a Macro when sorting
'    ActiveWorkbook.Worksheets("Data").AutoFilter.Sort.SortFields.Add Key:=Range("I2:I1019"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
'    ActiveWorkbook.Worksheets("Data").AutoFilter.Sort.SortFields.Add Key:=Range("J2:J1019"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
'
'Parameters:
' pSheet    Sheet to find range     Example: Data
' pCol      Last column on sheet    Example: BC100
'
'Global Variables:
' gRange        UsedRange for current sheet Example: A1:BC100
' gPivotCols    Array of column names to Sort   Example: gPivotCols(1) = 5 for "Dept", gPivotCols(2) =  4 for "Company"
' gColSort  Last column in the sort     Example: 4 for the Company column being the 4th column in the data sheet
'gColMax        Max # of Sort Columns is 5
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
On Error GoTo Err_SortTab

    Dim i           As Integer

    'Remove all Fiters & Sorts
    Worksheets(pSheet).Activate                             'Select sheet
    Worksheets(pSheet).AutoFilterMode = False               'Turn AutoFilter off
    Worksheets(pSheet).UsedRange.AutoFilter                 'Turn AutoFilter on
    Worksheets(pSheet).AutoFilter.Sort.SortFields.Clear     'Clear any Sorts

'Code inserted to find out how many sort columns exist after a AutoFilter.Sort.SortFields.Clear
'Currently returning a value of 13 sorts
i = ExistingSorts()
If i > 0 Then
    MsgBox i & " existing sorts still exist", vbCritical, "Error"
    SortTab = False
    Exit Function
End If

    With ActiveSheet.Sort
        .Header = xlYes                 'Tab has Headers
        .MatchCase = False              'Not case sensitive
        .Orientation = xlTopToBottom    'Sort Top to Bottom
        .SetRange Range(gRange)         'Complete range on Data tab to sort example: A1:BC100

        For i = 1 To gColMax            'Loop throuh column heading in the Pivot table
            If gPivotCols(i) = 0 Then   'Check for less than 5 columns
                Exit For
            End If
            gColSort = gPivotCols(i)    'Set the last column in the Sort

           .SortFields.Add Key:=Range(gRange).Columns(gColSort), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal       'Add sort column

        Next i
        .Apply
    End With

Exit_SortTab:
    SortTab = True
    Exit Function

Err_SortTab:
    If Application.UserName = "Murf" Then
        MsgBox Err.Description, vbOKOnly, "Error #: " & Err.Number
        Stop
        Resume
    End If

End Function

Function ExistingSorts() As Integer
'''''''''''''''''''''''''''''''''''''''''''''''''''
' Copied from internet
' Count existing sorts
'''''''''''''''''''''''''''''''''''''''''''''''''''
On Error Resume Next

    Dim S   As Sort
    Dim SF  As SortField

    Set S = ActiveSheet.Sort

    ExistingSorts = S.SortFields.Count

End Function
</code>```

I've tried several different variations of

Worksheets(pSheet).AutoFilter.Sort.SortFields.Clear

Activesheet.AutoFilter.Sort.SortFields.Clear

with Activesheet
.AutoFilter.Sort.SortFields.Clear

The manual sorts created on the data tab disappear (arrows go away) but the actual data is sorted by whatever string of columns is already entered.

Body:
I have VBA code that uses the columns (values in the Rows section) of a Pivot table on one worksheet to sort another worksheet's data and then summarize that data.  Whenever the Pivot table changes the summarized data is recalculated by users pushing a command button.  After I run the AutoFilter.Sort.SortFields.Clear I'm still getting 13 sorts exist.  These are combinations of the previous sorts.  This continues to build up until I get a XLSM file is corrupt message.

Function SortTab(pSheet As String, pCol As String) As Boolean
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Sort entire tab by 1 to 5 columns
'
'Code examples from recording a Macro when sorting
'    ActiveWorkbook.Worksheets("Data").AutoFilter.Sort.SortFields.Add Key:=Range("I2:I1019"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
'    ActiveWorkbook.Worksheets("Data").AutoFilter.Sort.SortFields.Add Key:=Range("J2:J1019"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
'
'Parameters:
' pSheet    Sheet to find range     Example: Data
' pCol      Last column on sheet    Example: BC100
'
'Global Variables:
' gRange        UsedRange for current sheet Example: A1:BC100
' gPivotCols    Array of column names to Sort   Example: gPivotCols(1) = 5 for "Dept", gPivotCols(2) =  4 for "Company"
' gColSort  Last column in the sort     Example: 4 for the Company column being the 4th column in the data sheet
'gColMax        Max # of Sort Columns is 5
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
On Error GoTo Err_SortTab

    Dim i           As Integer

    'Remove all Fiters & Sorts
    Worksheets(pSheet).Activate                             'Select sheet
    Worksheets(pSheet).AutoFilterMode = False               'Turn AutoFilter off
    Worksheets(pSheet).UsedRange.AutoFilter                 'Turn AutoFilter on
    Worksheets(pSheet).AutoFilter.Sort.SortFields.Clear     'Clear any Sorts

'Code inserted to find out how many sort columns exist after a AutoFilter.Sort.SortFields.Clear
'Currently returning a value of 13 sorts
i = ExistingSorts()
If i > 0 Then
    MsgBox i & " existing sorts still exist", vbCritical, "Error"
    SortTab = False
    Exit Function
End If

    With ActiveSheet.Sort
        .Header = xlYes                 'Tab has Headers
        .MatchCase = False              'Not case sensitive
        .Orientation = xlTopToBottom    'Sort Top to Bottom
        .SetRange Range(gRange)         'Complete range on Data tab to sort example: A1:BC100

        For i = 1 To gColMax            'Loop throuh column heading in the Pivot table
            If gPivotCols(i) = 0 Then   'Check for less than 5 columns
                Exit For
            End If
            gColSort = gPivotCols(i)    'Set the last column in the Sort

           .SortFields.Add Key:=Range(gRange).Columns(gColSort), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal       'Add sort column

        Next i
        .Apply
    End With

Exit_SortTab:
    SortTab = True
    Exit Function

Err_SortTab:
    If Application.UserName = "Murf" Then
        MsgBox Err.Description, vbOKOnly, "Error #: " & Err.Number
        Stop
        Resume
    End If

End Function

Function ExistingSorts() As Integer
'''''''''''''''''''''''''''''''''''''''''''''''''''
' Copied from internet
' Count existing sorts
'''''''''''''''''''''''''''''''''''''''''''''''''''
On Error Resume Next

    Dim S   As Sort
    Dim SF  As SortField

    Set S = ActiveSheet.Sort

    ExistingSorts = S.SortFields.Count

End Function

I've tried several different variations of

Worksheets(pSheet).AutoFilter.Sort.SortFields.Clear

Activesheet.AutoFilter.Sort.SortFields.Clear

with Activesheet
.AutoFilter.Sort.SortFields.Clear

The manual sorts created on the data tab disappear (arrows go away) but the actual data is sorted by whatever string of columns is already entered.


问:
how to export WBlock by using pyautocad
hi all i have this problem when i try to export object through WBlock what is wrong there i'm try to do simple python work (note: i'm beginners :D)  .. any help

```<code>
from pyautocad import Autocad, APoint,utils
import win32com.client

AutoCAD = win32com.client.dynamic.Dispatch("AutoCAD.Application")
acad = Autocad(create_if_not_exists = False)
acad.Visible=True

doc = AutoCAD.ActiveDocument
layersList = doc.Layers
for l in layersList:
    object = acad.iter_objects()
    if l.name == "0":
        pass
    else:
        for o in object:
            if o.ObjectName == "AcDbText":
                SelectionSet = doc.SelectionSets.Item(o.ObjectName).Name
                directoryN = "C:\\Temp\\{}_{}.dwg".format(l.name,o.TextString)
                doc.WBlock(directoryN,SelectionSet)

</code>```

here what i Get

```<code>AcDbText
Traceback (most recent call last):
  File "C:/Temp/Exporter.py", line 23, in <module>
    doc.WBlock(directoryN,SelectionSet)
  File "<COMObject <unknown>>", line 2, in WBlock
pywintypes.com_error: (-2147352571, 'Type mismatch.', None, 2)

</code>```

thanks

i'm try to export every text as WBlock

Title: how to export WBlock by using pyautocad

Body:
hi all i have this problem when i try to export object through WBlock what is wrong there i'm try to do simple python work (note: i'm beginners :D)  .. any help

from pyautocad import Autocad, APoint,utils
import win32com.client

AutoCAD = win32com.client.dynamic.Dispatch("AutoCAD.Application")
acad = Autocad(create_if_not_exists = False)
acad.Visible=True

doc = AutoCAD.ActiveDocument
layersList = doc.Layers
for l in layersList:
    object = acad.iter_objects()
    if l.name == "0":
        pass
    else:
        for o in object:
            if o.ObjectName == "AcDbText":
                SelectionSet = doc.SelectionSets.Item(o.ObjectName).Name
                directoryN = "C:\\Temp\\{}_{}.dwg".format(l.name,o.TextString)
                doc.WBlock(directoryN,SelectionSet)

here what i Get

AcDbText
Traceback (most recent call last):
  File "C:/Temp/Exporter.py", line 23, in <module>
    doc.WBlock(directoryN,SelectionSet)
  File "<COMObject <unknown>>", line 2, in WBlock
pywintypes.com_error: (-2147352571, 'Type mismatch.', None, 2)

thanks

i'm try to export every text as WBlock


问:
Django: How to store data in Form #1 while filling up Forms #2 and #3 and autoselect data from Forms #2 and #3 into Form #1?
I have a Vinyl model form (Form #1) that creates vinyl with the following fields: artist (ManyToManyField), title, record label (ForeignKey), cat.number, release date, cover art, price, genre, style, tracklist, quantity, and condition. Under artist and record label there are buttons that allow the user to create new entities. When pressing the "Add new artist" button, a new form (Form #2) is shown and I would like to have the already added data in Form 1 to be preserved and get the data from Form #2 populated into Form 1.

Example:
The artist I'm looking for is not on the list of artists in Form 1. I click "Add new artist" and Form #2 appears. I fill in the data and when clicking submit, I get redirected to Form #1. I want this new artist to be autoselected. Then I write the title. Then I see that the record label is not on the list of record labels so I click "Add new label". Form #3 is shown and I fill in the data. When clicking the submit button I'm redirected to Form #1. I would like to have all the previously added data and also the newly generated record label to be selected.

How can I achieve this?

models.py

class Vinyl(models.Model):
    artist = models.ManyToManyField(Artist)
    title = models.CharField(max_length=222)
    cat_number = models.CharField(max_length=20, unique=True, null=True, blank=True)
    release_date = models.DateField(null=True, blank=True)
    price = models.FloatField(validators=[
        MinValueValidator(0.01),
        MaxValueValidator(1000000),
    ], null=True, blank=True)
    record_label = models.ForeignKey(RecordLabel, on_delete=models.CASCADE, null=True, blank=True)
    cover_art = ImageField(upload_to=get_upload_path, null=True, blank=True)
    genre = models.ForeignKey(Genre, on_delete=models.CASCADE, null=True, blank=True)
    style = ChainedForeignKey(Style,
                              chained_field='genre',
                              chained_model_field='genre',
                              show_all=False,
                              sort=True,
                              null=True,
                              blank=True)
    tracklist = models.TextField(null=True, blank=True)
    quantity = models.PositiveIntegerField(null=True, default=1)
    condition = models.CharField(max_length=123, choices=Condition.choices(), null=True, blank=True)
    user = models.ForeignKey(AppUser, on_delete=models.CASCADE)
```
<p><strong>views.py</strong></p>
<pre class="lang-py prettyprint-override"><code>class SellVinylView(LoginRequiredMixin, views.CreateView):
    template_name = 'sell.html'
    form_class = VinylAddForm
    success_url = '/'

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super().form_valid(form)
</code>```

forms.py

class VinylAddForm(forms.ModelForm):
    class Meta:
        model = Vinyl
        exclude = ['user']
```
<p><strong>template</strong></p>
<pre class="lang-html prettyprint-override"><code><form method="post" action="{% url 'sell' %}" enctype="multipart/form-data">
        <p>{{ form.artist.label_tag }} {{ form.artist }}</p>
        <p>Artist not in list? Add new artist</p>
        <p>{{ form.title.label_tag }} {{ form.title }}</p>
        <p>{{ form.record_label.label_tag }} {{ form.record_label }}</p>
        <p>Label not in list? Add new label</p>
        <p>{{ form.cat_number.label_tag }} {{ form.cat_number }}</p>
        <p>{{ form.release_date.label_tag }} {{ form.release_date }}</p>
        <p>{{ form.cover_art.label_tag }} {{ form.cover_art }}</p>
        <p>{{ form.price.label_tag }} {{ form.price }}</p>
        <p>{{ form.genre.label_tag }} {{ form.genre }}</p>
        <p>{{ form.style.label_tag }} {{ form.style }}</p>
        <p>{{ form.tracklist.label_tag }} {{ form.tracklist }}</p>
        <p>{{ form.quantity.label_tag }} {{ form.quantity }}</p>
        <p>{{ form.condition.label_tag }} {{ form.condition }}</p>
        <button>Submit</button>
        {% csrf_token %}
    </form>
</code>```

Body:
I have a Vinyl model form (Form #1) that creates vinyl with the following fields: artist (ManyToManyField), title, record label (ForeignKey), cat.number, release date, cover art, price, genre, style, tracklist, quantity, and condition. Under artist and record label there are buttons that allow the user to create new entities. When pressing the "Add new artist" button, a new form (Form #2) is shown and I would like to have the already added data in Form 1 to be preserved and get the data from Form #2 populated into Form 1.

Example:
The artist I'm looking for is not on the list of artists in Form 1. I click "Add new artist" and Form #2 appears. I fill in the data and when clicking submit, I get redirected to Form #1. I want this new artist to be autoselected. Then I write the title. Then I see that the record label is not on the list of record labels so I click "Add new label". Form #3 is shown and I fill in the data. When clicking the submit button I'm redirected to Form #1. I would like to have all the previously added data and also the newly generated record label to be selected.

How can I achieve this?

models.py

class Vinyl(models.Model):
    artist = models.ManyToManyField(Artist)
    title = models.CharField(max_length=222)
    cat_number = models.CharField(max_length=20, unique=True, null=True, blank=True)
    release_date = models.DateField(null=True, blank=True)
    price = models.FloatField(validators=[
        MinValueValidator(0.01),
        MaxValueValidator(1000000),
    ], null=True, blank=True)
    record_label = models.ForeignKey(RecordLabel, on_delete=models.CASCADE, null=True, blank=True)
    cover_art = ImageField(upload_to=get_upload_path, null=True, blank=True)
    genre = models.ForeignKey(Genre, on_delete=models.CASCADE, null=True, blank=True)
    style = ChainedForeignKey(Style,
                              chained_field='genre',
                              chained_model_field='genre',
                              show_all=False,
                              sort=True,
                              null=True,
                              blank=True)
    tracklist = models.TextField(null=True, blank=True)
    quantity = models.PositiveIntegerField(null=True, default=1)
    condition = models.CharField(max_length=123, choices=Condition.choices(), null=True, blank=True)
    user = models.ForeignKey(AppUser, on_delete=models.CASCADE)

views.py

class SellVinylView(LoginRequiredMixin, views.CreateView):
    template_name = 'sell.html'
    form_class = VinylAddForm
    success_url = '/'

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super().form_valid(form)

forms.py

class VinylAddForm(forms.ModelForm):
    class Meta:
        model = Vinyl
        exclude = ['user']

template

<form method="post" action="{% url 'sell' %}" enctype="multipart/form-data">

{{ form.artist.label_tag }} {{ form.artist }}

Artist not in list? Add new artist

{{ form.title.label_tag }} {{ form.title }}

{{ form.record_label.label_tag }} {{ form.record_label }}

Label not in list? Add new label

{{ form.cat_number.label_tag }} {{ form.cat_number }}

{{ form.release_date.label_tag }} {{ form.release_date }}

{{ form.cover_art.label_tag }} {{ form.cover_art }}

{{ form.price.label_tag }} {{ form.price }}

{{ form.genre.label_tag }} {{ form.genre }}

{{ form.style.label_tag }} {{ form.style }}

{{ form.tracklist.label_tag }} {{ form.tracklist }}

{{ form.quantity.label_tag }} {{ form.quantity }}

{{ form.condition.label_tag }} {{ form.condition }}

        <button>Submit</button>
        {% csrf_token %}
    </form>


问:
emitting of state doesn't seem to work the second time , flutter_bloc
I am working with flutter_bloc and trying to understand how it works entirely.

I have Profile Screen. Where in the User should enter his details if previously not existed else should update the details.

Logic: If the user already exists then i fill up the textfields prior to loading , else the textfields are left blank

Problem: I have worked out of achieving the above mentioned goal , but everything seems to work only the first time , Once i save the profile and come back to the profile page it doesn't load the data and textfields are empty even if the user exists.

User_Cubit

```<code>class UserCubit extends Cubit<UserState> {
  UserCubit() : super(UserInitialState()) {
    checkIfUserExists();
  }
  void checkIfUserExists() {
    emit(UserLoadingState());
    ...
      if (userExists) {
        emit(UserExists(user));
      } else {
        emit(UserNotExists());
      }
    });
  }
</code>```

Profile Screen

```<code>class _MyProfileScreenState extends State<MyProfileScreen> {
  TextEditingController? fullNameController;
  TextEditingController? mailAddressController;
  late UserCubit _userCubit;

  @override
  void initState() {
    fullNameController = TextEditingController();
    mailAddressController = TextEditingController();
    _userCubit = UserCubit(); // initializing the cubit here
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: MultiBlocListener(
          listeners: [
            BlocListener<UserCubit, UserState>(
              listener: (context, state) {
                if (state is UserExists) {
                  appUser = state.user;
                  mailAddressController!.text = appUser!.email; // Loading the fields
                  fullNameController!.text = appUser!.fullName; // Loading the fields
                }
              },
            )
          ],
          child: BlocBuilder<UserCubit, UserState>(
              builder: (context, state) {
            if (state is UserLoadingState) {
              return const Center(child: CircularProgressIndicator());
            }
            return Container(
                  TextFormField() // For fullName
                  TextFormField() // For EmailAddress
            )
       )
    );
}
</code>```

Why does this functionality work only the first time not the consecutive times. Thougth the UserCubit is intialized in initstate ?

Any further suggestions to improve this logic by not initializing the UserCubit on every page render would be also appreciated !!

Body:
I am working with flutter_bloc and trying to understand how it works entirely.

I have Profile Screen. Where in the User should enter his details if previously not existed else should update the details.

Logic: If the user already exists then i fill up the textfields prior to loading , else the textfields are left blank

Problem: I have worked out of achieving the above mentioned goal , but everything seems to work only the first time , Once i save the profile and come back to the profile page it doesn't load the data and textfields are empty even if the user exists.

User_Cubit

class UserCubit extends Cubit<UserState> {
  UserCubit() : super(UserInitialState()) {
    checkIfUserExists();
  }
  void checkIfUserExists() {
    emit(UserLoadingState());
    ...
      if (userExists) {
        emit(UserExists(user));
      } else {
        emit(UserNotExists());
      }
    });
  }

Profile Screen

class _MyProfileScreenState extends State<MyProfileScreen> {
  TextEditingController? fullNameController;
  TextEditingController? mailAddressController;
  late UserCubit _userCubit;

  @override
  void initState() {
    fullNameController = TextEditingController();
    mailAddressController = TextEditingController();
    _userCubit = UserCubit(); // initializing the cubit here
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: MultiBlocListener(
          listeners: [
            BlocListener<UserCubit, UserState>(
              listener: (context, state) {
                if (state is UserExists) {
                  appUser = state.user;
                  mailAddressController!.text = appUser!.email; // Loading the fields
                  fullNameController!.text = appUser!.fullName; // Loading the fields
                }
              },
            )
          ],
          child: BlocBuilder<UserCubit, UserState>(
              builder: (context, state) {
            if (state is UserLoadingState) {
              return const Center(child: CircularProgressIndicator());
            }
            return Container(
                  TextFormField() // For fullName
                  TextFormField() // For EmailAddress
            )
       )
    );
}

Why does this functionality work only the first time not the consecutive times. Thougth the UserCubit is intialized in initstate ?

Any further suggestions to improve this logic by not initializing the UserCubit on every page render would be also appreciated !!


问:
Is there any way to combine/compound multiple shaders for a single object?
I'm using a vertex shader to help me calculate lighting, and I'm using it to render every object in my scene. If I wanted to make a specific vertex shader for grass movement while still keeping the lighting, how would I do that? Can I somehow render it using both the lighting shader and grass shader? Or can i create some type of compound "grass and lighting" shader? Or do I just have to copy all the lighting logic into my grass shader?</p>


问:
What's my mistake when I am trying to work with files in C?
I am a beginner in programming and I need to find out palindromes in the first file and put them into the second one.
I have a Thread 1: EXC_BAD_ACCESS (code=1, address=0x68), when I am trying to start the code

```<code>#include <stdio.h>
#include <string.h>
 int main ()
 {
     char line[255];
     unsigned long k;
     int i;
     int flag = 1;
     FILE *file = fopen("1zad.txt", "r");
     FILE *new = fopen("new1.txt", "a");
     while(!feof(file) && !ferror(file))
     {
         fgets(line, 255, file);
         k = strlen(line);
         for (i = 0;i < k/2;i++)
         {
             if(line[i]!=line[k-1-i]){
                 flag = 0;
             }
         }
         if(flag == 1){
             fputs(line, new);
         }
     }
     fclose(file);
     fclose(new);
     return 0;
 }

</code>```

it underlines "!feof", text files are available and near the program file.
i have no ideas what is going wrong

Body:
I am a beginner in programming and I need to find out palindromes in the first file and put them into the second one.
I have a Thread 1: EXC_BAD_ACCESS (code=1, address=0x68), when I am trying to start the code

#include <stdio.h>
#include <string.h>
 int main ()
 {
     char line[255];
     unsigned long k;
     int i;
     int flag = 1;
     FILE *file = fopen("1zad.txt", "r");
     FILE *new = fopen("new1.txt", "a");
     while(!feof(file) && !ferror(file))
     {
         fgets(line, 255, file);
         k = strlen(line);
         for (i = 0;i < k/2;i++)
         {
             if(line[i]!=line[k-1-i]){
                 flag = 0;
             }
         }
         if(flag == 1){
             fputs(line, new);
         }
     }
     fclose(file);
     fclose(new);
     return 0;
 }

it underlines "!feof", text files are available and near the program file.
i have no ideas what is going wrong


问:
How do I center-align my menu screen relative to the terminal? This would be after generating the menu with a loop
I need to center-align everything relative to the terminal size that is generated in my title_screen() function. How exactly do I go about doing this, because I am lost.

```<code>from pytube import YouTube
import os
import time

# ################################################################
# #                          Variables                           #
# ################################################################
"""Version"""
version_         = "v0.4.87"

"""Software Information"""
author          = "By scrappedpixel42"
#code_one_desc   = "Invalid YouTube URL!"
#code_zero_desc  = "Invalid directory!"
description     = ["This is an easy and free to use ",
                   "YouTube downloader program. Copy",
                   "and paste a YouTube URL, find a ",
                   "valid directory, and download   ",
                   "the video in seconds.           "]
#err_code_one    = "1"
#err_code_zero   = "0"
software_title  = "YouTube Downloader PY"

"""Placeholders and Numbers"""
asset           = "#"
#chunk           = 1024
column          = 56
rows            = 14

# ################################################################
# #                          Functions                           #
# ################################################################
"""Tools"""
def custom_center(text):
    t = text.center(column - 2)
    print((asset + t + asset).center(os.get_terminal_size().columns))

def triple_return():
    print("\n\n\n")

def version(ver):
    v = column - (len(ver) + 3)
    print(asset, end="")
    for element in range(v):
        print(" ", end="")
    print(version_ + " " + asset, end="")

def title_screen():
    u = 0
    triple_return()
    for i in range(1, rows + 1):
        print(end="")
        for e in range(1, column + 1):
            if(i == 1 or i == rows or
               e == 1 or e == column):
                if(i == 2):
                    version(version_)
                    break
                if(i == 4):
                    custom_center(software_title)
                    break
                if(i == 6):
                    custom_center(author)
                    break
                if(i >= 9 and i <= 12):
                    custom_center(description[u])
                    u += 1
                    break
                print(asset, end="")
            else:
                print(" ", end="")
        print()
    triple_return()

# ################################################################
# #                             Main                             #
# ################################################################
title_screen()

input()
</code>```

Output:

enter image description here

I have been attempting to center-align my menu for many hours now and have gotten no-where. This is one of my attempts with .center(os.get_terminal_center().columns), on line 50.

Body:
I need to center-align everything relative to the terminal size that is generated in my title_screen() function. How exactly do I go about doing this, because I am lost.

from pytube import YouTube
import os
import time

# ################################################################
# #                          Variables                           #
# ################################################################
"""Version"""
version_         = "v0.4.87"

"""Software Information"""
author          = "By scrappedpixel42"
#code_one_desc   = "Invalid YouTube URL!"
#code_zero_desc  = "Invalid directory!"
description     = ["This is an easy and free to use ",
                   "YouTube downloader program. Copy",
                   "and paste a YouTube URL, find a ",
                   "valid directory, and download   ",
                   "the video in seconds.           "]
#err_code_one    = "1"
#err_code_zero   = "0"
software_title  = "YouTube Downloader PY"

"""Placeholders and Numbers"""
asset           = "#"
#chunk           = 1024
column          = 56
rows            = 14

# ################################################################
# #                          Functions                           #
# ################################################################
"""Tools"""
def custom_center(text):
    t = text.center(column - 2)
    print((asset + t + asset).center(os.get_terminal_size().columns))

def triple_return():
    print("\n\n\n")

def version(ver):
    v = column - (len(ver) + 3)
    print(asset, end="")
    for element in range(v):
        print(" ", end="")
    print(version_ + " " + asset, end="")

def title_screen():
    u = 0
    triple_return()
    for i in range(1, rows + 1):
        print(end="")
        for e in range(1, column + 1):
            if(i == 1 or i == rows or
               e == 1 or e == column):
                if(i == 2):
                    version(version_)
                    break
                if(i == 4):
                    custom_center(software_title)
                    break
                if(i == 6):
                    custom_center(author)
                    break
                if(i >= 9 and i <= 12):
                    custom_center(description[u])
                    u += 1
                    break
                print(asset, end="")
            else:
                print(" ", end="")
        print()
    triple_return()

# ################################################################
# #                             Main                             #
# ################################################################
title_screen()

input()

Output:

enter image description here

I have been attempting to center-align my menu for many hours now and have gotten no-where. This is one of my attempts with .center(os.get_terminal_center().columns), on line 50.


问:
Rust Matrix Type with Specialized and Generic Functions
Given a matrix type in Rust using const generic parameters, something like this:

```<code>pub struct Mat<T, const R: usize, const C: usize>
{
    m: [[T; C]; R],
}
</code>```

I am aware that specializations are not available (yet, and not for this type of
specialization it seems?), but it seems like it is possible to implement some
'specializations' for specific instances of this type, e.g.:

```<code>impl<T> Mat<T, 2, 2>
{
    pub fn invert(self) -> Self
    where T: From<f32> + Clone + std::ops::Neg<Output=T> + std::ops::Sub<T, Output = T> +
          std::ops::Mul<T, Output = T> + std::ops::Div<T, Output = T>
    {
        let r = T::from(1.0) / self.clone().determinant();
        Mat::new([[ self[1][1]*r.clone(), -self[0][1]*r.clone()],
                  [-self[1][0]*r.clone(),  self[0][0]*r]])
    }

    pub fn determinant(self) -> T
    where T: std::ops::Sub<T, Output = T> + std::ops::Mul<T, Output = T>
    {
        self[0][0]*self[1][1] - self[0][1]*self[1][0]
    }
}
</code>```

Similar 'specializations' can be implemented for 3x3 and 4x4 matrices.

However, at some point I would like to also implement a generalized
determinant/inverse, something like this:

```<code>impl<T, const N: usize> Mat<T, N, N>
{
    /// Generalized matrix inversion.
    pub fn gen_invert(self) -> Self
    {
        // TODO: determinant(), matrix_minor(), cofactor(), adjugate()
        Mat::default()
    }

    /// Generalized matrix determinant.
    pub fn gen_det(self) -> T
    {
        match N
        {
            1 => self.determinant(), // <- Wrong type Mat<T, N, N>, not Mat<T, 1, 1>.
            // 2 => // Same as above.
            _ => general_fn(),
        }
    }
}
</code>```

This turned out to be hard however, since there does not seem to be any way to
cast or even transmute a type of Mat<T, N, N> to Mat<T, 1, 1>, even though we
know that the sizes are correct, given that is done on a const variable under
an appropriate match case. Is there some way to accomplish the above without an
expensive from() function that manually creates a Mat<T, 1, 1> from the Mat<T,
N, N>?

Additionally, is there some way to avoid renaming the generalized versions of
these functions? I tried to do that using traits, similar to this question, but
since all functions have the same name this does not appear to work for this
case.

(There are even more complications with this though, since computing minor
matrices requires arithmetic on const generics and that is only in nightly Rust
right now, but that is beyond the scope of this question.)

Body:
Given a matrix type in Rust using const generic parameters, something like this:

pub struct Mat<T, const R: usize, const C: usize>
{
    m: [[T; C]; R],
}

I am aware that specializations are not available (yet, and not for this type of
specialization it seems?), but it seems like it is possible to implement some
'specializations' for specific instances of this type, e.g.:

impl<T> Mat<T, 2, 2>
{
    pub fn invert(self) -> Self
    where T: From<f32> + Clone + std::ops::Neg<Output=T> + std::ops::Sub<T, Output = T> +
          std::ops::Mul<T, Output = T> + std::ops::Div<T, Output = T>
    {
        let r = T::from(1.0) / self.clone().determinant();
        Mat::new([[ self[1][1]*r.clone(), -self[0][1]*r.clone()],
                  [-self[1][0]*r.clone(),  self[0][0]*r]])
    }

    pub fn determinant(self) -> T
    where T: std::ops::Sub<T, Output = T> + std::ops::Mul<T, Output = T>
    {
        self[0][0]*self[1][1] - self[0][1]*self[1][0]
    }
}

Similar 'specializations' can be implemented for 3x3 and 4x4 matrices.

However, at some point I would like to also implement a generalized
determinant/inverse, something like this:

impl<T, const N: usize> Mat<T, N, N>
{
    /// Generalized matrix inversion.
    pub fn gen_invert(self) -> Self
    {
        // TODO: determinant(), matrix_minor(), cofactor(), adjugate()
        Mat::default()
    }

    /// Generalized matrix determinant.
    pub fn gen_det(self) -> T
    {
        match N
        {
            1 => self.determinant(), // <- Wrong type Mat<T, N, N>, not Mat<T, 1, 1>.
            // 2 => // Same as above.
            _ => general_fn(),
        }
    }
}

This turned out to be hard however, since there does not seem to be any way to
cast or even transmute a type of Mat<T, N, N> to Mat<T, 1, 1>, even though we
know that the sizes are correct, given that is done on a const variable under
an appropriate match case. Is there some way to accomplish the above without an
expensive from() function that manually creates a Mat<T, 1, 1> from the Mat<T,
N, N>?

Additionally, is there some way to avoid renaming the generalized versions of
these functions? I tried to do that using traits, similar to this question, but
since all functions have the same name this does not appear to work for this
case.

(There are even more complications with this though, since computing minor
matrices requires arithmetic on const generics and that is only in nightly Rust
right now, but that is beyond the scope of this question.)


问:
How to build the Json Structure and Rest API for a State Machine Service
I would like to build a Rest Api for a "Statemachine".

The statemachine is modeled like this:

```<code>@Entity
public class StateMachine {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn
    private State startState;

    @OneToMany(cascade = CascadeType.ALL)
    private Set<State> states = new HashSet<>();

    @OneToMany
    private Set<StateTransition> stateTransitions = new HashSet<>();
...
</code>```

The state is modeled like this:

```<code>@Entity
public class State {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;

    private String description;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn
    private StateMachine statemachine;

</code>```

Finally the State Transition Entity is this:

```<code>@Entity
public class StateTransition {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToOne
    private StateMachine statemachine;

    @ManyToOne()
    private State fromState;

    @ManyToOne()
    private State toState;

    }

</code>```

My goal is to have one post service in a Statemachine Controller and the Json in the Request Body may contain the full structure of the Statemachine.

I think this is better then first creating a more or less empty state machine, then posting some states to him, set the start state and finally add some statetransitions.
These would be many http calls over the wire.

But how have the Json look like ?
Must it contain Ids to build up the references ?
I do struggle with this, because the Ids should be generated by the Model automatically.

I think this is a common question and that there do exist a pattern for this.

Without using Ids, I do get the StartState be generated twice.

```<code>{
    "startState": {
                "name": "StartState",
                "description": "This is the StartState"
                }
    ,
    "states": [
                {
                "name": "StartState",
                "description": "This is the StartState"
                },

                {
                "name": "EndState",
                "description": "This is the EndState"
                }

    ]
}
</code>```

Body:
I would like to build a Rest Api for a "Statemachine".

The statemachine is modeled like this:

@Entity
public class StateMachine {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn
    private State startState;

    @OneToMany(cascade = CascadeType.ALL)
    private Set<State> states = new HashSet<>();

    @OneToMany
    private Set<StateTransition> stateTransitions = new HashSet<>();
...

The state is modeled like this:

@Entity
public class State {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;

    private String description;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn
    private StateMachine statemachine;

Finally the State Transition Entity is this:

@Entity
public class StateTransition {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToOne
    private StateMachine statemachine;

    @ManyToOne()
    private State fromState;

    @ManyToOne()
    private State toState;

    }

My goal is to have one post service in a Statemachine Controller and the Json in the Request Body may contain the full structure of the Statemachine.

I think this is better then first creating a more or less empty state machine, then posting some states to him, set the start state and finally add some statetransitions.
These would be many http calls over the wire.

But how have the Json look like ?
Must it contain Ids to build up the references ?
I do struggle with this, because the Ids should be generated by the Model automatically.

I think this is a common question and that there do exist a pattern for this.

Without using Ids, I do get the StartState be generated twice.

{
    "startState": {
                "name": "StartState",
                "description": "This is the StartState"
                }
    ,
    "states": [
                {
                "name": "StartState",
                "description": "This is the StartState"
                },

                {
                "name": "EndState",
                "description": "This is the EndState"
                }

    ]
}


问:
How to count grapheme clusters with Firestore security rules
I'm encountering this issue when developing forms using Flutter and Firestore.

When setting character limits for form fields, Flutter counts everything (including emojis) as a single character. This creates a wonderful user experience because users intuitively expect an emoji to count as a single character. However, this becomes a problem when using Firestore security rules to validate the length of the submitted form field.

To give an example, let's say you create a form field titled "Comments" with a character limit of 1,000. When the user submits the form, you store Comments as a String in a Firestore document. Just before that, your security rules would check the incoming String to ensure the size of it is <= 1000. The issue, however, is that the front-end (Flutter) counts characters using "grapheme clusters" (string.characters.length) when limiting the input by the user, but the back-end (security rules) counts characters using string.length—which counts emojis as more than 1 character. As a result, 1,000 characters counted by Flutter might be something like 1,001 characters when counted by security rules (using string.length) if a single emoji was used.

Because of this difference in calculating the size of a string, I'm finding it difficult to reasonably validate the length of Comments and ensure that a user hasn't maliciously discovered a way to inject additional characters into Comments and submit very large strings.

Is there a way to deal with this discrepancy using Firestore security rules, or will I need to modify Flutter to count actual characters instead of grapheme clusters?

See also:

Handling emojis and other complex characters

How Flutter counts "characters"

How to calculate String size in security rules

The only reasonable solution that I've managed to come up with is to provide a custom implementation of LengthLimitingTextInputFormatter to the inputFormatters parameter of the TextFormField constructor and override the function that counts characters to count characters by string.length, as opposed to string.characters.length. This would make the Comments form field count characters just like security rules does. This solution isn't exactly ideal though since it's not intuitive for the user.

See also:

TextFormField constructor


问:
How to avoid an Invalid Argument exception when calling SetControlText in a CFileDialog
I inherited some code that is clearly based on this discussion:

cfiledialog and file extension

The code reads:

```<code>#define FILE_DIALOG_NAME cmb13

// CStarMaskDlg dialog
/* ------------------------------------------------------------------- */

class CSaveMaskDlg : public CFileDialog
{
    DECLARE_DYNAMIC(CSaveMaskDlg)

    //
    // 9 December 2022 David C. Partridge
    //
    // I added OFN_EXPLORER to the open flags as per the note in the docs for CFileDialog::SetControlText
    // that say:
    //    To use this method, you must create the dialog box with the OFN_EXPLORER style.
    //    Otherwise, the function will fail with an assertion.
    //
public :
    CSaveMaskDlg(bool bOpenFileDialog, // true for FileOpen, false for FileSaveAs
        LPCTSTR lpszDefExt = nullptr,
        LPCTSTR lpszFileName = nullptr,
        DWORD dwFlags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_EXPLORER, // Add OFN_EXPLORER - see CFileDialog
        LPCTSTR lpszFilter = nullptr,
        CWnd* pParentWnd = nullptr):CFileDialog(bOpenFileDialog, lpszDefExt, lpszFileName, dwFlags, lpszFilter, pParentWnd)
    {
    };
    virtual ~CSaveMaskDlg()
    {
    };

protected:
    virtual void OnTypeChange()
    {
        CFileDialog::OnTypeChange();
        CString         strFileName = GetFileTitle();

        if (strFileName.GetLength())
        {
            if (m_ofn.nFilterIndex == 1)
                strFileName += ".tif";
            else
                strFileName += ".fits";
            SetControlText(FILE_DIALOG_NAME, strFileName);
        };
    };
};
IMPLEMENT_DYNAMIC(CSaveMaskDlg, CFileDialog)

/* ------------------------------------------------------------------- */

IMPLEMENT_DYNAMIC(CStarMaskDlg, CDialog)
</code>```

The problem is that whenever SetControlText is invoked (at least on W10 and W11), an InvalidArgument exception is thrown.

As you can see I tried to fix the problem but so far it is beating me.

If this code is wrong, then please put me out of my misery and show me how it should go.

Thanks a lot
David

Body:
I inherited some code that is clearly based on this discussion:

cfiledialog and file extension

The code reads:

#define FILE_DIALOG_NAME cmb13

// CStarMaskDlg dialog
/* ------------------------------------------------------------------- */

class CSaveMaskDlg : public CFileDialog
{
    DECLARE_DYNAMIC(CSaveMaskDlg)

    //
    // 9 December 2022 David C. Partridge
    //
    // I added OFN_EXPLORER to the open flags as per the note in the docs for CFileDialog::SetControlText
    // that say:
    //    To use this method, you must create the dialog box with the OFN_EXPLORER style.
    //    Otherwise, the function will fail with an assertion.
    //
public :
    CSaveMaskDlg(bool bOpenFileDialog, // true for FileOpen, false for FileSaveAs
        LPCTSTR lpszDefExt = nullptr,
        LPCTSTR lpszFileName = nullptr,
        DWORD dwFlags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_EXPLORER, // Add OFN_EXPLORER - see CFileDialog
        LPCTSTR lpszFilter = nullptr,
        CWnd* pParentWnd = nullptr):CFileDialog(bOpenFileDialog, lpszDefExt, lpszFileName, dwFlags, lpszFilter, pParentWnd)
    {
    };
    virtual ~CSaveMaskDlg()
    {
    };

protected:
    virtual void OnTypeChange()
    {
        CFileDialog::OnTypeChange();
        CString         strFileName = GetFileTitle();

        if (strFileName.GetLength())
        {
            if (m_ofn.nFilterIndex == 1)
                strFileName += ".tif";
            else
                strFileName += ".fits";
            SetControlText(FILE_DIALOG_NAME, strFileName);
        };
    };
};
IMPLEMENT_DYNAMIC(CSaveMaskDlg, CFileDialog)

/* ------------------------------------------------------------------- */

IMPLEMENT_DYNAMIC(CStarMaskDlg, CDialog)

The problem is that whenever SetControlText is invoked (at least on W10 and W11), an InvalidArgument exception is thrown.

As you can see I tried to fix the problem but so far it is beating me.

If this code is wrong, then please put me out of my misery and show me how it should go.

Thanks a lot
David


问:
audio player return DOMException: The element has no supported sources
I am working with audio player
The response of get song, blob object, and url return by URL.createObjectURL like this.
enter image description here

The headers of blob link show enter image description here

And "DOMException: The element has no supported sources" appeared
.Please help me

I coded like this

```<code>            const blob = new Blob([response.data],{type: 'audio/mpeg'})
            const url = URL.createObjectURL(blob)

            audio.current.src = url

</code>```

Body:
I am working with audio player
The response of get song, blob object, and url return by URL.createObjectURL like this.
enter image description here

The headers of blob link show enter image description here

And "DOMException: The element has no supported sources" appeared
.Please help me

I coded like this

            const blob = new Blob([response.data],{type: 'audio/mpeg'})
            const url = URL.createObjectURL(blob)

            audio.current.src = url


问:
Flutter/Dart: how to hint text on entered keyword
Let's say I have a list of strings:
[ apple, ananas, banana]

I want to make a text input that for example when I write a the input field would automatically show the word ananas with nanas being less visible, so that the user can see it is a hint. Continuing the example, if the next word in the input would be ap then it would hint towards apple, and if ENTER is pressed the word apple should be the actual value of the text field.


问:
EntityManagerFactory error after implementing Spring-JDBC?
So I wanted to use Spring-JDBC for using more procedures pointing to complex views, but still having JPA for Entity handling. After checking out JDBC a little and tried to implement it, I had some problem.. and I felt I wanted to go back to JPA and tackle this later.

But now.. when I try to "rollback" I'll recieve this error:

```<code>***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 1 of constructor in com.expenses.expenses.Controllers.CreditGroupController required a bean named 'entityManagerFactory' that could not be found.

Action:

Consider defining a bean named 'entityManagerFactory' in your configuration.
</code>```

What I've been trying:

Rolling back the pom-file

Run maven clean install

Delete the target-map manually

Running invalidate caches

Delete the whole repository map in .m2 and run maven clean install again

Trying to exclude some classes in autoconfiguration (Not really sure which one that should be the correct one to exclude if so)

Enabled debug to see if I can see something suspicious, debug in spring is pretty new for me though, so I'm not so sure to know what I should look for.

It feels like the application doesn't look for the datasource configuration in application.properties anymore.

These are my dependecies that worked before i tried Spring-JDBC:

```<code>        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springdoc</groupId>
            <artifactId>springdoc-openapi-ui</artifactId>
            <version>1.6.9</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
            <version>3.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.univocity</groupId>
            <artifactId>univocity-parsers</artifactId>
            <version>2.9.0</version>
        </dependency>
        <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.19.2</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-impl</artifactId>
            <version>0.11.2</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-api</artifactId>
            <version>0.11.2</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-jackson</artifactId>
            <version>0.11.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-oauth2-client</artifactId>
        </dependency>
</code>```

This was the dependecy I used for Spring-JDBC

```<code><!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.3.24</version>
</dependency>

</code>```

My main method:

```<code>@SpringBootApplication
public class ExpensesApplication {

    public static void main(String[] args) {
        SpringApplication.run(ExpensesApplication.class, args);
    }

}
</code>```

Feels just like a dumb misstake.. but I need some fresh eyes with a bit more experience which probably can explain to me why this occurs..

Thank you in advance!

Body:
So I wanted to use Spring-JDBC for using more procedures pointing to complex views, but still having JPA for Entity handling. After checking out JDBC a little and tried to implement it, I had some problem.. and I felt I wanted to go back to JPA and tackle this later.

But now.. when I try to "rollback" I'll recieve this error:

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 1 of constructor in com.expenses.expenses.Controllers.CreditGroupController required a bean named 'entityManagerFactory' that could not be found.

Action:

Consider defining a bean named 'entityManagerFactory' in your configuration.

What I've been trying:

Rolling back the pom-file

Run maven clean install

Delete the target-map manually

Running invalidate caches

Delete the whole repository map in .m2 and run maven clean install again

Trying to exclude some classes in autoconfiguration (Not really sure which one that should be the correct one to exclude if so)

Enabled debug to see if I can see something suspicious, debug in spring is pretty new for me though, so I'm not so sure to know what I should look for.

It feels like the application doesn't look for the datasource configuration in application.properties anymore.

These are my dependecies that worked before i tried Spring-JDBC:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springdoc</groupId>
            <artifactId>springdoc-openapi-ui</artifactId>
            <version>1.6.9</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
            <version>3.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.univocity</groupId>
            <artifactId>univocity-parsers</artifactId>
            <version>2.9.0</version>
        </dependency>
        <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.19.2</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-impl</artifactId>
            <version>0.11.2</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-api</artifactId>
            <version>0.11.2</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-jackson</artifactId>
            <version>0.11.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-oauth2-client</artifactId>
        </dependency>

This was the dependecy I used for Spring-JDBC

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.3.24</version>
</dependency>

My main method:

@SpringBootApplication
public class ExpensesApplication {

    public static void main(String[] args) {
        SpringApplication.run(ExpensesApplication.class, args);
    }

}

Feels just like a dumb misstake.. but I need some fresh eyes with a bit more experience which probably can explain to me why this occurs..

Thank you in advance!


问:
Missing index.html issue is shown in the terminal in flutter while trying to upload a network image
I wanted to upload a network image on my android emulator. But the image was not displaying giving an unreadable error (no adress assosiated with hostname). when i tried to run the flutter renderer html command in terminal then Missing index.html error was shown on my terminal. which i am unable to figure out

tried different commands in terminal but of no result so want a solution for the said problem


问:
parse(value) throwing error when I have Image
I'm having a text editor that stores edited value in a state called "value" like shown below.

I show preview of content added. The preview of the text looks like this when you do console.log

```<code><p>This is the value intially</p>
</code>```

So I'm using parse(value) to render content correctly.

```<code>import parse from 'html-react-parser';

 const [value, setValue] = useState('This is the value intially');

const getValue =()=>{
   return parse(value).props.children
}

    </div>

                    <Highlighter
    highlightClassName="YourHighlightClass"
    searchWords={["and", "or", "the"]}
    autoEscape={true}
    textToHighlight={getValue}

                    </div>

</code>```

But when I add an image and click on preview, it crashes. Could someone help me?

Body:
I'm having a text editor that stores edited value in a state called "value" like shown below.

I show preview of content added. The preview of the text looks like this when you do console.log

This is the value intially

So I'm using parse(value) to render content correctly.

import parse from 'html-react-parser';

 const [value, setValue] = useState('This is the value intially');

const getValue =()=>{
   return parse(value).props.children
}

                    <Highlighter
    highlightClassName="YourHighlightClass"
    searchWords={["and", "or", "the"]}
    autoEscape={true}
    textToHighlight={getValue}

But when I add an image and click on preview, it crashes. Could someone help me?


问:
How can I put a twilio call on hold without conference?
We are developing a calling web app using React and Node. In this app, we are providing incoming and outgoing calls. But I am having trouble holding the hold. Please provide some references or code.

I want to put the call on hold without conference and then play music on the other end.


问:
termios, getchar() always returns -1 with error EAGAIN
I have a piece of code in which I want to read a character from the terminal. The goal is to give keyboard input for moving a robot.

If there is no input in the terminal , the code should return -1, which it does, but even when I do give inputs, it always returns -1 with errno set to EAGAIN. According to the documentation, it means: no data available. Does anyone has an idea why is that happening?

Here is the code, reduced to a minimal version:

#include <termios.h>
#include <cstdio>

int getch()
{
    int ch;
    struct termios oldt;
    struct termios newt;

    // Store old settings, and copy to new settings
    tcgetattr(0, &oldt);
    newt = oldt;

    // Make required changes and apply the settings
    newt.c_lflag &= ~(ICANON | ECHO);
    newt.c_iflag |= IGNBRK;
    newt.c_iflag &= ~(INLCR | ICRNL | IXON | IXOFF);
    newt.c_lflag &= ~(ICANON | ECHO | ECHOK | ECHOE | ECHONL | ISIG | IEXTEN);
    newt.c_cc[VMIN] = 0;
    newt.c_cc[VTIME] = 1;
    tcsetattr(fileno(stdin), TCSANOW, &newt);

    // Get the current character
    ch = getchar();

    // Reapply old settings
    tcsetattr(0, TCSANOW, &oldt);

    return ch;
}

int main(int argc, char **argv)
{

    long count = 0;

    while (true)
    {

        int ch = 0;

        ch = getch();

        printf("%ld\n", count++);
        printf("char = %d\n\n", ch);

        switch (ch)
        {
        case 'q':
            printf("already quit!\n");
            return 0;

        case 'w':
            printf("move forward!\n");
            break;

        case 's':
            printf("move backward!\n");
            break;

        case 'a':
            printf("move left!\n");
            break;

        case 'd':
            printf("move right!\n");
            break;

        case 'j':
            printf("turn left!\n");
            break;

        case 'l':
            printf("turn right!\n");
            break;

        default:
            printf("Stop!\n");
            break;
        }

    }

    return 0;
}
```

I precise that the code works when I change VMIN and VTIME: it can read the inputs from the terminal, but the problem is that then it blocks and if I do not give any input, it doesn't exit, while the expected result is that it outputs -1.
I'm on Ubuntu 20.04, using gnome-terminal.
Thanks for any help!

What I did, what I expected to happen, what actually happens:
I tried to run my code and expected that when I hit a key of my keyboard, it returns the key I pressed, but instead, it always returns -1.

Body:
I have a piece of code in which I want to read a character from the terminal. The goal is to give keyboard input for moving a robot.

If there is no input in the terminal , the code should return -1, which it does, but even when I do give inputs, it always returns -1 with errno set to EAGAIN. According to the documentation, it means: no data available. Does anyone has an idea why is that happening?

Here is the code, reduced to a minimal version:

#include <termios.h>
#include <cstdio>

int getch()
{
    int ch;
    struct termios oldt;
    struct termios newt;

    // Store old settings, and copy to new settings
    tcgetattr(0, &oldt);
    newt = oldt;

    // Make required changes and apply the settings
    newt.c_lflag &= ~(ICANON | ECHO);
    newt.c_iflag |= IGNBRK;
    newt.c_iflag &= ~(INLCR | ICRNL | IXON | IXOFF);
    newt.c_lflag &= ~(ICANON | ECHO | ECHOK | ECHOE | ECHONL | ISIG | IEXTEN);
    newt.c_cc[VMIN] = 0;
    newt.c_cc[VTIME] = 1;
    tcsetattr(fileno(stdin), TCSANOW, &newt);

    // Get the current character
    ch = getchar();

    // Reapply old settings
    tcsetattr(0, TCSANOW, &oldt);

    return ch;
}

int main(int argc, char **argv)
{

    long count = 0;

    while (true)
    {

        int ch = 0;

        ch = getch();

        printf("%ld\n", count++);
        printf("char = %d\n\n", ch);

        switch (ch)
        {
        case 'q':
            printf("already quit!\n");
            return 0;

        case 'w':
            printf("move forward!\n");
            break;

        case 's':
            printf("move backward!\n");
            break;

        case 'a':
            printf("move left!\n");
            break;

        case 'd':
            printf("move right!\n");
            break;

        case 'j':
            printf("turn left!\n");
            break;

        case 'l':
            printf("turn right!\n");
            break;

        default:
            printf("Stop!\n");
            break;
        }

    }

    return 0;
}

I precise that the code works when I change VMIN and VTIME: it can read the inputs from the terminal, but the problem is that then it blocks and if I do not give any input, it doesn't exit, while the expected result is that it outputs -1.
I'm on Ubuntu 20.04, using gnome-terminal.
Thanks for any help!

What I did, what I expected to happen, what actually happens:
I tried to run my code and expected that when I hit a key of my keyboard, it returns the key I pressed, but instead, it always returns -1.


问:
Connecting Java in the Database MySQL
I am creating a small project where there will be a Admin pre-registered through java back-end and a Regular one in which that once registered his/her details would be saved to the database.
Will also have some privileges on what can or can't do on the system. Basically, the Regular user would operate some math question and the Admin would have access to all of what his done.

Well, I have been doing this for 3 weeks and so far I couldn't even connect to the database. I tried to create a static variable where the connection would be global for the whole project. My code is a mess and I don't even understand what I am doing anymore. Could anyone please help me. I am desperate...What am I doing wrong here. All I want is to connect to the database and register a new user.

```<code>public class calculator {
public static void main(String[] args) {

       int userChoice=0;

        BufferedReader kb = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Hi there...");
        System.out.println("What would like to do?" + "\n");
    do{
        System.out.println("Enter 1 to login: ");
        System.out.println("Enter 2 to sign-up: ");
    try{
       userChoice=Integer.parseInt(kb.readLine());// converting int to string
    }catch(Exception e ){
        System.out.println("Please Only Numbers Allowed.." + "\n");
        System.out.println("If already user Please choose 1 to login.");
        System.out.println("If not user yet. Please choose 2 to sign-up" + "\n");
    }
}       while((userChoice!=1 && userChoice!=2));

        // switch case for user option

        switch(userChoice){
        case 1: //STEP 2: show login options (display option 1 =>login

            break;
        case 2:
            DBconnection Register = new DBconnection();
            Register.Register();

            break;
        default:
    }

}

//static method to create a static variable in order to make it global

private static String DBsetUp() {

    //try-catch for driver instance
    try{Class.forName(driver).newInstance();
    }catch(Exception e){System.out.println("Connection Failed. Please check your Driver method.");
        e.printStackTrace();
    }

    try{ Connection conn = DriverManager.getConnection(DATABASE_URL,USERNAME,PASSWORD);
         Statement stmt = conn.createStatement();

     // INSERTING data into database
     stmt.execute("USE " + DB_NAME + ";" );
     stmt.executeUpdate(

             // FIND A EASIER WAY OF INSERT DATA USING JAVA
             String.format("INSERT INTO " + TB_NAME+"(user_name,user_passWord)"

                //FIX THIS LINE...
                 + "VALUES (\"%s\",\"%s\") ;"
                 // using the 'User' arguments to get the variable attribute
             // in the class 'Users' and set values to be called in the main...
                     ));

     //  DISPLAYING ALL DATA CREATED FOR TESTING PORPUSES...

     ResultSet results=stmt.executeQuery("SELECT * FROM " + DB_NAME + "." + TB_NAME +";");
     while(results.next())
        System.out.println("Username: "+results.getString(1)+", ID " + "     "+results.getString(2)+", Pass "+" "+results.getString(3));
        conn.close();

    // System.out.println(rs);

        return null;
    }catch(SQLException e){("check the following ERROR!!!");
        e.printStackTrace(); // Will show the exact line in which the method raised the exception
    }return null ;
 }

}

// Admin User Pre-registered Credentials as per Assignment Requirmeents...

    public class DBconnection {

    static final String DB_NAME="integratedca";
    static final String DATABASE_URL="jdbc:mysql://localhost/" + DB_NAME;
    static final String USERNAME="CCT"; static final String PASSWORD="Dublin";
    static final String driver="com.mysql.cj.jdbc.Driver";
    static final String TB_NAME="user";

    public DBconnection(){  // Default constructor

        try{
            Class.forName(driver).newInstance();
            Connection conn = DriverManager.getConnection(DATABASE_URL,USERNAME,PASSWORD);
            Statement stmt = conn.createStatement();
            stmt.execute("USE " + DB_NAME + ";" );
        }catch(Exception e){
            System.out.println("h.");
            e.printStackTrace();
        }
    };

    /**
    * @return false if not authentication user is correct
    * @return true if user athentication is successful
    */
     public boolean Login(){

        BufferedReader myKeyboard =new BufferedReader(new InputStreamReader(System.in));

     //  while(USERNAME.equals(userName) && (PASSWORD.equals(password))){

     String userName = "", password = "";
     do{
     try{
        System.out.print(" Enter user name => ");
        userName=myKeyboard.readLine();

        System.out.print(" Enter password => ");
        password = myKeyboard.readLine();

     }catch(Exception e){
        System.out.println("PUT SOMETHING USEFUL HERE..."); // DONT FORGET
    }

        if (USERNAME.equals(userName) && PASSWORD.equals(password)) {
            System.out.println(" User successfully logged-in.. ");
            if(true){
                System.out.println("Say now. WHO IS THE BOSS.. HAHA");
            /*
                do stuff do tother stuff
                call the methods and things*/
            }

        } else {
            System.out.println("Invalid userName of password");
            System.out.println("Please try again.");
            System.out.println("If not user yet, sigh-up...");
             DBconnection Register = new DBconnection();
             Register.Register();
        }
    }while(!USERNAME.equals(userName) && (!PASSWORD.equals(password)));
       //}

    return false;
    }

     public String Register(){

          User Register = new User (""); // instantiating User class

          BufferedReader kb =new BufferedReader (new InputStreamReader(System.in));
          String userFName="",userLName="", userName="",password="";

          try{
          System.out.print("Enter your First Name: ");
          userFName=kb.readLine();
          Register.setUserFirstName(userFName);

             // Setting Last Name
          System.out.print("Enter your Last Name: ");
          userLName=kb.readLine();
          Register.setUserFirstName(userLName);

             // Setting Username
          System.out.print("Enter your Username: ");
          userName=kb.readLine();
          Register.setUserFirstName(userName);

            // Setting password
          System.out.print("Enter your password: ");
          password=kb.readLine();
          Register.setUserFirstName(password);
          }catch(Exception e){
            System.out.println("something went wrong...");

     }
       return null;
     }}

</code>```
```<code>
    public class User {

    private String firstName;   // attributes
    private String lastName;
    private String password;
    private int id;

    /**
     * Default blank Constructor constructor for login purposes as User input will be iMplemented
     */
    public User(String userRecord){  // Default constructor

       this.firstName = userRecord;// change the fields user table removing (user_name => name) and so on.
       this.lastName = userRecord;
       this.password = userRecord;

        //...
     //  this.showMenu()// create menu user that shows the options as per requirements in the Project
        // each menu option, creates a method (update name); replace new userName; updatae user record for userName; return true =updated;
      //STEP 4:

    };

    //STEP 5:
    //PUBLIC SHOW MENU
    public String getUserFirstName() {
        return firstName;
    }

    public void setUserFirstName(String userFName) {
        this.firstName = userFName;
    }

    public String getUserLastName() {
        return lastName;
    }

    public void setUserLastName(String userLName) {
        this.lastName = userLName;
    }

    public String getPassWord() {
        return password;
    }

    public void setPassWord(String pass) {
        this.password = pass;
    }

    public int getId() {    // only get id as it is auto increment
        return id;
    }

}

</code>```

Title: Connecting Java in the Database MySQL

Body:
I am creating a small project where there will be a Admin pre-registered through java back-end and a Regular one in which that once registered his/her details would be saved to the database.
Will also have some privileges on what can or can't do on the system. Basically, the Regular user would operate some math question and the Admin would have access to all of what his done.

Well, I have been doing this for 3 weeks and so far I couldn't even connect to the database. I tried to create a static variable where the connection would be global for the whole project. My code is a mess and I don't even understand what I am doing anymore. Could anyone please help me. I am desperate...What am I doing wrong here. All I want is to connect to the database and register a new user.

public class calculator {
public static void main(String[] args) {

       int userChoice=0;

        BufferedReader kb = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Hi there...");
        System.out.println("What would like to do?" + "\n");
    do{
        System.out.println("Enter 1 to login: ");
        System.out.println("Enter 2 to sign-up: ");
    try{
       userChoice=Integer.parseInt(kb.readLine());// converting int to string
    }catch(Exception e ){
        System.out.println("Please Only Numbers Allowed.." + "\n");
        System.out.println("If already user Please choose 1 to login.");
        System.out.println("If not user yet. Please choose 2 to sign-up" + "\n");
    }
}       while((userChoice!=1 && userChoice!=2));

        // switch case for user option

        switch(userChoice){
        case 1: //STEP 2: show login options (display option 1 =>login

            break;
        case 2:
            DBconnection Register = new DBconnection();
            Register.Register();

            break;
        default:
    }

}

//static method to create a static variable in order to make it global

private static String DBsetUp() {

    //try-catch for driver instance
    try{Class.forName(driver).newInstance();
    }catch(Exception e){System.out.println("Connection Failed. Please check your Driver method.");
        e.printStackTrace();
    }

    try{ Connection conn = DriverManager.getConnection(DATABASE_URL,USERNAME,PASSWORD);
         Statement stmt = conn.createStatement();

     // INSERTING data into database
     stmt.execute("USE " + DB_NAME + ";" );
     stmt.executeUpdate(

             // FIND A EASIER WAY OF INSERT DATA USING JAVA
             String.format("INSERT INTO " + TB_NAME+"(user_name,user_passWord)"

                //FIX THIS LINE...
                 + "VALUES (\"%s\",\"%s\") ;"
                 // using the 'User' arguments to get the variable attribute
             // in the class 'Users' and set values to be called in the main...
                     ));

     //  DISPLAYING ALL DATA CREATED FOR TESTING PORPUSES...

     ResultSet results=stmt.executeQuery("SELECT * FROM " + DB_NAME + "." + TB_NAME +";");
     while(results.next())
        System.out.println("Username: "+results.getString(1)+", ID " + "     "+results.getString(2)+", Pass "+" "+results.getString(3));
        conn.close();

    // System.out.println(rs);

        return null;
    }catch(SQLException e){("check the following ERROR!!!");
        e.printStackTrace(); // Will show the exact line in which the method raised the exception
    }return null ;
 }

}

// Admin User Pre-registered Credentials as per Assignment Requirmeents...

    public class DBconnection {

    static final String DB_NAME="integratedca";
    static final String DATABASE_URL="jdbc:mysql://localhost/" + DB_NAME;
    static final String USERNAME="CCT"; static final String PASSWORD="Dublin";
    static final String driver="com.mysql.cj.jdbc.Driver";
    static final String TB_NAME="user";

    public DBconnection(){  // Default constructor

        try{
            Class.forName(driver).newInstance();
            Connection conn = DriverManager.getConnection(DATABASE_URL,USERNAME,PASSWORD);
            Statement stmt = conn.createStatement();
            stmt.execute("USE " + DB_NAME + ";" );
        }catch(Exception e){
            System.out.println("h.");
            e.printStackTrace();
        }
    };

    /**
    * @return false if not authentication user is correct
    * @return true if user athentication is successful
    */
     public boolean Login(){

        BufferedReader myKeyboard =new BufferedReader(new InputStreamReader(System.in));

     //  while(USERNAME.equals(userName) && (PASSWORD.equals(password))){

     String userName = "", password = "";
     do{
     try{
        System.out.print(" Enter user name => ");
        userName=myKeyboard.readLine();

        System.out.print(" Enter password => ");
        password = myKeyboard.readLine();

     }catch(Exception e){
        System.out.println("PUT SOMETHING USEFUL HERE..."); // DONT FORGET
    }

        if (USERNAME.equals(userName) && PASSWORD.equals(password)) {
            System.out.println(" User successfully logged-in.. ");
            if(true){
                System.out.println("Say now. WHO IS THE BOSS.. HAHA");
            /*
                do stuff do tother stuff
                call the methods and things*/
            }

        } else {
            System.out.println("Invalid userName of password");
            System.out.println("Please try again.");
            System.out.println("If not user yet, sigh-up...");
             DBconnection Register = new DBconnection();
             Register.Register();
        }
    }while(!USERNAME.equals(userName) && (!PASSWORD.equals(password)));
       //}

    return false;
    }

     public String Register(){

          User Register = new User (""); // instantiating User class

          BufferedReader kb =new BufferedReader (new InputStreamReader(System.in));
          String userFName="",userLName="", userName="",password="";

          try{
          System.out.print("Enter your First Name: ");
          userFName=kb.readLine();
          Register.setUserFirstName(userFName);

             // Setting Last Name
          System.out.print("Enter your Last Name: ");
          userLName=kb.readLine();
          Register.setUserFirstName(userLName);

             // Setting Username
          System.out.print("Enter your Username: ");
          userName=kb.readLine();
          Register.setUserFirstName(userName);

            // Setting password
          System.out.print("Enter your password: ");
          password=kb.readLine();
          Register.setUserFirstName(password);
          }catch(Exception e){
            System.out.println("something went wrong...");

     }
       return null;
     }}

    public class User {

    private String firstName;   // attributes
    private String lastName;
    private String password;
    private int id;

    /**
     * Default blank Constructor constructor for login purposes as User input will be iMplemented
     */
    public User(String userRecord){  // Default constructor

       this.firstName = userRecord;// change the fields user table removing (user_name => name) and so on.
       this.lastName = userRecord;
       this.password = userRecord;

        //...
     //  this.showMenu()// create menu user that shows the options as per requirements in the Project
        // each menu option, creates a method (update name); replace new userName; updatae user record for userName; return true =updated;
      //STEP 4:

    };

    //STEP 5:
    //PUBLIC SHOW MENU
    public String getUserFirstName() {
        return firstName;
    }

    public void setUserFirstName(String userFName) {
        this.firstName = userFName;
    }

    public String getUserLastName() {
        return lastName;
    }

    public void setUserLastName(String userLName) {
        this.lastName = userLName;
    }

    public String getPassWord() {
        return password;
    }

    public void setPassWord(String pass) {
        this.password = pass;
    }

    public int getId() {    // only get id as it is auto increment
        return id;
    }

}


问:
NER classification with LSTM
I am trying to code an NER algorithm using LSTM .
I tried to follow up with this notebook ( instead of NER they did the POS task )

I implement the LSTM using the word and character embedding and got :

F1 Score on test is :0.4324746291959407

```
<p>With this Neural Network :</p>
<pre class="lang-py prettyprint-override"><code>class DualLSTMTagger(nn.Module):
    def __init__(self, word_embedding_dim, word_hidden_dim, char_embedding_dim, char_hidden_dim, word_vocab_size, char_vocab_size, tag_vocab_size):
        super(DualLSTMTagger, self).__init__()
        self.word_embedding = nn.Embedding(word_vocab_size, word_embedding_dim)

        self.char_embedding = nn.Embedding(char_vocab_size, char_embedding_dim)
        self.char_lstm = nn.LSTM(char_embedding_dim, char_hidden_dim)

        self.lstm = nn.LSTM(word_embedding_dim + char_hidden_dim, word_hidden_dim)
        self.hidden2tag = nn.Linear(word_hidden_dim, tag_vocab_size)

    def forward(self, sentence, words):
        embeds = self.word_embedding(sentence)
        char_hidden_final = []
        for word in words:
            char_embeds = self.char_embedding(word)
            _, (char_hidden, char_cell_state) = self.char_lstm(char_embeds.view(len(word), 1, -1))
            word_char_hidden_state = char_hidden.view(-1)
            char_hidden_final.append(word_char_hidden_state)
        char_hidden_final = torch.stack(tuple(char_hidden_final))

        combined = torch.cat((embeds, char_hidden_final), 1)

        lstm_out, _ = self.lstm(combined.view(len(sentence), 1, -1))
        tag_space = self.hidden2tag(lstm_out.view(len(sentence), -1))

        tag_scores = F.log_softmax(tag_space, dim=1)
        return tag_scores
</code>```

I wanted to use the glove embedding to have a better f1

import gensim.downloader as api
word_vectors = api.load("glove-twitter-100")
weights = torch.FloatTensor(word_vectors.vectors)

```
<p>And then replace the</p>
<pre class="lang-py prettyprint-override"><code>        self.word_embedding = nn.Embedding(word_vocab_size, word_embedding_dim)

</code>```

by

        self.word_embedding = nn.Embedding.from_pretrained(weights)

```

The problem is that I am getting a lower F1 Score with the implementation of glove .
Is this common or I missed something there ?

Title: NER classification with LSTM

Body:
I am trying to code an NER algorithm using LSTM .
I tried to follow up with this notebook ( instead of NER they did the POS task )

I implement the LSTM using the word and character embedding and got :

F1 Score on test is :0.4324746291959407

With this Neural Network :

class DualLSTMTagger(nn.Module):
    def __init__(self, word_embedding_dim, word_hidden_dim, char_embedding_dim, char_hidden_dim, word_vocab_size, char_vocab_size, tag_vocab_size):
        super(DualLSTMTagger, self).__init__()
        self.word_embedding = nn.Embedding(word_vocab_size, word_embedding_dim)

        self.char_embedding = nn.Embedding(char_vocab_size, char_embedding_dim)
        self.char_lstm = nn.LSTM(char_embedding_dim, char_hidden_dim)

        self.lstm = nn.LSTM(word_embedding_dim + char_hidden_dim, word_hidden_dim)
        self.hidden2tag = nn.Linear(word_hidden_dim, tag_vocab_size)

    def forward(self, sentence, words):
        embeds = self.word_embedding(sentence)
        char_hidden_final = []
        for word in words:
            char_embeds = self.char_embedding(word)
            _, (char_hidden, char_cell_state) = self.char_lstm(char_embeds.view(len(word), 1, -1))
            word_char_hidden_state = char_hidden.view(-1)
            char_hidden_final.append(word_char_hidden_state)
        char_hidden_final = torch.stack(tuple(char_hidden_final))

        combined = torch.cat((embeds, char_hidden_final), 1)

        lstm_out, _ = self.lstm(combined.view(len(sentence), 1, -1))
        tag_space = self.hidden2tag(lstm_out.view(len(sentence), -1))

        tag_scores = F.log_softmax(tag_space, dim=1)
        return tag_scores

I wanted to use the glove embedding to have a better f1

import gensim.downloader as api
word_vectors = api.load("glove-twitter-100")
weights = torch.FloatTensor(word_vectors.vectors)

And then replace the

        self.word_embedding = nn.Embedding(word_vocab_size, word_embedding_dim)

by

        self.word_embedding = nn.Embedding.from_pretrained(weights)

The problem is that I am getting a lower F1 Score with the implementation of glove .
Is this common or I missed something there ?


问:
how buy/sell with stripe few products
so i develop a little project with nodejs express and react and one of the functions i do its to sell products
now i do the payment with stripe and i success to sell the same project with any quantity but the
the problem is i dont know How to sell several different products
so i know how to sell the same product with a variable amount But not a number of different products

this is the code how i sell the same products
this is the backend

exports.getCheckoutSession = async (req, res, next) => {
    const quantityBook = req.params.quantity
    console.log(quantityBook)
    const book = await Book.findById(req.params.bookId)
    console.log(book)
    if (req.body) {
        const books = await Book.findById(req.body.booksId)
        console.log(books)
    }
    if (book.quantity < quantityBook) {
        return next(new AppError(`just has ${book.quantity} in stuck`))
    }
    if (book.quantity <= 0) {
        return next(new AppError('the quantity is 0 please try another book'))
    }
    console.log(book)

    const session = await stripe.checkout.sessions.create({
        payment_method_types: ['card'],
        success_url: `http://127.0.0.1:3001`,
        cancel_url: `http://127.0.0.1:3001/account`,
        customer_email: req.user.email,
        client_reference_id: req.params.bookId,
        line_items: [{
            price_data: {
                currency: 'usd',
                unit_amount: book.price * 100,
                product_data: {
                    name: book.title,
                    description: book.description,
                    images: [book.image],
                },
            },
            quantity: quantityBook,
        }],
        mode: 'payment',
    });
    console.log('sesssssioiononio', session)

    res.status(200).json({
        status: 'suceess',
        session
    })

    if (res.status == 200) {
        const doc = await Book.findByIdAndUpdate(req.params.bookId, { $inc: { quantity: -quantityBook } }, {
            new: true,
            runValidators: true
        })
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script></code>```

this is the code from the frontend

import axios from "axios";
import React, { useEffect, useState } from "react";
import './displayBook.css'
import { useNavigate, useParams } from 'react-router-dom'
import { loadStripe } from '@stripe/stripe-js';

function DisplayBook(props) {

    const [book, setBook] = useState([])
    const [quantity, setQuantityBook] = useState(Number)
    const { bookId } = useParams();

    useEffect(() => {
        axios.create({ withCredentials: true }).get(`http://127.0.0.1:3000/books/${bookId}`)
            .then(res => {
                setBook(res.data.data.book)
            })
    }, [])

    // let navigate = useNavigate();

    const buyNow = async () => {
        const stripe = await loadStripe('PUBLISH_KEY');
        try {
            const session = await axios.create({ withCredentials: true }).get(`http://127.0.0.1:3000/booking/checkout-session/${bookId}/${quantity}`)
            console.log(session)
            console.log(stripe)
            await stripe.redirectToCheckout({ sessionId: session.data.session.id })
        } catch (error) {
            alert("this book is over please try another book")
        }

    }

    if (book === undefined) {
        return <></>
    }
    return (

                 {
                    return el.image
                })} />

rating reviews, search results, social metrics. The bellow reviews were picked manually by Avada Commerce experts, if your CSS Book Effects does not include in the list, feel free to contact us. The best CSS Book Effects css collection is ranked

bookname:{book.map(el => {
                    return el.title
                })}

auther:{book.map(el => {
                    return el.author
                })}

in stuck : {book.map(el => {
                    return el.quantity
                })}

                <button onClick={buyNow} className="buyBtn">Buy Now</button>
                <input onChange={(e) => setQuantityBook(e.target.value)} type='number' className="quentity" placeholder='0' />

    )
}

export default DisplayBook```

I try search in the docs of stripe but i dont find anything

Title: how buy/sell with stripe few products

Body:
so i develop a little project with nodejs express and react and one of the functions i do its to sell products
now i do the payment with stripe and i success to sell the same project with any quantity but the
the problem is i dont know How to sell several different products
so i know how to sell the same product with a variable amount But not a number of different products

this is the code how i sell the same products
this is the backend

exports.getCheckoutSession = async (req, res, next) => {
    const quantityBook = req.params.quantity
    console.log(quantityBook)
    const book = await Book.findById(req.params.bookId)
    console.log(book)
    if (req.body) {
        const books = await Book.findById(req.body.booksId)
        console.log(books)
    }
    if (book.quantity < quantityBook) {
        return next(new AppError(`just has ${book.quantity} in stuck`))
    }
    if (book.quantity <= 0) {
        return next(new AppError('the quantity is 0 please try another book'))
    }
    console.log(book)

    const session = await stripe.checkout.sessions.create({
        payment_method_types: ['card'],
        success_url: `http://127.0.0.1:3001`,
        cancel_url: `http://127.0.0.1:3001/account`,
        customer_email: req.user.email,
        client_reference_id: req.params.bookId,
        line_items: [{
            price_data: {
                currency: 'usd',
                unit_amount: book.price * 100,
                product_data: {
                    name: book.title,
                    description: book.description,
                    images: [book.image],
                },
            },
            quantity: quantityBook,
        }],
        mode: 'payment',
    });
    console.log('sesssssioiononio', session)

    res.status(200).json({
        status: 'suceess',
        session
    })

    if (res.status == 200) {
        const doc = await Book.findByIdAndUpdate(req.params.bookId, { $inc: { quantity: -quantityBook } }, {
            new: true,
            runValidators: true
        })
    }
}

this is the code from the frontend

import axios from "axios";
import React, { useEffect, useState } from "react";
import './displayBook.css'
import { useNavigate, useParams } from 'react-router-dom'
import { loadStripe } from '@stripe/stripe-js';

function DisplayBook(props) {

    const [book, setBook] = useState([])
    const [quantity, setQuantityBook] = useState(Number)
    const { bookId } = useParams();

    useEffect(() => {
        axios.create({ withCredentials: true }).get(`http://127.0.0.1:3000/books/${bookId}`)
            .then(res => {
                setBook(res.data.data.book)
            })
    }, [])

    // let navigate = useNavigate();

    const buyNow = async () => {
        const stripe = await loadStripe('PUBLISH_KEY');
        try {
            const session = await axios.create({ withCredentials: true }).get(`http://127.0.0.1:3000/booking/checkout-session/${bookId}/${quantity}`)
            console.log(session)
            console.log(stripe)
            await stripe.redirectToCheckout({ sessionId: session.data.session.id })
        } catch (error) {
            alert("this book is over please try another book")
        }

    }

    if (book === undefined) {
        return <></>
    }
    return (

                 {
                    return el.image
                })} />

rating reviews, search results, social metrics. The bellow reviews were picked manually by Avada Commerce experts, if your CSS Book Effects does not include in the list, feel free to contact us. The best CSS Book Effects css collection is ranked

bookname:{book.map(el => {
                    return el.title
                })}

auther:{book.map(el => {
                    return el.author
                })}

in stuck : {book.map(el => {
                    return el.quantity
                })}

                <button onClick={buyNow} className="buyBtn">Buy Now</button>
                <input onChange={(e) => setQuantityBook(e.target.value)} type='number' className="quentity" placeholder='0' />

    )
}

export default DisplayBook

I try search in the docs of stripe but i dont find anything