问:
How to fix these Core Data "one-to-many" relationship errors?
I am making a simple macOS Notes app where a user can create new folders and then create new notes for those folders. I am very new to Core Data and the "one-to-many" relationship amongst entities. I am trying to do this relationship with folders and notes. I want each folder to have their own separate notes. I keep getting errors like "Value of optional type 'String?' must be unwrapped to a value of type 'String'", "Coalesce using '??' to provide a default when the optional value contains 'nil'", and "Force-unwrap using '!' to abort execution if the optional value contains 'nil'".

I know I must have one specific problem somewhere in my code but I have no idea where. I have no idea if my code is remotely correct or not.

I have a folder view (Sidebar) and a note view (NoteView). I passed in the selected Folder as an ObservedObject in my NoteView (@ObservedObject var rootFolder: Folder) and tried to create a notesArray. In my NotesView I did rootFolder.notesArray.

Here is part of my Sidebar (folders) view:

```<code>struct Sidebar: View {

    @Environment(\.managedObjectContext) private var viewContext
    @State private var isPresented: Bool = false

    @FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Folder.folderName, ascending: true)])
    var folders: FetchedResults<Folder>

    @State private var selectedFoldersIds: Set<Folder.ID> = []

    private var selectedFolder: Folder?{
        guard let selectedFolderId = selectedFoldersIds.first,
              let selectedFolder = folders.filter ({$0.id == selectedFolderId}).first else{
                  return nil
              }
        return selectedFolder
    }
    var body: some View {

        Button(){
            isPresented = true
        } label: {
            HStack{
                Image(systemName: "folder.badge.plus")
                Text("Add Folder")

            }
            .cornerRadius(50)

        }
        .sheet(isPresented: $isPresented){
            AddFolderView{ name in
                saveNewFolder(name: name)
            }
        }
            .padding()
        Divider()
        Text("Folders")
            .frame(maxWidth: .infinity, alignment: .leading)
            .font(.caption)
            .foregroundColor(.secondary)
        List(folders, selection: $selectedFoldersIds){folder in
               HStack{
                        Image(systemName: "folder")
                   NavigationLink(folder.folderName, destination:NoteView(rootFolder: folder)) //where error occurs. Is the problem something to do with folderName?
                }

       }
</code>```

Part of NoteView:

```<code>struct NoteView: View {
    @ObservedObject var rootFolder: Folder
    @Environment(\.managedObjectContext) private var viewContext
    @State private var isPresented: Bool = false

    @FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Note.name, ascending: true)])
    var notes: FetchedResults<Note>

    @State private var selectedNotesIds: Set<Note.ID> = []

    private var selectedNote: Note?{
        guard let selectedNoteId = selectedNotesIds.first,
              let selectedNote = notes.filter ({$0.id == selectedNoteId}).first else{
                  return nil
              }
        return selectedNote
    }
    var body: some View {
        List {
            ForEach(rootFolder.notesArray) { note in
                NavigationLink(note.name, destination: NoteEditor(note: note)) // where error occurs once again. I think the problem has to do with note.name. Why doesn't this work?
            }

       }
</code>```

Folder and Core Data Properties:

```<code>extension Folder {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Folder> {
        return NSFetchRequest<Folder>(entityName: "Folder")
    }

    @NSManaged public var folderId: UUID?
    @NSManaged public var folderName: String?
    @NSManaged public var notes: NSSet?

    public var notesArray: [Note] {
            let set = notes as? Set<Note> ?? []
            return set.sorted {
                $0.wrappedName > $1.wrappedName // is something wrong with this?
            }
        }

}

extension Folder{

    @objc(addNotesObject:)
    @NSManaged public func addToNotes(_ value: Note)

    @objc(removeNotesObject:)
    @NSManaged public func removeFromNotes(_ value: Note)

    @objc(addNotes:)
    @NSManaged public func addToNotes(_ values: NSSet)

    @objc(removeNotes:)
    @NSManaged public func removeFromNotes(_ values: NSSet)
}

extension Folder : Identifiable {

}
</code>```

Note and Core Data Properties:

```<code>extension Note {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Note> {
        return NSFetchRequest<Note>(entityName: "Note")
    }

    @NSManaged public var id: UUID?
    @NSManaged public var name: String?
    @NSManaged public var text: String? // text attribute is used to pass into a TextEditor. Once again I get errors with this in my TextEditor view.
    @NSManaged public var folder: Folder?

    public var wrappedName: String { // is something wrong with this?
        name ?? "Unknown"
    }

}

extension Note : Identifiable {

}

</code>```

Complete Sidebar code that probably isn't relevant:

```<code>struct Sidebar: View {

    @Environment(\.managedObjectContext) private var viewContext
    @State private var isPresented: Bool = false

    @FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Folder.folderName, ascending: true)])
    var folders: FetchedResults<Folder>

    @State private var selectedFoldersIds: Set<Folder.ID> = []

    private var selectedFolder: Folder?{
        guard let selectedFolderId = selectedFoldersIds.first,
              let selectedFolder = folders.filter ({$0.id == selectedFolderId}).first else{
                  return nil
              }
        return selectedFolder
    }
    var body: some View {

        Button(){
            isPresented = true
        } label: {
            HStack{
                Image(systemName: "folder.badge.plus")
                Text("Add Folder")

            }
            .cornerRadius(50)

        }
        .sheet(isPresented: $isPresented){
            AddFolderView{ name in
                saveNewFolder(name: name)
            }
        }
            .padding()
        Divider()
        Text("Folders")
            .frame(maxWidth: .infinity, alignment: .leading)
            .font(.caption)
            .foregroundColor(.secondary)
        List(folders, selection: $selectedFoldersIds){folder in
               HStack{
                        Image(systemName: "folder")
                   NavigationLink(folder.folderName, destination:NoteView(rootFolder: folder))
                }

       }

        .onDeleteCommand(perform: deleteSelectedFolders)
        .toolbar{
            ToolbarItem(placement: .primaryAction){
                Button(action: toggleSidebar) {
                    Image(systemName: "sidebar.left")
                }
            }
            ToolbarItem(placement: .primaryAction){
                Button(action: deleteSelectedFolders){
                    Label("Delete note", systemImage: "trash")
                }
            }
        }

}

    private func toggleSidebar() {
        NSApp.keyWindow?.firstResponder?
            .tryToPerform(#selector(NSSplitViewController.toggleSidebar(_:)), with: nil)
    }

    func saveNewFolder(name: String){
           let folder = Folder(context: viewContext)
           folder.folderId = UUID()
           folder.folderName = name
           do{
               try viewContext.save()
           } catch{
               let nsError = error as NSError
               fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
           }
       }

    private func deleteSelectedFolders(){
        withAnimation{
            let selectedFolders = folders.filter {selectedFoldersIds.contains($0.id)}
            deleteFolders(folders: selectedFolders)
        }

    }

    private func deleteFolders(folders: [Folder]){
        viewContext.perform{ folders.forEach(viewContext.delete)}
    }
}

</code>```

Complete NoteView code that probably isn't relevant:

```<code>struct NoteView: View {
    @ObservedObject var rootFolder: Folder
    @Environment(\.managedObjectContext) private var viewContext
    @State private var isPresented: Bool = false

    @FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Note.name, ascending: true)])
    var notes: FetchedResults<Note>

    @State private var selectedNotesIds: Set<Note.ID> = []

    private var selectedNote: Note?{
        guard let selectedNoteId = selectedNotesIds.first,
              let selectedNote = notes.filter ({$0.id == selectedNoteId}).first else{
                  return nil
              }
        return selectedNote
    }
    var body: some View {
        List {
            ForEach(rootFolder.notesArray) { note in
                NavigationLink(note.name, destination: NoteEditor(note: note))
            }

       }

        .toolbar{
            ToolbarItem(placement: .primaryAction){
                Button(){
                    isPresented.toggle()
                } label: {
                    Image(systemName: "square.and.pencil")
                }
                .sheet(isPresented: $isPresented){
                    AddNoteView{ name in
                        saveNewNote(name: name, text: "")
                    }
                }
            }

            ToolbarItem(placement: .primaryAction){
                Button(action: deleteSelectedNotes){
                    Label("Delete note", systemImage: "trash")
                }
            }

        }

    }

    func saveNewNote(name: String, text: String){
           let note = Note(context: viewContext)
           note.id = UUID()
           note.name = name
           note.text = text
           do{
               try viewContext.save()
           } catch{
               let nsError = error as NSError
               fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
           }
       }

    private func deleteSelectedNotes(){
        withAnimation{
            let selectedNotes = notes.filter {selectedNotesIds.contains($0.id)}
            deleteNotes(notes: selectedNotes)
        }

    }

    private func deleteNotes(notes: [Note]){
        viewContext.perform{ notes.forEach(viewContext.delete)}
    }
}

</code>```

Body:
I am making a simple macOS Notes app where a user can create new folders and then create new notes for those folders. I am very new to Core Data and the "one-to-many" relationship amongst entities. I am trying to do this relationship with folders and notes. I want each folder to have their own separate notes. I keep getting errors like "Value of optional type 'String?' must be unwrapped to a value of type 'String'", "Coalesce using '??' to provide a default when the optional value contains 'nil'", and "Force-unwrap using '!' to abort execution if the optional value contains 'nil'".

I know I must have one specific problem somewhere in my code but I have no idea where. I have no idea if my code is remotely correct or not.

I have a folder view (Sidebar) and a note view (NoteView). I passed in the selected Folder as an ObservedObject in my NoteView (@ObservedObject var rootFolder: Folder) and tried to create a notesArray. In my NotesView I did rootFolder.notesArray.

Here is part of my Sidebar (folders) view:

struct Sidebar: View {

    @Environment(\.managedObjectContext) private var viewContext
    @State private var isPresented: Bool = false

    @FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Folder.folderName, ascending: true)])
    var folders: FetchedResults<Folder>

    @State private var selectedFoldersIds: Set<Folder.ID> = []

    private var selectedFolder: Folder?{
        guard let selectedFolderId = selectedFoldersIds.first,
              let selectedFolder = folders.filter ({$0.id == selectedFolderId}).first else{
                  return nil
              }
        return selectedFolder
    }
    var body: some View {

        Button(){
            isPresented = true
        } label: {
            HStack{
                Image(systemName: "folder.badge.plus")
                Text("Add Folder")

            }
            .cornerRadius(50)

        }
        .sheet(isPresented: $isPresented){
            AddFolderView{ name in
                saveNewFolder(name: name)
            }
        }
            .padding()
        Divider()
        Text("Folders")
            .frame(maxWidth: .infinity, alignment: .leading)
            .font(.caption)
            .foregroundColor(.secondary)
        List(folders, selection: $selectedFoldersIds){folder in
               HStack{
                        Image(systemName: "folder")
                   NavigationLink(folder.folderName, destination:NoteView(rootFolder: folder)) //where error occurs. Is the problem something to do with folderName?
                }

       }

Part of NoteView:

struct NoteView: View {
    @ObservedObject var rootFolder: Folder
    @Environment(\.managedObjectContext) private var viewContext
    @State private var isPresented: Bool = false

    @FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Note.name, ascending: true)])
    var notes: FetchedResults<Note>

    @State private var selectedNotesIds: Set<Note.ID> = []

    private var selectedNote: Note?{
        guard let selectedNoteId = selectedNotesIds.first,
              let selectedNote = notes.filter ({$0.id == selectedNoteId}).first else{
                  return nil
              }
        return selectedNote
    }
    var body: some View {
        List {
            ForEach(rootFolder.notesArray) { note in
                NavigationLink(note.name, destination: NoteEditor(note: note)) // where error occurs once again. I think the problem has to do with note.name. Why doesn't this work?
            }

       }

Folder and Core Data Properties:

extension Folder {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Folder> {
        return NSFetchRequest<Folder>(entityName: "Folder")
    }

    @NSManaged public var folderId: UUID?
    @NSManaged public var folderName: String?
    @NSManaged public var notes: NSSet?

    public var notesArray: [Note] {
            let set = notes as? Set<Note> ?? []
            return set.sorted {
                $0.wrappedName > $1.wrappedName // is something wrong with this?
            }
        }

}

extension Folder{

    @objc(addNotesObject:)
    @NSManaged public func addToNotes(_ value: Note)

    @objc(removeNotesObject:)
    @NSManaged public func removeFromNotes(_ value: Note)

    @objc(addNotes:)
    @NSManaged public func addToNotes(_ values: NSSet)

    @objc(removeNotes:)
    @NSManaged public func removeFromNotes(_ values: NSSet)
}

extension Folder : Identifiable {

}

Note and Core Data Properties:

extension Note {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Note> {
        return NSFetchRequest<Note>(entityName: "Note")
    }

    @NSManaged public var id: UUID?
    @NSManaged public var name: String?
    @NSManaged public var text: String? // text attribute is used to pass into a TextEditor. Once again I get errors with this in my TextEditor view.
    @NSManaged public var folder: Folder?

    public var wrappedName: String { // is something wrong with this?
        name ?? "Unknown"
    }

}

extension Note : Identifiable {

}

Complete Sidebar code that probably isn't relevant:

struct Sidebar: View {

    @Environment(\.managedObjectContext) private var viewContext
    @State private var isPresented: Bool = false

    @FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Folder.folderName, ascending: true)])
    var folders: FetchedResults<Folder>

    @State private var selectedFoldersIds: Set<Folder.ID> = []

    private var selectedFolder: Folder?{
        guard let selectedFolderId = selectedFoldersIds.first,
              let selectedFolder = folders.filter ({$0.id == selectedFolderId}).first else{
                  return nil
              }
        return selectedFolder
    }
    var body: some View {

        Button(){
            isPresented = true
        } label: {
            HStack{
                Image(systemName: "folder.badge.plus")
                Text("Add Folder")

            }
            .cornerRadius(50)

        }
        .sheet(isPresented: $isPresented){
            AddFolderView{ name in
                saveNewFolder(name: name)
            }
        }
            .padding()
        Divider()
        Text("Folders")
            .frame(maxWidth: .infinity, alignment: .leading)
            .font(.caption)
            .foregroundColor(.secondary)
        List(folders, selection: $selectedFoldersIds){folder in
               HStack{
                        Image(systemName: "folder")
                   NavigationLink(folder.folderName, destination:NoteView(rootFolder: folder))
                }

       }

        .onDeleteCommand(perform: deleteSelectedFolders)
        .toolbar{
            ToolbarItem(placement: .primaryAction){
                Button(action: toggleSidebar) {
                    Image(systemName: "sidebar.left")
                }
            }
            ToolbarItem(placement: .primaryAction){
                Button(action: deleteSelectedFolders){
                    Label("Delete note", systemImage: "trash")
                }
            }
        }

}

    private func toggleSidebar() {
        NSApp.keyWindow?.firstResponder?
            .tryToPerform(#selector(NSSplitViewController.toggleSidebar(_:)), with: nil)
    }

    func saveNewFolder(name: String){
           let folder = Folder(context: viewContext)
           folder.folderId = UUID()
           folder.folderName = name
           do{
               try viewContext.save()
           } catch{
               let nsError = error as NSError
               fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
           }
       }

    private func deleteSelectedFolders(){
        withAnimation{
            let selectedFolders = folders.filter {selectedFoldersIds.contains($0.id)}
            deleteFolders(folders: selectedFolders)
        }

    }

    private func deleteFolders(folders: [Folder]){
        viewContext.perform{ folders.forEach(viewContext.delete)}
    }
}

Complete NoteView code that probably isn't relevant:

struct NoteView: View {
    @ObservedObject var rootFolder: Folder
    @Environment(\.managedObjectContext) private var viewContext
    @State private var isPresented: Bool = false

    @FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Note.name, ascending: true)])
    var notes: FetchedResults<Note>

    @State private var selectedNotesIds: Set<Note.ID> = []

    private var selectedNote: Note?{
        guard let selectedNoteId = selectedNotesIds.first,
              let selectedNote = notes.filter ({$0.id == selectedNoteId}).first else{
                  return nil
              }
        return selectedNote
    }
    var body: some View {
        List {
            ForEach(rootFolder.notesArray) { note in
                NavigationLink(note.name, destination: NoteEditor(note: note))
            }

       }

        .toolbar{
            ToolbarItem(placement: .primaryAction){
                Button(){
                    isPresented.toggle()
                } label: {
                    Image(systemName: "square.and.pencil")
                }
                .sheet(isPresented: $isPresented){
                    AddNoteView{ name in
                        saveNewNote(name: name, text: "")
                    }
                }
            }

            ToolbarItem(placement: .primaryAction){
                Button(action: deleteSelectedNotes){
                    Label("Delete note", systemImage: "trash")
                }
            }

        }

    }

    func saveNewNote(name: String, text: String){
           let note = Note(context: viewContext)
           note.id = UUID()
           note.name = name
           note.text = text
           do{
               try viewContext.save()
           } catch{
               let nsError = error as NSError
               fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
           }
       }

    private func deleteSelectedNotes(){
        withAnimation{
            let selectedNotes = notes.filter {selectedNotesIds.contains($0.id)}
            deleteNotes(notes: selectedNotes)
        }

    }

    private func deleteNotes(notes: [Note]){
        viewContext.perform{ notes.forEach(viewContext.delete)}
    }
}


来源: stackexchange

问:
filter NULL rows if non-null exists in groupby query in SQL (Teradata)
Given the following table:

ID
Price
Agg_ID

1
34
a

1
42
NULL

2
34
c

I would like to have one row per ID where the Agg_ID is not null, if such not null exists, otherwise, one of the null rows is chosen. Regardless, only one row per ID should exist after filter.

ID
Price
Agg_ID

1
34
a

2
34
c

I tried following the following question, suggesting to use the orderby, but I couldn't assert that after orderby, the nonnull rows are first.
Thanks.

ContentLicense: CC BY-SA 4.0


问:
How to unique values from different nodes in xslt
I have below xml

input:

```<code><Records count="1">
<Record contentId="2410630" levelId="442" levelGuid="29c1b6a4-b7db-49dc-a703-e78aa1b1246a" moduleId="875" parentId="0">
    <Record contentId="2410631" levelId="458" levelGuid="67dbf848-5352-4953-a25b-1b1bbcde89be" moduleId="891" parentId="0">
        <Record contentId="2208294" levelId="330" levelGuid="d25cfb04-eb2a-423c-bdab-2db21a58fd4d" moduleId="675" parentId="0">
            <Field id="31799" guid="2ebbfd8e-3e89-4be5-9c1f-1b5e85950753" type="1">Unauthorized modification of Information/System - External</Field>
            <Field id="31796" guid="24640c19-d1de-415b-b349-25b0af521373" type="6">2208294</Field>
        </Record>
    </Record>
    <Record contentId="2410632" levelId="458" levelGuid="67dbf848-5352-4953-a25b-1b1bbcde89be" moduleId="891" parentId="0">
        <Record contentId="2208289" levelId="330" levelGuid="d25cfb04-eb2a-423c-bdab-2db21a58fd4d" moduleId="675" parentId="0">
            <Field id="31799" guid="2ebbfd8e-3e89-4be5-9c1f-1b5e85950753" type="1">Inadequate Information Security Practices</Field>
            <Field id="31796" guid="24640c19-d1de-415b-b349-25b0af521373" type="6">2208289</Field>
        </Record>
    </Record>
    <Record contentId="2410633" levelId="458" levelGuid="67dbf848-5352-4953-a25b-1b1bbcde89be" moduleId="891" parentId="0">
        <Record contentId="2208270" levelId="330" levelGuid="d25cfb04-eb2a-423c-bdab-2db21a58fd4d" moduleId="675" parentId="0">
            <Field id="31799" guid="2ebbfd8e-3e89-4be5-9c1f-1b5e85950753" type="1">Loss of Systems Including Data Center</Field>
            <Field id="31796" guid="24640c19-d1de-415b-b349-25b0af521373" type="6">2208270</Field>
        </Record>
    </Record>
    <Record contentId="2410636" levelId="458" levelGuid="67dbf848-5352-4953-a25b-1b1bbcde89be" moduleId="891" parentId="0">
        <Record contentId="2208289" levelId="330" levelGuid="d25cfb04-eb2a-423c-bdab-2db21a58fd4d" moduleId="675" parentId="0">
            <Field id="31799" guid="2ebbfd8e-3e89-4be5-9c1f-1b5e85950753" type="1">Inadequate Information Security Practices</Field>
            <Field id="31796" guid="24640c19-d1de-415b-b349-25b0af521373" type="6">2208289</Field>
        </Record>
    </Record>
    <Record contentId="2410661" levelId="463" levelGuid="cc59604e-cc41-4253-879a-5fbde3ffd760" moduleId="896" parentId="0">
        <Field id="41541" guid="bae76db7-4e46-4113-a453-68243a76d4f6" type="9">
            <Reference id="2208289">Inadequate Information Security Practices</Reference>
        </Field>
    </Record>
    <Record contentId="2410666" levelId="463" levelGuid="cc59604e-cc41-4253-879a-5fbde3ffd760" moduleId="896" parentId="0">
        <Field id="41541" guid="bae76db7-4e46-4113-a453-68243a76d4f6" type="9">
            <Reference id="2208273"> Loss of 50% Staff </Reference>
        </Field>
    </Record>
    <Record contentId="2410649" levelId="462" levelGuid="83a26d99-e79d-41af-8a20-fa069f791cef" moduleId="895" parentId="0">
        <Field id="41453" guid="9a764db7-a75e-4a49-9b26-de03e2bc4bb5" type="9">
            <Reference id="2208328">Technology Configuration</Reference>
        </Field>
    </Record>
</Record>
</Records>
</code>```

Expected Output:

```<code>    <uniqueValues>Inadequate Information Security Practices</uniqueValues>
    <uniqueValues>Loss of Systems Including Data Center</uniqueValues>
    <uniqueValues>Loss of 50% Staff</uniqueValues>
    <uniqueValues>Technology Configuration</uniqueValues>
</code>```

Here is my code

```<code>  <xsl:stylesheet version="3.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
  <xsl:output method="xml" indent="yes"/>

<xsl:output method="xml"/>

  <xsl:variable name ="fields" select="//Metadata/FieldDefinitions" />

  <!--match the root node-->
  <xsl:template match="Records">
    <ArcherRecords>

      <xsl:for-each select="Record[@levelGuid='29c1b6a4-b7db-49dc-a703-e78aa1b1246a']">
          <xsl:variable name="valuesTobeCompared" select="Record/Field[@guid='bae76db7-4e46-4113-a453-68243a76d4f6']/Reference/@id"/>
          <xsl:for-each-group select="Record/Record" group-by="./Field[@guid='24640c19-d1de-415b-b349-25b0af521373']">
            <xsl:choose>
              <xsl:when test="$valuesTobeCompared = ./Field[@guid='24640c19-d1de-415b-b349-25b0af521373']">
              </xsl:when>
              <xsl:otherwise>
                 <uniqueValues><xsl:value-of select="./Field[@guid='24640c19-d1de-415b-b349-25b0af521373']"/></uniqueValues>
              </xsl:otherwise>
            </xsl:choose>
          </xsl:for-each-group>
      </xsl:for-each>
    </ArcherRecords>
  </xsl:template>
  </xsl:stylesheet>
</code>```

but it is only giving first set of unique values but I want all unique values from entire record set along with it should also have one value of duplicated value, I was not sure how to get all node values into one variable I am able to store only one node values into variable,
Could anybody help me how to write a xslt code to get the unique values

group-by itself will retrieve unique values from provided selectpath, but how can I give multiple node-set values to for-each-group

Body:
I have below xml

input:

<Records count="1">
<Record contentId="2410630" levelId="442" levelGuid="29c1b6a4-b7db-49dc-a703-e78aa1b1246a" moduleId="875" parentId="0">
    <Record contentId="2410631" levelId="458" levelGuid="67dbf848-5352-4953-a25b-1b1bbcde89be" moduleId="891" parentId="0">
        <Record contentId="2208294" levelId="330" levelGuid="d25cfb04-eb2a-423c-bdab-2db21a58fd4d" moduleId="675" parentId="0">
            <Field id="31799" guid="2ebbfd8e-3e89-4be5-9c1f-1b5e85950753" type="1">Unauthorized modification of Information/System - External</Field>
            <Field id="31796" guid="24640c19-d1de-415b-b349-25b0af521373" type="6">2208294</Field>
        </Record>
    </Record>
    <Record contentId="2410632" levelId="458" levelGuid="67dbf848-5352-4953-a25b-1b1bbcde89be" moduleId="891" parentId="0">
        <Record contentId="2208289" levelId="330" levelGuid="d25cfb04-eb2a-423c-bdab-2db21a58fd4d" moduleId="675" parentId="0">
            <Field id="31799" guid="2ebbfd8e-3e89-4be5-9c1f-1b5e85950753" type="1">Inadequate Information Security Practices</Field>
            <Field id="31796" guid="24640c19-d1de-415b-b349-25b0af521373" type="6">2208289</Field>
        </Record>
    </Record>
    <Record contentId="2410633" levelId="458" levelGuid="67dbf848-5352-4953-a25b-1b1bbcde89be" moduleId="891" parentId="0">
        <Record contentId="2208270" levelId="330" levelGuid="d25cfb04-eb2a-423c-bdab-2db21a58fd4d" moduleId="675" parentId="0">
            <Field id="31799" guid="2ebbfd8e-3e89-4be5-9c1f-1b5e85950753" type="1">Loss of Systems Including Data Center</Field>
            <Field id="31796" guid="24640c19-d1de-415b-b349-25b0af521373" type="6">2208270</Field>
        </Record>
    </Record>
    <Record contentId="2410636" levelId="458" levelGuid="67dbf848-5352-4953-a25b-1b1bbcde89be" moduleId="891" parentId="0">
        <Record contentId="2208289" levelId="330" levelGuid="d25cfb04-eb2a-423c-bdab-2db21a58fd4d" moduleId="675" parentId="0">
            <Field id="31799" guid="2ebbfd8e-3e89-4be5-9c1f-1b5e85950753" type="1">Inadequate Information Security Practices</Field>
            <Field id="31796" guid="24640c19-d1de-415b-b349-25b0af521373" type="6">2208289</Field>
        </Record>
    </Record>
    <Record contentId="2410661" levelId="463" levelGuid="cc59604e-cc41-4253-879a-5fbde3ffd760" moduleId="896" parentId="0">
        <Field id="41541" guid="bae76db7-4e46-4113-a453-68243a76d4f6" type="9">
            <Reference id="2208289">Inadequate Information Security Practices</Reference>
        </Field>
    </Record>
    <Record contentId="2410666" levelId="463" levelGuid="cc59604e-cc41-4253-879a-5fbde3ffd760" moduleId="896" parentId="0">
        <Field id="41541" guid="bae76db7-4e46-4113-a453-68243a76d4f6" type="9">
            <Reference id="2208273"> Loss of 50% Staff </Reference>
        </Field>
    </Record>
    <Record contentId="2410649" levelId="462" levelGuid="83a26d99-e79d-41af-8a20-fa069f791cef" moduleId="895" parentId="0">
        <Field id="41453" guid="9a764db7-a75e-4a49-9b26-de03e2bc4bb5" type="9">
            <Reference id="2208328">Technology Configuration</Reference>
        </Field>
    </Record>
</Record>
</Records>

Expected Output:

    <uniqueValues>Inadequate Information Security Practices</uniqueValues>
    <uniqueValues>Loss of Systems Including Data Center</uniqueValues>
    <uniqueValues>Loss of 50% Staff</uniqueValues>
    <uniqueValues>Technology Configuration</uniqueValues>

Here is my code

  <xsl:stylesheet version="3.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
  <xsl:output method="xml" indent="yes"/>

<xsl:output method="xml"/>

  <xsl:variable name ="fields" select="//Metadata/FieldDefinitions" />

  <xsl:template match="Records">
    <ArcherRecords>

      <xsl:for-each select="Record[@levelGuid='29c1b6a4-b7db-49dc-a703-e78aa1b1246a']">
          <xsl:variable name="valuesTobeCompared" select="Record/Field[@guid='bae76db7-4e46-4113-a453-68243a76d4f6']/Reference/@id"/>
          <xsl:for-each-group select="Record/Record" group-by="./Field[@guid='24640c19-d1de-415b-b349-25b0af521373']">
            <xsl:choose>
              <xsl:when test="$valuesTobeCompared = ./Field[@guid='24640c19-d1de-415b-b349-25b0af521373']">
              </xsl:when>
              <xsl:otherwise>
                 <uniqueValues><xsl:value-of select="./Field[@guid='24640c19-d1de-415b-b349-25b0af521373']"/></uniqueValues>
              </xsl:otherwise>
            </xsl:choose>
          </xsl:for-each-group>
      </xsl:for-each>
    </ArcherRecords>
  </xsl:template>
  </xsl:stylesheet>

but it is only giving first set of unique values but I want all unique values from entire record set along with it should also have one value of duplicated value, I was not sure how to get all node values into one variable I am able to store only one node values into variable,
Could anybody help me how to write a xslt code to get the unique values

group-by itself will retrieve unique values from provided selectpath, but how can I give multiple node-set values to for-each-group


问:
Mongodb skips over check for duplicate
I'm using mongodb and next.js to check if a user exists in a database array, then add a like and increment a database element if this is true. The database is structured liked this:

likes -> by -> [array of users]

My code to find if a user exists in the database array is this:

 db.collection('quotes').findOne({
      likes: {
        by: cookies.get('user')
      }
    }, async function(liked) {
      if (!liked) {
      //...Add like
```
<p>However, for some reason the like just keeps getting added, regardless of the check if the user exists. I also get this error for some reason:</p>
<blockquote>
<p>API resolved without sending a response for /api/like, this may result in stalled requests.</p>
</blockquote>
<p>Here's my full code for <code>api/like</code></p>
<pre class="lang-js prettyprint-override"><code>import clientPromise from "../../lib/mongodb";
const ObjectId = require('mongodb').ObjectId;
import Cookies from 'cookies'

export default async function handler(req, res) {
  switch (req.method) {
    case 'POST': {
      return like(req, res);
    }
  }
}

async function like(req, res) {
  const cookies = new Cookies(req, res)
  const client = await clientPromise;
  const db = client.db("the-quotes-place");

  if (cookies.get('user') != null) {
    db.collection('quotes').findOne({
      likes: {
        by: cookies.get('user')
      }
    }, async function(liked) {
      if (!liked) {
        await db.collection('quotes').updateOne(
          { _id: new ObjectId(req.body.id) },
          {
          $inc: {
            "likes.num": 1
          },
          $push: {
            "likes.by": cookies.get('user')
          }
        })

        res.status(200).json({
          message: 'Succesfully added like',
          success: true
        })
      }
    })
  } else {
    res.status(403).json({
      message: 'Error: Cookies not found',
      success: true
    })
  }
}
</code>```

What's going on here?
Thanks for any help.

Title: Mongodb skips over check for duplicate

Body:
I'm using mongodb and next.js to check if a user exists in a database array, then add a like and increment a database element if this is true. The database is structured liked this:

likes -> by -> [array of users]

My code to find if a user exists in the database array is this:

 db.collection('quotes').findOne({
      likes: {
        by: cookies.get('user')
      }
    }, async function(liked) {
      if (!liked) {
      //...Add like

However, for some reason the like just keeps getting added, regardless of the check if the user exists. I also get this error for some reason:

API resolved without sending a response for /api/like, this may result in stalled requests.

Here's my full code for api/like

import clientPromise from "../../lib/mongodb";
const ObjectId = require('mongodb').ObjectId;
import Cookies from 'cookies'

export default async function handler(req, res) {
  switch (req.method) {
    case 'POST': {
      return like(req, res);
    }
  }
}

async function like(req, res) {
  const cookies = new Cookies(req, res)
  const client = await clientPromise;
  const db = client.db("the-quotes-place");

  if (cookies.get('user') != null) {
    db.collection('quotes').findOne({
      likes: {
        by: cookies.get('user')
      }
    }, async function(liked) {
      if (!liked) {
        await db.collection('quotes').updateOne(
          { _id: new ObjectId(req.body.id) },
          {
          $inc: {
            "likes.num": 1
          },
          $push: {
            "likes.by": cookies.get('user')
          }
        })

        res.status(200).json({
          message: 'Succesfully added like',
          success: true
        })
      }
    })
  } else {
    res.status(403).json({
      message: 'Error: Cookies not found',
      success: true
    })
  }
}

What's going on here?
Thanks for any help.


问:
Express js: page not correctly loading data
I have a page in an express.js app with a list of data from a Postgresql database. I have a delete button on my page that will delete the selected rows from the database based on the passed uuid's.  The problem I'm having is that sometimes when deleting data the row will be deleted in de database but the page will not update the data to show the new situation (for example if I delete a row with a date of Nov 9th it will be deleted in the database but it won't be gone on the page unless I reload multiple times). after deleting I redirect to the router that gets the data from the database and renders the page.

Script that executes the post request and page reload:

```<code>jQuery(function () {
    $("#deletemoment").on('click' ,function (event) {
        console.log('hello');
        $.confirm({
            title: 'Confirm deletion',
            content: 'Do you really want to delete this training?',
            buttons: {
                confirm: function(){
                    $.post('/groups/deletemoment',
                    {
                        uuid: getAllCheckedUuids().toString()
                    },
                    function (data,status){
                        console.log(data);

                    });
                    $.alert('Moment deleted succesfully!');
                    //reload page
                    location.reload();
                },
                cancel: function(){

                }
            }
        })
    });
    });

function getAllCheckedUuids(){
    var values = []
    var markedCheckbox = document.getElementsByName('checkbox');
    for(var checkbox of markedCheckbox){
        if(checkbox.checked){
            values.push(checkbox.id);
        }
    }
    //console.log(values)
    return values

}
</code>```

Delete request router:

```<code>router.post('/deletemoment', function(req, res, next){
  uuids = req.body.uuid.split(',');
  var sql = 'delete from "TrustCalendar".training_moment where uuid = any($1);';
  db.pool.query(sql, [uuids], function(err, res){
    if(err){
      throw err;
    }
  })
})
</code>```

Page refresh router:

```<code>router.get('/grouptrainingmomentslist', function(req, res, next){
  var group = req.query.group;
  console.log(group)
  var sql = 'select * from "TrustCalendar".training_moment where "group" = $1';
  var training_moments;
  db.pool.query(sql, [group], (err, results) => {
    if (err) {
      throw err;
    }
    //console.log(results.rows)
    training_moments = results.rows;
    console.log(training_moments);
    res.render('group-training-hours-list', { training_moments: training_moments });
  })

})
</code>```

Page jade file:

```<code>extends layout
block scripts
    script(type='text/javascript' src="../scripts/momentactions.js")

block content
    h1 Training Moments overview
    button#deletemoment Delete
    table
        thead
            tr
                th Date
                th Day
                th Trainer
                th From
                th Until
                th Group
        tbody

            each moment in training_moments
                    tr
                        td
                            input(type="checkbox" name='checkbox' id=moment.uuid)
                        td=moment.date
                        td=moment.day
                        td=moment.trainer
                        td=moment.from
                        td=moment.until
                        td=moment.group
                        td=moment.location
</code>```

I have tried to check if the reload is actually used and it seems to get into the router where the list of the data is retrieved from the database but sometimes the list is not correct.

Body:
I have a page in an express.js app with a list of data from a Postgresql database. I have a delete button on my page that will delete the selected rows from the database based on the passed uuid's.  The problem I'm having is that sometimes when deleting data the row will be deleted in de database but the page will not update the data to show the new situation (for example if I delete a row with a date of Nov 9th it will be deleted in the database but it won't be gone on the page unless I reload multiple times). after deleting I redirect to the router that gets the data from the database and renders the page.

Script that executes the post request and page reload:

jQuery(function () {
    $("#deletemoment").on('click' ,function (event) {
        console.log('hello');
        $.confirm({
            title: 'Confirm deletion',
            content: 'Do you really want to delete this training?',
            buttons: {
                confirm: function(){
                    $.post('/groups/deletemoment',
                    {
                        uuid: getAllCheckedUuids().toString()
                    },
                    function (data,status){
                        console.log(data);

                    });
                    $.alert('Moment deleted succesfully!');
                    //reload page
                    location.reload();
                },
                cancel: function(){

                }
            }
        })
    });
    });

function getAllCheckedUuids(){
    var values = []
    var markedCheckbox = document.getElementsByName('checkbox');
    for(var checkbox of markedCheckbox){
        if(checkbox.checked){
            values.push(checkbox.id);
        }
    }
    //console.log(values)
    return values

}

Delete request router:

router.post('/deletemoment', function(req, res, next){
  uuids = req.body.uuid.split(',');
  var sql = 'delete from "TrustCalendar".training_moment where uuid = any($1);';
  db.pool.query(sql, [uuids], function(err, res){
    if(err){
      throw err;
    }
  })
})

Page refresh router:

router.get('/grouptrainingmomentslist', function(req, res, next){
  var group = req.query.group;
  console.log(group)
  var sql = 'select * from "TrustCalendar".training_moment where "group" = $1';
  var training_moments;
  db.pool.query(sql, [group], (err, results) => {
    if (err) {
      throw err;
    }
    //console.log(results.rows)
    training_moments = results.rows;
    console.log(training_moments);
    res.render('group-training-hours-list', { training_moments: training_moments });
  })

})

Page jade file:

extends layout
block scripts
    script(type='text/javascript' src="../scripts/momentactions.js")

block content
    h1 Training Moments overview
    button#deletemoment Delete
    table
        thead
            tr
                th Date
                th Day
                th Trainer
                th From
                th Until
                th Group
        tbody

            each moment in training_moments
                    tr
                        td
                            input(type="checkbox" name='checkbox' id=moment.uuid)
                        td=moment.date
                        td=moment.day
                        td=moment.trainer
                        td=moment.from
                        td=moment.until
                        td=moment.group
                        td=moment.location

I have tried to check if the reload is actually used and it seems to get into the router where the list of the data is retrieved from the database but sometimes the list is not correct.


问:
React Native android release error A problem occurred evaluating project ':app'. > Could not find method splits() for arguments error
i have a problem when receiving application release
yarn android --variant release i'm running this command and gives me the following error;

```<code>yarn android --variant release
yarn run v1.22.19
$ react-native run-android --variant release
info Starting JS server...
info Launching emulator...
info Successfully launched emulator.
info Installing the app...
5 actionable tasks: 5 up-to-date

FAILURE: Build failed with an exception.

* Where:
Build file 'C:\Users\user_0\Desktop\AwesomeProject\android\app\build.gradle' line: 216

* What went wrong:
A problem occurred evaluating project ':app'.
> Could not find method splits() for arguments [build_9cj0nm0uy7u5p9mmnrxyr8ysi$_run_closure6@3c34a482] on project ':app' of type org.gradle.api.Project.

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BU�LD FAILED in 3s

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: gradlew.bat app:installRelease -PreactNativeDevServerPort=8081

FAILURE: Build failed with an exception.

* Where:
Build file 'C:\Users\user_0\Desktop\AwesomeProject\android\app\build.gradle' line: 216

* What went wrong:
A problem occurred evaluating project ':app'.
> Could not find method splits() for arguments [build_9cj0nm0uy7u5p9mmnrxyr8ysi$_run_closure6@3c34a482] on project ':app' of type org.gradle.api.Project.

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BU�LD FAILED in 3s

    at makeError (C:\Users\user_0\Desktop\AwesomeProject\node_modules\execa\index.js:174:9)
    at C:\Users\user_0\Desktop\AwesomeProject\node_modules\execa\index.js:278:16
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async runOnAllDevices (C:\Users\user_0\Desktop\AwesomeProject\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:109:5)
    at async Command.handleAction (C:\Users\user_0\Desktop\AwesomeProject\node_modules\@react-native-community\cli\build\index.js:142:9)
info Run CLI with --verbose flag for more details.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
</code>```

https://reactnative.dev/docs/signed-apk-android i followed these steps exactly. i tried again 3-4 times but nothing changes. how can i fix this ?

Body:
i have a problem when receiving application release
yarn android --variant release i'm running this command and gives me the following error;

yarn android --variant release
yarn run v1.22.19
$ react-native run-android --variant release
info Starting JS server...
info Launching emulator...
info Successfully launched emulator.
info Installing the app...
5 actionable tasks: 5 up-to-date

FAILURE: Build failed with an exception.

* Where:
Build file 'C:\Users\user_0\Desktop\AwesomeProject\android\app\build.gradle' line: 216

* What went wrong:
A problem occurred evaluating project ':app'.
> Could not find method splits() for arguments [build_9cj0nm0uy7u5p9mmnrxyr8ysi$_run_closure6@3c34a482] on project ':app' of type org.gradle.api.Project.

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BU�LD FAILED in 3s

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: gradlew.bat app:installRelease -PreactNativeDevServerPort=8081

FAILURE: Build failed with an exception.

* Where:
Build file 'C:\Users\user_0\Desktop\AwesomeProject\android\app\build.gradle' line: 216

* What went wrong:
A problem occurred evaluating project ':app'.
> Could not find method splits() for arguments [build_9cj0nm0uy7u5p9mmnrxyr8ysi$_run_closure6@3c34a482] on project ':app' of type org.gradle.api.Project.

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BU�LD FAILED in 3s

    at makeError (C:\Users\user_0\Desktop\AwesomeProject\node_modules\execa\index.js:174:9)
    at C:\Users\user_0\Desktop\AwesomeProject\node_modules\execa\index.js:278:16
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async runOnAllDevices (C:\Users\user_0\Desktop\AwesomeProject\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:109:5)
    at async Command.handleAction (C:\Users\user_0\Desktop\AwesomeProject\node_modules\@react-native-community\cli\build\index.js:142:9)
info Run CLI with --verbose flag for more details.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

https://reactnative.dev/docs/signed-apk-android i followed these steps exactly. i tried again 3-4 times but nothing changes. how can i fix this ?


问:
React Context and Typescript
I'am trying to create a context, this is the code

```<code>import React, { createContext } from 'react'
import { linkData } from '../data'

export const NavBarContext = createContext(null)
console.log(NavBarContext)
export const NavBarProvider = ({ children }: { children: React.ReactNode }) => {
  return (
    <NavBarContext.Provider value={{ linkData }}>
     { children }
    </NavBarContext.Provider>
 )
}
</code>```

This is my first time creating context
But there are a few errors which are giving me troubles:
"Unterminated regular expression literal."
"Cannot find namespace 'NavBarContext'."
"'>' expected."
"Cannot find name 'value'."
"Operator '<' cannot be applied to types 'boolean' and 'RegExp'."
"No value exists in scope for the shorthand property 'children'. Either declare one or provide an initializer."

Codesandbox with same code and erorrs.
Can someone tell me where is the problem?

Title: React Context and Typescript

Body:
I'am trying to create a context, this is the code

import React, { createContext } from 'react'
import { linkData } from '../data'

export const NavBarContext = createContext(null)
console.log(NavBarContext)
export const NavBarProvider = ({ children }: { children: React.ReactNode }) => {
  return (
    <NavBarContext.Provider value={{ linkData }}>
     { children }
    </NavBarContext.Provider>
 )
}

This is my first time creating context
But there are a few errors which are giving me troubles:
"Unterminated regular expression literal."
"Cannot find namespace 'NavBarContext'."
"'>' expected."
"Cannot find name 'value'."
"Operator '<' cannot be applied to types 'boolean' and 'RegExp'."
"No value exists in scope for the shorthand property 'children'. Either declare one or provide an initializer."

Codesandbox with same code and erorrs.
Can someone tell me where is the problem?


问:
I can't get VScode to activate a virtual environment called ll_env
I'm trying to create a virtual environment for Django Project ,(Chapter 18-20) of Python Crash Course, and it won't work

I'm on python version 3.10.7

Here is a link to the book: https://www.google.com/books/edition/Python_Crash_Course_2nd_Edition/w1v6DwAAQBAJ?hl=en&gbpv=1
you can find the chapter in question at page 379

here is the file that generates when you run the first command:
https://github.com/Hunty405/ll_env

```<code>C:\Python\Projects\Learning Log> python -m venv ll_env          **<- Create virtual Environment**
C:\Python\Projects\Learning Log> source ll_env/bin/activate     **<- Activate virtual Environment**
source : The term 'source' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was
included, verify that the path is correct and try again.
At line:1 char:1
+ source ll_env/bin/activate
+ ~~~~~~
    + CategoryInfo          : ObjectNotFound: (source:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

PS C:\Users\hlehm\Onedrive Transfer\Python\Projects\Learning Log>

</code>```

I tried running the given codes in the book but i can't get it to activate the environment
please help

Body:
I'm trying to create a virtual environment for Django Project ,(Chapter 18-20) of Python Crash Course, and it won't work

I'm on python version 3.10.7

Here is a link to the book: https://www.google.com/books/edition/Python_Crash_Course_2nd_Edition/w1v6DwAAQBAJ?hl=en&gbpv=1
you can find the chapter in question at page 379

here is the file that generates when you run the first command:
https://github.com/Hunty405/ll_env

C:\Python\Projects\Learning Log> python -m venv ll_env          **<- Create virtual Environment**
C:\Python\Projects\Learning Log> source ll_env/bin/activate     **<- Activate virtual Environment**
source : The term 'source' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was
included, verify that the path is correct and try again.
At line:1 char:1
+ source ll_env/bin/activate
+ ~~~~~~
    + CategoryInfo          : ObjectNotFound: (source:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

PS C:\Users\hlehm\Onedrive Transfer\Python\Projects\Learning Log>

I tried running the given codes in the book but i can't get it to activate the environment
please help


问:
How to post an audio file from an API call using PHP
I am trying to send an audio voice sms using an API call, but end up getting the error message {"message":"The voice file must be a file.","status":"error"}</p>
```<code>$curl = curl_init();

curl_setopt_array($curl, [
    CURLOPT_URL => 'https://example/api/send',
    CURLOPT_HTTPHEADER => ['api-key: keyxxx='],
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS => http_build_query([
        'recipients' => [
            '233550000000'
        ],
        'voice_file' => new CURLFILE('voice_message.mp3'),
    ]),
]);

$response = curl_exec($curl);

curl_close($curl);
echo $response;
</code>```

Body:
I am trying to send an audio voice sms using an API call, but end up getting the error message {"message":"The voice file must be a file.","status":"error"}

$curl = curl_init();

curl_setopt_array($curl, [
    CURLOPT_URL => 'https://example/api/send',
    CURLOPT_HTTPHEADER => ['api-key: keyxxx='],
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS => http_build_query([
        'recipients' => [
            '233550000000'
        ],
        'voice_file' => new CURLFILE('voice_message.mp3'),
    ]),
]);

$response = curl_exec($curl);

curl_close($curl);
echo $response;


问:
Adding a share link when using fbdialog to post to a users wall
I'm using FBConnect to post a link to a user's wall.  I am using the FBDialog api instead of using graph paths:

```<code>[facebook dialog:@"feed" andParams:_params andDelegate:_delegate];
</code>```

Everything posts correctly except when the wall is viewed, there is no share link, only the like and comment links.  I've researched this and figured out that this appears to be unique to using FBDialog.

If the graph path method is used:

```<code>[facebook requestWithGraphPath:_path andParams:_params andHttpMethod:@"POST" andDelegate:_delegate];
</code>```

the share link shows up.

To fix this, I have added a custom link using the actions parameter provided by FBDialog:

```<code>SBJSON *jsonWriter = [[SBJSON new] autorelease];

NSDictionary* actionLinks = [NSArray arrayWithObjects:
                             [NSDictionary dictionaryWithObjectsAndKeys:
                              @"Share", @"name",
                              @"http:???", @"link",
                              nil],
                             nil];

NSString *actionLinksStr = [jsonWriter stringWithObject:actionLinks];

[params setObject:@"link" forKey:@"type"];
[params setObject:self.url forKey:@"link"];
[params setObject:self.title forKey:@"name"];
[params setObject:self.caption forKey:@"caption"];
[params setObject:actionLinksStr forKey:@"actions"];
</code>```

This again, works correctly and creates a share link.  The question I have is:  What url do I use to share the wall post? Any ideas?

Thanks so much!

ContentLicense: CC BY-SA 3.0

Body:
I'm using FBConnect to post a link to a user's wall.  I am using the FBDialog api instead of using graph paths:

[facebook dialog:@"feed" andParams:_params andDelegate:_delegate];

Everything posts correctly except when the wall is viewed, there is no share link, only the like and comment links.  I've researched this and figured out that this appears to be unique to using FBDialog.

If the graph path method is used:

[facebook requestWithGraphPath:_path andParams:_params andHttpMethod:@"POST" andDelegate:_delegate];

the share link shows up.

To fix this, I have added a custom link using the actions parameter provided by FBDialog:

SBJSON *jsonWriter = [[SBJSON new] autorelease];

NSDictionary* actionLinks = [NSArray arrayWithObjects:
                             [NSDictionary dictionaryWithObjectsAndKeys:
                              @"Share", @"name",
                              @"http:???", @"link",
                              nil],
                             nil];

NSString *actionLinksStr = [jsonWriter stringWithObject:actionLinks];

[params setObject:@"link" forKey:@"type"];
[params setObject:self.url forKey:@"link"];
[params setObject:self.title forKey:@"name"];
[params setObject:self.caption forKey:@"caption"];
[params setObject:actionLinksStr forKey:@"actions"];

This again, works correctly and creates a share link.  The question I have is:  What url do I use to share the wall post? Any ideas?

Thanks so much!


问:
Filter a chart directly in libreoffice calc
I have a chart which shows the data I want when I filter for values > 0 on a single column. But I would like to have this filter inside of the chart itself so that I can look at the workbook with no filters, and still see the chart with the zero values filtered out.

So I want the first row to appear in the chart because the last value is > 0, but I want the chart to ignore the 2nd row because the last column value == 0

Is there some way to set a filter on the chart itself?


问:
Prevent main AppKit app window from opening when loading a SwiftUI preview
I have a Mac App that's mostly written in AppKit. Over time, I'm adding new views in SwiftUI, and all the while I've been using SwiftUI previews to preview both my new SwiftUI views, and my old AppKit views/view controllers (see Previews are not just for SwiftUI views).

One nuisance I've been running into is that starting a SwiftUI preview opens my app's main window. This is a consequence of how previews go through the regular startup flow, e.g. calling applicationDidFinishLaunching(_:) on my App Delegate, which is where I instantiate and present my app's main window on start. Naturally, I don't want that to happen if I'm working on a view in a preview.

Here's what my AppDelegate looks like:

@NSApplicationMain
public class AppDelegate: NSObject, NSApplicationDelegate {
    lazy var mainWindowController = MainWindowController()

    public func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Nasty hack :(
        let isInSwiftUIPreview = ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"] == "1"

        if !isRunningInTest() && !isInSwiftUIPreview {
            mainWindowController.showWindow(self)
        }
    }

    // ...
}
```

As you can see, I've added special cases for not showing the main window if this code is running in a test or SwiftUI preview. This smells, and suggests to me that I'm doing it wrong.

If fact, Apple mentions this exact issue in Mastering Xcode Previews, at 41:41. They suggest to make your app scene-aware and use a UISceneDelegate to do this work instead. However, that's an iOS/catalyst-only API, and I don't see an obvious alternative for AppKit.

With all that said: What's the right way to open the main window of an AppKit app, so that it doesn't open during tests or SwiftUI previews?

Body:
I have a Mac App that's mostly written in AppKit. Over time, I'm adding new views in SwiftUI, and all the while I've been using SwiftUI previews to preview both my new SwiftUI views, and my old AppKit views/view controllers (see Previews are not just for SwiftUI views).

One nuisance I've been running into is that starting a SwiftUI preview opens my app's main window. This is a consequence of how previews go through the regular startup flow, e.g. calling applicationDidFinishLaunching(_:) on my App Delegate, which is where I instantiate and present my app's main window on start. Naturally, I don't want that to happen if I'm working on a view in a preview.

Here's what my AppDelegate looks like:

@NSApplicationMain
public class AppDelegate: NSObject, NSApplicationDelegate {
    lazy var mainWindowController = MainWindowController()

    public func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Nasty hack :(
        let isInSwiftUIPreview = ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"] == "1"

        if !isRunningInTest() && !isInSwiftUIPreview {
            mainWindowController.showWindow(self)
        }
    }

    // ...
}

As you can see, I've added special cases for not showing the main window if this code is running in a test or SwiftUI preview. This smells, and suggests to me that I'm doing it wrong.

If fact, Apple mentions this exact issue in Mastering Xcode Previews, at 41:41. They suggest to make your app scene-aware and use a UISceneDelegate to do this work instead. However, that's an iOS/catalyst-only API, and I don't see an obvious alternative for AppKit.

With all that said: What's the right way to open the main window of an AppKit app, so that it doesn't open during tests or SwiftUI previews?


问:
After upgrade to version 5 'styled-components' is broken
I have the below components made with styled-components. I used to work fine with version 4.2.0. In order to cover my App with unit-tests, I upgraded styled-components to the version: 5.3.6.

After that, styled components stopped working on the "first render" when I am running a pre-compiled bundle. Under "development server" everything is still running normally.

However, when the page renders from a bundle, styles are missing. When I inspect the page, there is a style name my divs, and those styles do not exist.

My components are below:

```<code>import styled from 'styled-components';

export default styled.div`
  text-align: center;
  width: 46px;
  min-height: 100vh;
  flex-direction: column;
  background-color: ${({ admin }) => (admin ? '#ffffff' : '#262626')};
  overflow: hidden;
  white-space: nowrap;
  &:hover {
    width: 250px;
    text-align: left;
  }
  @media (max-width: 768px) {
    display: none;
    &.mobileOpen {
        display: flex;
        &:hover {
                width: 46px;
                text-align: left;
            }
  }
`;

export const MobileNavBar = styled.div`
  @media (min-width: 769px) {
    display: none;
  }
  @media (max-width: 768px) {
    position: fixed;
    z-index: 10;
    text-align: center;
    width: 100vw;
    height: 60px;
    flex-direction: row;
    background-color: ${({ admin }) => (admin ? '#ffffff' : '#262626')};
    overflow: hidden;
    white-space: nowrap;
    justify-content: space-between;
  }
`;

export const MobileNavBarOpen = styled.div`
  position: fixed;
  top: 60px;
  text-align: center;
  width: 46px;
  height: 100vh;
  flex-direction: column;
  background-color: ${({ admin }) => (admin ? '#ffffff' : '#262626')};
  overflow: hidden;
  white-space: nowrap;
  padding-bottom: 100px;
  &:hover {
    width: 250px;
    text-align: left;
  }
  @media (max-width: 768px) {
    display: none;
    &.mobileOpen {
        display: flex;
        &:hover {
                width: 46px;
                text-align: left;
            }
  }
`;
</code>```

My best guess is that styles are generated, then there is a render, and the class name changes under this re-render. The new style-class name is different from the previous one, so my styles are not being associated with the components. I don't have SSR or anything fancy here, just building the bundle with CRA npm run build.

Interestingly, if I press the browser refresh button, the styles appear fine.

What could I do to fix this?

Body:
I have the below components made with styled-components. I used to work fine with version 4.2.0. In order to cover my App with unit-tests, I upgraded styled-components to the version: 5.3.6.

After that, styled components stopped working on the "first render" when I am running a pre-compiled bundle. Under "development server" everything is still running normally.

However, when the page renders from a bundle, styles are missing. When I inspect the page, there is a style name my divs, and those styles do not exist.

My components are below:

import styled from 'styled-components';

export default styled.div`
  text-align: center;
  width: 46px;
  min-height: 100vh;
  flex-direction: column;
  background-color: ${({ admin }) => (admin ? '#ffffff' : '#262626')};
  overflow: hidden;
  white-space: nowrap;
  &:hover {
    width: 250px;
    text-align: left;
  }
  @media (max-width: 768px) {
    display: none;
    &.mobileOpen {
        display: flex;
        &:hover {
                width: 46px;
                text-align: left;
            }
  }
`;

export const MobileNavBar = styled.div`
  @media (min-width: 769px) {
    display: none;
  }
  @media (max-width: 768px) {
    position: fixed;
    z-index: 10;
    text-align: center;
    width: 100vw;
    height: 60px;
    flex-direction: row;
    background-color: ${({ admin }) => (admin ? '#ffffff' : '#262626')};
    overflow: hidden;
    white-space: nowrap;
    justify-content: space-between;
  }
`;

export const MobileNavBarOpen = styled.div`
  position: fixed;
  top: 60px;
  text-align: center;
  width: 46px;
  height: 100vh;
  flex-direction: column;
  background-color: ${({ admin }) => (admin ? '#ffffff' : '#262626')};
  overflow: hidden;
  white-space: nowrap;
  padding-bottom: 100px;
  &:hover {
    width: 250px;
    text-align: left;
  }
  @media (max-width: 768px) {
    display: none;
    &.mobileOpen {
        display: flex;
        &:hover {
                width: 46px;
                text-align: left;
            }
  }
`;

My best guess is that styles are generated, then there is a render, and the class name changes under this re-render. The new style-class name is different from the previous one, so my styles are not being associated with the components. I don't have SSR or anything fancy here, just building the bundle with CRA npm run build.

Interestingly, if I press the browser refresh button, the styles appear fine.

What could I do to fix this?


问:
Error odoo.exceptions.UserError: No data has been found I can't update rate on odoo14
I have this problem in odoo 14 when I update rate, I don't know why but it does not update the rate and it tells me that no data has been found

```<code> Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/odoo/addons/base/models/ir_http.py", line 237, in _dispatch
    result = request.dispatch()
  File "/usr/lib/python3/dist-packages/odoo/http.py", line 685, in dispatch
    result = self._call_function(**self.params)
  File "/usr/lib/python3/dist-packages/odoo/http.py", line 361, in _call_function
    return checked_call(self.db, *args, **kwargs)
  File "/usr/lib/python3/dist-packages/odoo/service/model.py", line 94, in wrapper
    return f(dbname, *args, **kwargs)
  File "/usr/lib/python3/dist-packages/odoo/http.py", line 349, in checked_call
    result = self.endpoint(*a, **kw)
  File "/usr/lib/python3/dist-packages/odoo/http.py", line 914, in __call__
    return self.method(*args, **kw)
  File "/usr/lib/python3/dist-packages/odoo/http.py", line 533, in response_wrap
    response = f(*args, **kw)
  File "/usr/lib/python3/dist-packages/odoo/addons/web/controllers/main.py", line 1388, in call_kw
    return self._call_kw(model, method, args, kwargs)
  File "/usr/lib/python3/dist-packages/odoo/addons/web/controllers/main.py", line 1380, in _call_kw
    return call_kw(request.env[model], method, args, kwargs)
  File "/usr/lib/python3/dist-packages/odoo/api.py", line 399, in call_kw
    result = _call_kw_multi(method, model, args, kwargs)
  File "/usr/lib/python3/dist-packages/odoo/api.py", line 386, in _call_kw_multi
    result = method(recs, *args, **kwargs)
  File "/mnt/alimentos_dms/fc_currency_rate_live/models/res_company.py", line 120, in update_currency_rates_bcv
    self.env.company.update_currency_rates()
  File "/mnt/enterprise/currency_rate_live/models/res_config_settings.py", line 232, in update_currency_rates
    parse_results = parse_function(active_currencies)
  File "/mnt/alimentos_dms/fc_currency_rate_live/models/res_company.py", line 64, in _parse_bcv_data
    dictionary = self.get_dictionary(date, date, 'USD')
  File "/mnt/alimentos_dms/fc_currency_rate_live/models/res_company.py", line 46, in get_dictionary
    dictionary = gr.get_exchange_rate(currency, from_date, end_date, self.env)
  File "/mnt/alimentos_dms/fc_currency_rate_live/models/getrate.py", line 161, in get_exchange_rate
    raise UserError(_("No data found."))
Exception

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/odoo/http.py", line 641, in _handle_exception
    return super(JsonRequest, self)._handle_exception(exception)
  File "/usr/lib/python3/dist-packages/odoo/http.py", line 317, in _handle_exception
    raise exception.with_traceback(None) from new_cause
odoo.exceptions.UserError: No data has been found
</code>```

here it's the getrate.py, but i don't understand why don't read the information

`

```<code> def get_exchange_rate(self, currency, date, to_date=None, env=False):
        data_frame = self._data_frame(currency, date, to_date or date)
        if data_frame is not None:
            data = self._to_dict(data_frame)
            if date and not to_date:
                date = datetime.strptime(date, '%d/%m/%Y')
                return data[date.strftime(self.date_format)]
            return data
        else:
            raise UserError(_("No data found."))
</code>```

`

Body:
I have this problem in odoo 14 when I update rate, I don't know why but it does not update the rate and it tells me that no data has been found

 Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/odoo/addons/base/models/ir_http.py", line 237, in _dispatch
    result = request.dispatch()
  File "/usr/lib/python3/dist-packages/odoo/http.py", line 685, in dispatch
    result = self._call_function(**self.params)
  File "/usr/lib/python3/dist-packages/odoo/http.py", line 361, in _call_function
    return checked_call(self.db, *args, **kwargs)
  File "/usr/lib/python3/dist-packages/odoo/service/model.py", line 94, in wrapper
    return f(dbname, *args, **kwargs)
  File "/usr/lib/python3/dist-packages/odoo/http.py", line 349, in checked_call
    result = self.endpoint(*a, **kw)
  File "/usr/lib/python3/dist-packages/odoo/http.py", line 914, in __call__
    return self.method(*args, **kw)
  File "/usr/lib/python3/dist-packages/odoo/http.py", line 533, in response_wrap
    response = f(*args, **kw)
  File "/usr/lib/python3/dist-packages/odoo/addons/web/controllers/main.py", line 1388, in call_kw
    return self._call_kw(model, method, args, kwargs)
  File "/usr/lib/python3/dist-packages/odoo/addons/web/controllers/main.py", line 1380, in _call_kw
    return call_kw(request.env[model], method, args, kwargs)
  File "/usr/lib/python3/dist-packages/odoo/api.py", line 399, in call_kw
    result = _call_kw_multi(method, model, args, kwargs)
  File "/usr/lib/python3/dist-packages/odoo/api.py", line 386, in _call_kw_multi
    result = method(recs, *args, **kwargs)
  File "/mnt/alimentos_dms/fc_currency_rate_live/models/res_company.py", line 120, in update_currency_rates_bcv
    self.env.company.update_currency_rates()
  File "/mnt/enterprise/currency_rate_live/models/res_config_settings.py", line 232, in update_currency_rates
    parse_results = parse_function(active_currencies)
  File "/mnt/alimentos_dms/fc_currency_rate_live/models/res_company.py", line 64, in _parse_bcv_data
    dictionary = self.get_dictionary(date, date, 'USD')
  File "/mnt/alimentos_dms/fc_currency_rate_live/models/res_company.py", line 46, in get_dictionary
    dictionary = gr.get_exchange_rate(currency, from_date, end_date, self.env)
  File "/mnt/alimentos_dms/fc_currency_rate_live/models/getrate.py", line 161, in get_exchange_rate
    raise UserError(_("No data found."))
Exception

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/odoo/http.py", line 641, in _handle_exception
    return super(JsonRequest, self)._handle_exception(exception)
  File "/usr/lib/python3/dist-packages/odoo/http.py", line 317, in _handle_exception
    raise exception.with_traceback(None) from new_cause
odoo.exceptions.UserError: No data has been found

here it's the getrate.py, but i don't understand why don't read the information

`

 def get_exchange_rate(self, currency, date, to_date=None, env=False):
        data_frame = self._data_frame(currency, date, to_date or date)
        if data_frame is not None:
            data = self._to_dict(data_frame)
            if date and not to_date:
                date = datetime.strptime(date, '%d/%m/%Y')
                return data[date.strftime(self.date_format)]
            return data
        else:
            raise UserError(_("No data found."))

`


问:
Check if user,phone or email is already registered using java and mysql
I create the first try/catch to check if user,email or phone number is already registered, but I got a java.sql.SQLException: Illegal operation on empty result set, when I set a non registered name. When I send a registered name got java.sql.SQLException: Before start of result set. What's happening?

```<code>
    public void createUser(User user) throws NameFieldNotFilledException,EmailFieldNotFilledException, PhoneFieldNotFilledException,
    PasswordFieldNotFilledException, PasswordConfirmationDoesNotMatchException, EmailNotValidException, PasswordInvalidException,
    UserAlreadyRegisteredException, EmailAlreadyRegisteredException, PhoneAlreadyRegisteredException{

        String userSalt = PBKDF2Salt.getSalt();
        Matcher matcherEmail = patternEmail.matcher(user.getEmail());
        Matcher matcherPassword = patternPassword.matcher(user.getPassword());

        try {
            PreparedStatement preparedStatement = this.databaseMySQL.getConnection().
                    prepareStatement("SELECT * FROM OS_USERS WHERE USR_NAME = ? ;");
            preparedStatement.setString(1, user.getName());
            ResultSet resultSet = preparedStatement.executeQuery();
            if (resultSet.getString("USR_NAME").equals(user.getName()))
                throw new UserAlreadyRegisteredException("User already registered");
            if (resultSet.getString("USR_EMAIL").equals(user.getEmail()))
                throw new EmailAlreadyRegisteredException("Email already registered");
            if (resultSet.getString("USR_PHONE").equals(user.getPhone()))
                throw new PhoneAlreadyRegisteredException("Phone already registered");
        }catch (Exception e) {
            e.printStackTrace();
        }

        if (user.getName() == null || user.getName().equalsIgnoreCase("") || user.getName().equalsIgnoreCase("\n"))
            throw new NameFieldNotFilledException("Name is required");
        else if (user.getEmail() == null || user.getEmail().equalsIgnoreCase("") || user.getEmail().equalsIgnoreCase("\n"))
            throw new EmailFieldNotFilledException("Email is required");
        else if (user.getPhone() == null || user.getPhone().equalsIgnoreCase("") || user.getPhone().equalsIgnoreCase("\n"))
            throw new PhoneFieldNotFilledException("Phone is required");
        else if (user.getPassword() == null || user.getPassword().equalsIgnoreCase("") || user.getPassword().equalsIgnoreCase("\n"))
            throw new PasswordFieldNotFilledException("Password is required");
        else if (! user.getConfirmPassword().equals(user.getPassword()))
            throw new PasswordConfirmationDoesNotMatchException("Password and confirm password do not match");
        else if (! matcherEmail.matches())
            throw new EmailNotValidException("Email format invalid. Example valid: user@domain.com");
        else if (! matcherPassword.matches())
            throw new PasswordInvalidException("Invalid password");
        else {
            try {
                PreparedStatement preparedStatement = this.databaseMySQL.getConnection().prepareStatement("INSERT INTO OS_USERS VALUES (?, ?, ?, ?, ?, ?);");
                preparedStatement.setInt(1, user.getId());
                preparedStatement.setString(2, user.getName());
                preparedStatement.setString(3, user.getEmail());
                preparedStatement.setString(4, user.getPhone());
                preparedStatement.setString(5, PBKDF2Salt.hashing(user.getPassword(),userSalt));
                preparedStatement.setString(6,userSalt);
                preparedStatement.execute();
            }catch(SQLException exception){
                exception.printStackTrace();
            }
        }
    }
</code>```

I want to throw these exception if already exists username, email or phone in my database

Body:
I create the first try/catch to check if user,email or phone number is already registered, but I got a java.sql.SQLException: Illegal operation on empty result set, when I set a non registered name. When I send a registered name got java.sql.SQLException: Before start of result set. What's happening?

    public void createUser(User user) throws NameFieldNotFilledException,EmailFieldNotFilledException, PhoneFieldNotFilledException,
    PasswordFieldNotFilledException, PasswordConfirmationDoesNotMatchException, EmailNotValidException, PasswordInvalidException,
    UserAlreadyRegisteredException, EmailAlreadyRegisteredException, PhoneAlreadyRegisteredException{

        String userSalt = PBKDF2Salt.getSalt();
        Matcher matcherEmail = patternEmail.matcher(user.getEmail());
        Matcher matcherPassword = patternPassword.matcher(user.getPassword());

        try {
            PreparedStatement preparedStatement = this.databaseMySQL.getConnection().
                    prepareStatement("SELECT * FROM OS_USERS WHERE USR_NAME = ? ;");
            preparedStatement.setString(1, user.getName());
            ResultSet resultSet = preparedStatement.executeQuery();
            if (resultSet.getString("USR_NAME").equals(user.getName()))
                throw new UserAlreadyRegisteredException("User already registered");
            if (resultSet.getString("USR_EMAIL").equals(user.getEmail()))
                throw new EmailAlreadyRegisteredException("Email already registered");
            if (resultSet.getString("USR_PHONE").equals(user.getPhone()))
                throw new PhoneAlreadyRegisteredException("Phone already registered");
        }catch (Exception e) {
            e.printStackTrace();
        }

        if (user.getName() == null || user.getName().equalsIgnoreCase("") || user.getName().equalsIgnoreCase("\n"))
            throw new NameFieldNotFilledException("Name is required");
        else if (user.getEmail() == null || user.getEmail().equalsIgnoreCase("") || user.getEmail().equalsIgnoreCase("\n"))
            throw new EmailFieldNotFilledException("Email is required");
        else if (user.getPhone() == null || user.getPhone().equalsIgnoreCase("") || user.getPhone().equalsIgnoreCase("\n"))
            throw new PhoneFieldNotFilledException("Phone is required");
        else if (user.getPassword() == null || user.getPassword().equalsIgnoreCase("") || user.getPassword().equalsIgnoreCase("\n"))
            throw new PasswordFieldNotFilledException("Password is required");
        else if (! user.getConfirmPassword().equals(user.getPassword()))
            throw new PasswordConfirmationDoesNotMatchException("Password and confirm password do not match");
        else if (! matcherEmail.matches())
            throw new EmailNotValidException("Email format invalid. Example valid: user@domain.com");
        else if (! matcherPassword.matches())
            throw new PasswordInvalidException("Invalid password");
        else {
            try {
                PreparedStatement preparedStatement = this.databaseMySQL.getConnection().prepareStatement("INSERT INTO OS_USERS VALUES (?, ?, ?, ?, ?, ?);");
                preparedStatement.setInt(1, user.getId());
                preparedStatement.setString(2, user.getName());
                preparedStatement.setString(3, user.getEmail());
                preparedStatement.setString(4, user.getPhone());
                preparedStatement.setString(5, PBKDF2Salt.hashing(user.getPassword(),userSalt));
                preparedStatement.setString(6,userSalt);
                preparedStatement.execute();
            }catch(SQLException exception){
                exception.printStackTrace();
            }
        }
    }

I want to throw these exception if already exists username, email or phone in my database


问:
TailWind not applying in Phoenix/Elixir project
I am trying to migrate from Bootstrap to TailWind and it is not applying the styles from my html in the browser. I followed the documentation for Phoenix specifically, but for some reason it's not watching/building with TailWind.

mix.exs:

```<code> defp aliases do
    [
      "assets.deploy": ["tailwind default --minify", "esbuild default --minify", "phx.digest"]
    ]
  end
</code>```

tailwind.config.js:

```<code>let plugin = require('tailwindcss/plugin')

module.exports = {
  important: true,
  content: [
    './js/**/*.{js,vue}',
    '../lib/*_web.ex',
    '../lib/*_web/**/*.*ex',
  ],
  theme: {
    extend: {
      }
    },
  },
  plugins: [
    require('@tailwindcss/forms'),
    plugin(({addVariant}) => addVariant('phx-no-feedback', ['&.phx-no-feedback', '.phx-no-feedback &'])),
    plugin(({addVariant}) => addVariant('phx-click-loading', ['&.phx-click-loading', '.phx-click-loading &'])),
    plugin(({addVariant}) => addVariant('phx-submit-loading', ['&.phx-submit-loading', '.phx-submit-loading &'])),
    plugin(({addVariant}) => addVariant('phx-change-loading', ['&.phx-change-loading', '.phx-change-loading &']))
  ]
}
</code>```

app.css:

```<code>@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";
</code>```

config.exs:

```<code>config :tailwind, version: "3.2.4", default: [
  args: ~w(
    --config=tailwind.config.js
    --input=css/app.css
    --output=../priv/static/assets/app.css
  ),
  cd: Path.expand("../assets", __DIR__)
]
</code>```

dev.exs:

```<code>watchers: [
  tailwind: {Tailwind, :install_and_run, [:default, ~w(--watch)]}
]
</code>```

Body:
I am trying to migrate from Bootstrap to TailWind and it is not applying the styles from my html in the browser. I followed the documentation for Phoenix specifically, but for some reason it's not watching/building with TailWind.

mix.exs:

 defp aliases do
    [
      "assets.deploy": ["tailwind default --minify", "esbuild default --minify", "phx.digest"]
    ]
  end

tailwind.config.js:

let plugin = require('tailwindcss/plugin')

module.exports = {
  important: true,
  content: [
    './js/**/*.{js,vue}',
    '../lib/*_web.ex',
    '../lib/*_web/**/*.*ex',
  ],
  theme: {
    extend: {
      }
    },
  },
  plugins: [
    require('@tailwindcss/forms'),
    plugin(({addVariant}) => addVariant('phx-no-feedback', ['&.phx-no-feedback', '.phx-no-feedback &'])),
    plugin(({addVariant}) => addVariant('phx-click-loading', ['&.phx-click-loading', '.phx-click-loading &'])),
    plugin(({addVariant}) => addVariant('phx-submit-loading', ['&.phx-submit-loading', '.phx-submit-loading &'])),
    plugin(({addVariant}) => addVariant('phx-change-loading', ['&.phx-change-loading', '.phx-change-loading &']))
  ]
}

app.css:

@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";

config.exs:

config :tailwind, version: "3.2.4", default: [
  args: ~w(
    --config=tailwind.config.js
    --input=css/app.css
    --output=../priv/static/assets/app.css
  ),
  cd: Path.expand("../assets", __DIR__)
]

dev.exs:

watchers: [
  tailwind: {Tailwind, :install_and_run, [:default, ~w(--watch)]}
]