问:
minio Unsupported OkHttp library found. Must use okhttp >= 4.8.1
after using minio as instructions and fixing it with ways below, I failed.what can i do to solve this bug</p>
```<code>        <dependency>
        <groupId>io.minio</groupId>
        <artifactId>minio</artifactId>
        <version>8.3.5</version>
        <exclusions>
            <exclusion>
                <artifactId>okhttp</artifactId>
                <groupId>com.squareup.okhttp3</groupId>
            </exclusion>
        </exclusions>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
    <dependency>
        <groupId>com.squareup.okhttp3</groupId>
        <artifactId>okhttp</artifactId>
        <version>4.9.3</version>
    </dependency>
</dependencies>
</code>```

答:
I also experienced this issues with io.minio:minio:8.3.6, but was able to force a newer version of okhttp, which works with the MinIO client library. Here is the snippet of build.gradle (should work similar with Maven):

```<code>implementation("io.minio:minio:8.3.6")
implementation("com.squareup.okhttp3:okhttp:4.9.3")
</code>```

In my case it was probably caused by spring-boot-dependencies coming with the spring dependency plugin, which manages a lot of dependencies containing also okhttp and thus forces the downgrade.

See also:

https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-dependencies/2.6.3

https://github.com/minio/minio-java/issues/1298

Update

With Spring Boot 2.7.0, the fix is no longer required, since the version requirements for okhttp have been updated. The MinIO dependency should work now out of the box.

Body:
after using minio as instructions and fixing it with ways below, I failed.what can i do to solve this bug

        <dependency>
        <groupId>io.minio</groupId>
        <artifactId>minio</artifactId>
        <version>8.3.5</version>
        <exclusions>
            <exclusion>
                <artifactId>okhttp</artifactId>
                <groupId>com.squareup.okhttp3</groupId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>com.squareup.okhttp3</groupId>
        <artifactId>okhttp</artifactId>
        <version>4.9.3</version>
    </dependency>
</dependencies>

Body:
I also experienced this issues with io.minio:minio:8.3.6, but was able to force a newer version of okhttp, which works with the MinIO client library. Here is the snippet of build.gradle (should work similar with Maven):

implementation("io.minio:minio:8.3.6")
implementation("com.squareup.okhttp3:okhttp:4.9.3")

In my case it was probably caused by spring-boot-dependencies coming with the spring dependency plugin, which manages a lot of dependencies containing also okhttp and thus forces the downgrade.

See also:

https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-dependencies/2.6.3

https://github.com/minio/minio-java/issues/1298

Update

With Spring Boot 2.7.0, the fix is no longer required, since the version requirements for okhttp have been updated. The MinIO dependency should work now out of the box.


来源: stackexchange

问:
Fixed Grid inside LazyColumn in Jetpack Compose?
Currently in Jetpack Compose, this code throws an IllegalStateException because you cannot nest two vertically scrolling Composables:

@ExperimentalFoundationApi
@Composable
fun MyLazyColumn() {
    LazyColumn {
        item {
            Text(text = "My LazyColumn Title")
        }
        item {
            LazyVerticalGrid(cells = GridCells.Fixed(4)) {
                items(10) {
                    Box(
                        modifier = Modifier
                            .size(50.dp)
                            .padding(5.dp)
                            .background(Color.Gray)
                    )
                }
            }
        }
    }
}
```

I do not want the grid itself to scroll, but simply display a fixed grid of the Composable that I pass into it. Is there any workaround to displaying a non-scrolling grid inside a LazyColumn?

答:
This accepted answer is great and works fine in case you have a small list of data and simple UI for grid items, but when your data is large and grid's items have a complex UI and state, it will become a laggy and heavy.

In my case , I manage to solve this issue by making the LazyVerticalGrid as the container for grid's items and also the other content , now it looks like this :

```<code>val spanCount = 2
LazyVerticalGrid(
    modifier = modifier
        .fillMaxWidth(),
    cells = GridCells.Fixed(spanCount),
    state = rememberLazyGridState(),
) {
    item(
        span = {
            /** Take a full row */
            GridItemSpan(currentLineSpan = spanCount)
        }
    ) {
        Column(
            modifier = Modifier.fillMaxWidth()
        ) {
            items.forEach {
                /** Iterate over your items here */
            }
        }
    }
    items(
        items = gridItems
    ){gridItem->
        /** Grid items go here */
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Currently in Jetpack Compose, this code throws an IllegalStateException because you cannot nest two vertically scrolling Composables:

@ExperimentalFoundationApi
@Composable
fun MyLazyColumn() {
    LazyColumn {
        item {
            Text(text = "My LazyColumn Title")
        }
        item {
            LazyVerticalGrid(cells = GridCells.Fixed(4)) {
                items(10) {
                    Box(
                        modifier = Modifier
                            .size(50.dp)
                            .padding(5.dp)
                            .background(Color.Gray)
                    )
                }
            }
        }
    }
}

I do not want the grid itself to scroll, but simply display a fixed grid of the Composable that I pass into it. Is there any workaround to displaying a non-scrolling grid inside a LazyColumn?

Body:
This accepted answer is great and works fine in case you have a small list of data and simple UI for grid items, but when your data is large and grid's items have a complex UI and state, it will become a laggy and heavy.

In my case , I manage to solve this issue by making the LazyVerticalGrid as the container for grid's items and also the other content , now it looks like this :

val spanCount = 2
LazyVerticalGrid(
    modifier = modifier
        .fillMaxWidth(),
    cells = GridCells.Fixed(spanCount),
    state = rememberLazyGridState(),
) {
    item(
        span = {
            /** Take a full row */
            GridItemSpan(currentLineSpan = spanCount)
        }
    ) {
        Column(
            modifier = Modifier.fillMaxWidth()
        ) {
            items.forEach {
                /** Iterate over your items here */
            }
        }
    }
    items(
        items = gridItems
    ){gridItem->
        /** Grid items go here */
    }
}


问:
Enterprise Library Logging: Custom trace listener which sends messages to arbitrary WCF endpoint
I'm trying to write a custom trace listener for Enterprise Library Logging which sends all log messages to an arbitrary WCF endpoint. The idea behind this is that I can set up a simple console app, etc at the other end which prints out all log messages in real time.

My question is in two parts:

Is there a mechanism to do this already? I already looked at the MSMQ listener and I'm not interested in using that because I may have a need to use a different protocol/binding at some point.

The way I have it implemented below - is it efficient enough or is there a better way? My concern is that every time a message comes through from the Logger (which may be frequent) I'm opening a new channel and then slamming it shut. Will this cause performance issues?

In my sample RemoteClient derives from ClientBase<T>.

```<code>[ConfigurationElementType(typeof(CustomTraceListenerData))]
public class RemoteTraceListener : CustomTraceListener
{
    public override void Write(string message)
    {
        RemoteClient client = new RemoteClient();
        client.Open();
        client.Write(message);
        client.Close();
    }

    public override void WriteLine(string message)
    {
        RemoteClient client = new RemoteClient();
        client.Open();
        client.WriteLine(message);
        client.Close();
    }

    public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data)
    {
        if (data is LogEntry && this.Formatter != null)
        {
            WriteLine(this.Formatter.Format(data as LogEntry));
        }
        else
        {
            WriteLine(data.ToString());
        }
    }
}
</code>```

答:
I think you should use a SQL database on witch you should log to because if you logg in a console app you could not see for examle something before 2 days.While in SQL you can make a quote and get the right data you need.
Another solution is to use the log4net project.</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to write a custom trace listener for Enterprise Library Logging which sends all log messages to an arbitrary WCF endpoint. The idea behind this is that I can set up a simple console app, etc at the other end which prints out all log messages in real time.

My question is in two parts:

Is there a mechanism to do this already? I already looked at the MSMQ listener and I'm not interested in using that because I may have a need to use a different protocol/binding at some point.

The way I have it implemented below - is it efficient enough or is there a better way? My concern is that every time a message comes through from the Logger (which may be frequent) I'm opening a new channel and then slamming it shut. Will this cause performance issues?

In my sample RemoteClient derives from ClientBase<T>.

[ConfigurationElementType(typeof(CustomTraceListenerData))]
public class RemoteTraceListener : CustomTraceListener
{
    public override void Write(string message)
    {
        RemoteClient client = new RemoteClient();
        client.Open();
        client.Write(message);
        client.Close();
    }

    public override void WriteLine(string message)
    {
        RemoteClient client = new RemoteClient();
        client.Open();
        client.WriteLine(message);
        client.Close();
    }

    public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data)
    {
        if (data is LogEntry && this.Formatter != null)
        {
            WriteLine(this.Formatter.Format(data as LogEntry));
        }
        else
        {
            WriteLine(data.ToString());
        }
    }
}


问:
Am I missing some code to view this video in a react app using visual studio code [react]
App.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';

import { Menu } from './Menu';
import { Video } from './Video';

const VIDEOS = {
  fast: require('./videos/bel.mp4'),
  slow: require('./videos/mimi.mp4'),
  cute: require('./videos/coco.mp4'),
  eek: require('./videos/drea.mp4')
};

export class App extends React.Component {
  constructor(props){
    super(props);

    this.state = {
      src: VIDEOS.fast
    };
  }

  render() {
    return(
      <div>
        <Menu  />
        <Video src={this.state.src} />
      </div>
    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('app')
);
</code>```

Video.js

```<code>import React from 'react';

export class Video extends React.Component {
    render() {
        return(
            <div>
                <video controls autoPlay muted src={this.props.src}/>
            </div>
        );
    }
}
</code>```

Menu.js

```<code>import React from 'react';

export class Menu extends React.Component {
    render(){
        return(
            <form>
                <input type="radio" name="src" value="fast"  /> Bella
                <input type="radio" name="src" value="slow"  /> Coco
                <input type="radio" name="src" value="cute"  /> Mimi
                <input type="radio" name="src" value="eek"  /> Drea
            </form>
        );
    }
}
</code>```

Trying to create a small React app to practice on my personal computer but the video isn't playing, not sure what I am missing. Video player shows and radio buttons are visible but video doesn't play. I know there is more that needs to be done but first I want to have the first video play that is why I set this.state to VIDEOS.fast

答:
The most likely issue is that React is not recognising that you are updating the video source and is not doing a video load.

This is a known characteristic - essentially you have to watch for a change in the src and when you see it trigger a load of the video.

There is a nice example in this answer here: https://stackoverflow.com/a/47382850/334402

Body:
App.js

import React from 'react';
import ReactDOM from 'react-dom';

import { Menu } from './Menu';
import { Video } from './Video';

const VIDEOS = {
  fast: require('./videos/bel.mp4'),
  slow: require('./videos/mimi.mp4'),
  cute: require('./videos/coco.mp4'),
  eek: require('./videos/drea.mp4')
};

export class App extends React.Component {
  constructor(props){
    super(props);

    this.state = {
      src: VIDEOS.fast
    };
  }

  render() {
    return(

        <Menu  />
        <Video src={this.state.src} />

    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('app')
);

Video.js

import React from 'react';

export class Video extends React.Component {
    render() {
        return(

                <video controls autoPlay muted src={this.props.src}/>

        );
    }
}

Menu.js

import React from 'react';

export class Menu extends React.Component {
    render(){
        return(
            <form>
                <input type="radio" name="src" value="fast"  /> Bella
                <input type="radio" name="src" value="slow"  /> Coco
                <input type="radio" name="src" value="cute"  /> Mimi
                <input type="radio" name="src" value="eek"  /> Drea
            </form>
        );
    }
}

Trying to create a small React app to practice on my personal computer but the video isn't playing, not sure what I am missing. Video player shows and radio buttons are visible but video doesn't play. I know there is more that needs to be done but first I want to have the first video play that is why I set this.state to VIDEOS.fast


问:
Class with virtual function, when derived from QObject, leads to linking error
Following is the code that works fine

class HttpService {
public:
    virtual ~HttpService(); // implemented in .cpp
protected:
    HttpService(struct MHD_Connection *conn) {}
};
class HttpFileService : public HttpService
{
public:
    virtual ~HttpFileService() ; // implemented in .cpp
protected:
    HttpFileService(struct MHD_Connection *conn) : HttpService(conn) {}
};
```

<p>Now, when I make <code>HttpService</code> a derived class of <code>QObject</code>, like below:</p>

<pre class="lang-c prettyprint-override"><code>#include <QObject>                      // change #1
class HttpService  : public QObject {   // change #2
    Q_OBJECT                            // change #3
public:
    virtual ~HttpService();
protected:
    HttpService(struct MHD_Connection *conn) {}
};

class HttpFileService : public HttpService {
    Q_OBJECT                            // change #4
public:
    virtual ~HttpFileService() ;
protected:
    HttpFileService(struct MHD_Connection *conn) : HttpService(conn) {}
};
</code>```

I encounter the following linking error:

```<code>Undefined symbols for architecture x86_64:
  "vtable for HttpService", referenced from:
      HttpService::~HttpService()in httpservice.o
</code>```

Changing HttpService's constructor to the following doesn't help either

```<code>explicit HttpService(QObject *parent = 0) : QObject(parent)
</code>```

答: Force running qmake and see if it works.</p>

Body:
Following is the code that works fine

class HttpService {
public:
    virtual ~HttpService(); // implemented in .cpp
protected:
    HttpService(struct MHD_Connection *conn) {}
};
class HttpFileService : public HttpService
{
public:
    virtual ~HttpFileService() ; // implemented in .cpp
protected:
    HttpFileService(struct MHD_Connection *conn) : HttpService(conn) {}
};

Now, when I make HttpService a derived class of QObject, like below:

#include <QObject>                      // change #1
class HttpService  : public QObject {   // change #2
    Q_OBJECT                            // change #3
public:
    virtual ~HttpService();
protected:
    HttpService(struct MHD_Connection *conn) {}
};

class HttpFileService : public HttpService {
    Q_OBJECT                            // change #4
public:
    virtual ~HttpFileService() ;
protected:
    HttpFileService(struct MHD_Connection *conn) : HttpService(conn) {}
};

I encounter the following linking error:

Undefined symbols for architecture x86_64:
  "vtable for HttpService", referenced from:
      HttpService::~HttpService()in httpservice.o

Changing HttpService's constructor to the following doesn't help either

explicit HttpService(QObject *parent = 0) : QObject(parent)


问:
How to correctly show the last nested Child data from multiple json(books) in new SwiftUI while using Disclosure group/ Outline group?
Struct that i'm using:

import SwiftUI

struct lvl4: View {
    //    @State var book: Book = Book()
    @State var books: [BookModel] = []
    @State var selection: BookModel?

    //ios 14 must to get the syntex right..
    @available(iOS 14, *)
    var body: some View {

        NavigationView {

            List(books) { book in
                ForEach(book.bookContent ?? []) { bookContent in
                    Section(header: Text(bookContent.title).font(.largeTitle) .fontWeight(.heavy)) {
                        OutlineGroup(bookContent.child, children: \.child) { item in
                            if #available(iOS 15, *) {

                                Text(attributedString(from: item.title, font: Font.system(size: 20)))

                                    .navigationBarTitle(book.bukTitle!)

                            }
                        }
                    }
                }
            }

        }

        .navigationBarTitleDisplayMode(.inline)
        .navigationViewStyle(StackNavigationViewStyle())
        //

        .listStyle(SidebarListStyle())
        //        .navigationViewStyle(.stack)
        .onAppear {
            //loadData()
        }
    }

    {

}

struct Buk: Identifiable, Codable {
    let id = UUID()
    var bukTitle: String = ""
    var isLive: Bool = false
    var userCanCopy: Bool = false
    var bookContent: [BookContent] = []

    enum CodingKeys: String, CodingKey {
        case bukTitle = "book_title"
        case isLive = "is_live"
        case userCanCopy = "user_can_copy"
        case bookContent = "book_content"
    }
}
struct BookContent: Identifiable, Codable {
    let id = UUID()
    var type,title:String
    var child: [Child]

}

struct Child: Identifiable, Codable {
    let id = UUID()
    var type,title:String
    var child: [Child]?

}

@available(iOS 15, *)
func attributedString(from str: String, font: Font) -> AttributedString {
    if let theData = str.data(using: .utf16) {
        do {
            let theString = try NSAttributedString(data: theData, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
            var attaString = AttributedString(theString)
            attaString.font = font
            return attaString
        } catch {
            print("\(error)")
        }
    }
    return AttributedString(str)
}

struct lvl4_Previews: PreviewProvider {
    static var previews: some View {
        lvl4()
    }
}```
</div>
</div>
</p>
<p><strong>Current Situation:</strong></p>
<p>There is a list of all the locally stored books(json files) that are being shown on same V-stack. Those books are fetched from local directory.  Now, when the user presses on drop down of disclosure group/outline group. "Struct"( which is lvl4()) that was made to parse the json show the nested json data.</p>
<p>The current data looks like following by implementing <strong>Outline group/ disclosure group</strong>.</p>
<p><img src="https://i.stack.imgur.com/43f0X.png" alt="Show this data on new view" /></p>
<p><strong>My Attempt</strong> ::</p>
<p>Showed books on same view where all the books are listed. but unable to show the last description child from json on another view.
Following is my Code that i tried using Disclosure group. The outline group used in disclosure group uses children: .child which helps to make the nested data look on the view. The last nested data is shown until the coding keys of json's  is "child": null
until here:</p>
<p>small part of one of that json data(hundreds of similar nested data in same line):</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>[
  {
    "book_title": "સત્સંગિજીવન સાગર મંથન",
    "is_live": false,
    "user_can_copy": true,
    "book_content": [
      {
        "title": "સત્સંગિજીવન માહાત્મ્ય",
        "type": "title",
        "child": [
          {
            "title": "૦૧. પૂર્વભૂમિકા",
            "type": "title",
            "child": [
              {
                "title": "૦૧. મંગલાચરણ",
                "type": "title",
                "child": [
                  {
                    "title": "<p>સતતં નિજમૂર્તિ ચિન્તકાનામ્, અધિક શ્વેત મનોહર પ્રકાશે ।<br />હૃદિ દર્શિત રમ્ય દિવ્યરૂપં, ભગવન્તં તમહં હરિં નમામિ ।।</p><h3 style='text-align: center;'><strong>( </strong><strong>અર્થ</strong><strong> )</strong></h3><p style='text-align: justify;'>      “હંમેશાં પોતાની મૂર્તિનું ચિંતન કરનારા, ભક્તજનોના હૃદય કમળમાં જણાતા અત્યંત શ્વેત મનોહર પ્રકાશવાળા, અક્ષર બ્રહ્મમાં જેમણે બતાવ્યું છે દિવ્યરૂપ એવા ભગવાન શ્રીહરિને હું નમસ્કાર કરું છું.”</p><p style='text-align: justify;'>      અનંતકોટિ બ્રહ્માંડોના ઉત્પત્તિના કારણ તથા અનંત ઐશ્વર્ય યુક્ત એવા પૂર્ણપુરુષોત્તમ શ્રી સ્વામિનારાયણ મહાપ્રભુજી તથા આપણા (ઉદ્ધવ) સંપ્રદાયના આદ્ય સ્થાપક ઉદ્ધવાવતાર શ્રી રામાનંદસ્વામી તથા જેની શિષ્ય પરંપરાગતમાં મને શિષ્ય બનવાનો સુલભ અવસર પ્રાપ્ત થયો છે, જેઓને ખુદ સ્વામિનારાયણ ભગવાન ગુરુ તરીકે માનીને મર્યાદા રાખતા અને જેઓને સત્સંગની 'મા' તરીકેનું બિરુદ આપી શ્રીહરિજીએ બહુમાન કર્યું હતું, એવા સર્વગુણે સંપન્ન મારા આદિ ગુરુ સદ્ગુરુ શ્રી મુક્તાનંદ સ્વામી તથા મૂળ અક્ષરમૂર્તિ યોગીરાજ સદ્ગુરુ ગોપાળાનંદ સ્વામી તથા જેઓને ખુદ શ્રીજી મહારાજે પોતાને સ્થાને બેસાડી સંપ્રદાયની ધુરા સોંપી આચાર્યપદ અર્પણ કર્યું છે એવા, સંતોનો અપાર મહિમા સમજનારા અને ગૃહસ્થાશ્રમમાં હોવા છતાં નિષ્કામી વ્રતને ધારણ કરનાર એવા પ. પૂ. ધ. ધુ. ૧૦૦૮ આચાર્ય શ્રી રઘુવીરજી મહારાજ તથા ધ્યાનના અંગવાળા અને આત્મનિષ્ઠાને સાંગોપાંગ જીવનમાં ઉતારનારા પ.પૂ.ધ.ધુ.૧૦૦૮ આચાર્યશ્રી અયોધ્યાપ્રસાદજી મહારાજ તથા સર્વે મહાન સંતો અને મહાન ભક્તોના ચરણોમાં વંદના કરી 'ગ્રંથરાજ શ્રીમદ્ સત્સંગિજીવન' માંથી મારી અલ્પમતિ અનુસાર મંથન કરી સાર રૂપ ઘી શોધવા માટે જઇ રહ્યો છું.</p>",
                    "type": "content",
                    "child": null
                  }
                ]
              }
            ]
          }
        ]
      }
    ]
  }
]</code>```

The current data looks like following by implementing Disclosure group.

Following code used::

import SwiftUI
import Foundation

struct ContentView: View {

    @EnvironmentObject var booksList:BooksList
    @State var books: [BookModel] = []
    @State var selection: BookModel?

    var body: some View {

//        NavigationView {

            VStack{
                List(booksList.books) { book in

//                        NavigationLink(destination: lvl4(books: [book], selection: nil)){
//                                               Text(book.bukTitle!)
//

                    if #available(iOS 15.0, *) {
                        DisclosureGroup ("\(Text(book.bukTitle!) .fontWeight(.medium) .font(.system(size: 27)))"){
                            ForEach(book.bookContent ?? []) { bookContent in
                                DisclosureGroup("\(Text(bookContent.title).fontWeight(.light) .font(.system(size: 25)))")
                                {
                                    OutlineGroup(bookContent.child  , children: \.child) { item in
                                         if #available(iOS 15, *) {

                                             Text(attributedString(from: item.title, font: Font.system(size: 23) ))
                                                 .navigationTitle(Text(bookContent.title))

//                                             if (([Child].self as? NSNull) == nil)  {

//                                                     NavigationLink(destination: ScrollView {Text(attributedString(from: item.title, font: Font.system(size: 25) )).padding(30) .lineSpacing(10) .navigationTitle(Text(bookContent.title)) .navigationBarTitleDisplayMode(.inline)
//
//                                                        })
//                                                        {
//
//    //                                                        EmptyView()
//        //                                                    .navigationTitle(Text(bookContent.title))
//                                                        }

//                                                    }

                                         }

                                       }
                                     }
                            }

                        }
                    } else {
                        // Fallback on earlier versions
                    }

//                }

            }

        }

    }

//
//                    DisclosureGroup("\(Text(book.bukTitle!).fontWeight(.light) .font(.system(size: 23)))"){
//
//                        ForEach(book.bookContent ?? []) { bookContent in
//
//                            DisclosureGroup("\(Text(bookContent.title))" ){
//
//                                OutlineGroup(bookContent.child, children: \.child) { chld in
//
//
//                                    List(bookContent.child, children: \.child)
//                                    {
//                                      OutlineGroup(bookContent.child, children: \.child) { item in
//                                            if #available(iOS 15, *) {
//
//                                                NavigationLink(destination: ScrollView{Text(attributedString(from: item.title, font: Font.system(size: 22) )).padding(30) .lineSpacing(10) .navigationTitle(Text(bookContent.title)) .navigationBarTitleDisplayMode(.inline)}){
//                                                    EmptyView()
//
//                                                }
//                                            }
//                                        }
//                                    }
//                            }
//                        }
//                    }
//                }
//            }
//        }
//    }
//}

@available(iOS 13.0.0, *)
struct ContentView_Previews: PreviewProvider {
    @available(iOS 13.0.0, *)
    static var previews: some View {
        ContentView()
    }
}
}```
</div>
</div>
</p>
<p><strong>struct Child is inside struct lvl4 which is given above in first code.</strong></p>
<p><strong>BookModel code is following::</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import Foundation

enum BookParseError: Error {
    case bookParsingFailed
}

struct BookModelForJSONConversion: Codable {
    var id:Int
    var title: String?
    var content: [BookContent]?

    func convertToJsonString()->String?{
        let jsonEncoder = JSONEncoder()
        jsonEncoder.outputFormatting = .prettyPrinted
        var encodedString:String?
        do {
            let encodePerson = try jsonEncoder.encode(self)
            let endcodeStringPerson = String(data: encodePerson, encoding: .utf8)!
            //print(endcodeStringPerson)
            encodedString = endcodeStringPerson
        } catch {
            print(error.localizedDescription)
            return nil
        }
        return encodedString
    }
}

struct BookModel: Identifiable, Codable {
    var id:Int
    var bukTitle: String?
    var isLive: Bool?
    var userCanCopy: Bool?
    var bookContent: [BookContent]?

    enum CodingKeys: String, CodingKey {
        case id = "id"
        case bukTitle = "title"
        case isLive = "is_live"
        case userCanCopy = "user_can_copy"
        case bookContent = "content"
    }
}

//struct BookContent: Identifiable, Codable {
//    let id = UUID()
//    var title, type: String
//    var child: [Child]
//}
//
//struct Child: Identifiable, Codable {
//    let id = UUID()
//    var title, type: String
//    var child: [Child]?
//}

enum BooksDirectory {
    /// Default, system Documents directory, for persisting media files for upload.
    case downloads

    /// Returns the directory URL for the directory type.
    ///
    fileprivate var url: URL {
        let fileManager = FileManager.default
        // Get a parent directory, based on the type.
        let parentDirectory: URL
        switch self {
        case .downloads:
            parentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
        }
        return parentDirectory.appendingPathComponent(VBBooksManager.booksDirectoryName, isDirectory: true)
    }
}

class VBBooksManager:NSObject {
    fileprivate static let booksDirectoryName = "books"

    let directory: BooksDirectory

    @objc (defaultManager)
    static let `default`: VBBooksManager = {
        return VBBooksManager()
    }()

    // MARK: - Init
    /// Init with default directory of .uploads.
    ///
    /// - Note: This is particularly because the original Media directory was in the NSFileManager's documents directory.
    ///   We shouldn't change this default directory lightly as older versions of the app may rely on Media files being in
    ///   the documents directory for upload.
    ///
    init(directory: BooksDirectory = .downloads) {
        self.directory = directory
    }

    // MARK: - Instance methods
    /// Returns filesystem URL for the local Media directory.
    ///
    @objc func directoryURL() throws -> URL {
        let fileManager = FileManager.default
        let mediaDirectory = directory.url
        // Check whether or not the file path exists for the Media directory.
        // If the filepath does not exist, or if the filepath does exist but it is not a directory, try creating the directory.
        // Note: This way, if unexpectedly a file exists but it is not a dir, an error will throw when trying to create the dir.
        var isDirectory: ObjCBool = false
        if fileManager.fileExists(atPath: mediaDirectory.path, isDirectory: &isDirectory) == false || isDirectory.boolValue == false {
            try fileManager.createDirectory(at: mediaDirectory, withIntermediateDirectories: true, attributes: nil)
        }
        return mediaDirectory
    }

    func saveBook(bookName:String,bookData:String)->Error?{
        //TODO: Save book into Document directory

        do {
            var finalBookName = bookName
            if !finalBookName.contains(".json"){
                finalBookName = "\(bookName).json"
            }

            let bookPath = try? self.directoryURL().appendingPathComponent(finalBookName)
            print(bookPath?.relativePath)

            do {
                let fileManager = FileManager.default
                if fileManager.fileExists(atPath: bookPath!.relativePath){
                    try fileManager.removeItem(at: bookPath!)
                }
                let data = Data(bookData.utf8)
                try? data.write(to: bookPath!, options: .atomic)
                //Just for Testing purpose call load book
                //lodBook(bookName: finalBookName)
            }
            catch let error as NSError {
                print(error)
                return error
            }

        }
        catch let error as NSError{
            print(error)
            return error
        }

        return nil

        //fileManager.wri wr(bookPath.relativePath, contents: Data(bookData), attributes: nil)
    }

    //https://stackoverflow.com/questions/39415249/best-practice-for-swift-methods-that-can-return-or-error
    func loadBookFromDocumentDirectory(bookName:String) throws -> BookModel? {
        let fileManager = FileManager.default
        do {
            var finalBookName = bookName
            if !finalBookName.contains(".json"){
                finalBookName = "\(bookName).json"
            }
            let bookPath = try? self.directoryURL().appendingPathComponent(finalBookName)
            print(bookPath?.relativePath)

            do {
                if fileManager.fileExists(atPath: bookPath!.relativePath){
                    let jsonBookString = fileManager.contents(atPath: bookPath!.relativePath)
                    do {
                        let data = try Data(jsonBookString!)
                        guard let parsedBookObject:BookModel? = try JSONDecoder().decode(BookModel.self, from: data) else {
                            throw BookParseError.bookParsingFailed
                        }
                        return parsedBookObject ?? nil
                        //print(parsedBookObject)
                    }
                    catch let error as NSError{
                        print("error: \(error)")
                        throw error
                    }

                }else{

                }
            }
            catch let error as NSError {
                print(error)
                throw error
            }

        }
        catch let error as NSError{
            print(error)
            throw error
        }
        return nil
    }

    func loadAllSavedBooks()->[BookModel]?{
        var allBooks:[BookModel] = []
        let fileManager = FileManager.default
        guard let booksPath = try? self.directoryURL() else {
            return []
        }
        print(booksPath)

        do {
            // Get the directory contents urls (including subfolders urls)
            let directoryContents = try fileManager.contentsOfDirectory(at: booksPath, includingPropertiesForKeys: nil)
            print(directoryContents)

            // if you want to filter the directory contents you can do like this:
            let books = directoryContents.filter{ $0.pathExtension == "json" }
            let bookNames = books.map{ $0.deletingPathExtension().lastPathComponent }
            print("bookNames list:", bookNames)
            //TODO: Load all the books and send array back

            for bookName in bookNames {
                do {
                    let book = try loadBookFromDocumentDirectory(bookName:bookName)
                    allBooks.append(book!)
                } catch BookParseError.bookParsingFailed {
                    continue
                }

            }
            return allBooks

        } catch let error as NSError {
            print(error)
        }

        return allBooks
    }

}</code>```

Issues::

Issue 1:
If i try to use Navigation link (which is commented out) then it'll show Navigation Links in all the Childs of the Disclosure group instead of only the last child where the last child is obtained( "child": null).

答:
This took some time to parse through. With the next question, please pull everything out of your code that is not necessary to the question, so it is easier to understand.

With you model, the first mistake you made was making everything optional. That gives you a level of complexity that is unnecessary. Your big concern was dealing with the arrays of Child, but you only have to deal with them if the arrays are not empty. If you make them optional, you are stuck having to unwrap them to then see if they are empty or not. That is unnecessary.

Also, as far as the data model goes, a BookContent == Child. There is absolutely no reason to have both, so I dropped Child.

Remodel the JSON so that every node has a value, even if it is simply an empty array or "" string. Since you control the JSON, keep it simple.

As you can see, I have rendered the views of each BookContent recursively, since every BookContent has an [BookContent]. If the [BookContent] is empty, the recursion ends.

Your Views:

```<code>struct ContentView: View {

    @State var booksList: [BookModel] = [
        BookModel(id: 1, bukTitle: "Book Title", isLive: false, userCanCopy: false, bookContent: [
            BookContent(title: "Content Title", type: "", children: [
                BookContent(title: "2nd Level Book Content", type: "", children: [
                    BookContent(title: "3rd Level Book Content", type: "", children: [
                        BookContent(title: "4th Level Book Content", type: "", children: [])
                    ])
                ])
            ])
        ])]

    var body: some View {
        NavigationView {
            VStack{
                List(booksList) { book in
                    Text(book.bukTitle)
                    ForEach(book.bookContent) { bookContent in
                        BookContentView(bookContent: bookContent)
                    }
                }
            }
        }
    }
}

struct BookContentView: View {

    let bookContent: BookContent

    var body: some View {
        Text(bookContent.title)
        ForEach(bookContent.children) { bookContent in
            BookContentView(bookContent: bookContent)
        }
    }
}
</code>```

Your Models:

```<code>struct BookModel: Identifiable, Codable {
    var id:Int
    var bukTitle: String
    var isLive: Bool
    var userCanCopy: Bool
    var bookContent: [BookContent]

    enum CodingKeys: String, CodingKey {
        case id = "id"
        case bukTitle = "title"
        case isLive = "is_live"
        case userCanCopy = "user_can_copy"
        case bookContent = "content"
    }
}

struct BookContent: Identifiable, Codable {
    let id = UUID()
    var title, type: String
    var children: [BookContent]

    // Since your id is a let constant, adding CodingKeys without id
    // silences the Codable warning that id won't be coded.
    enum CodingKeys: String, CodingKey {
        case title = "title"
        case type = "type"
        case children = "child"
    }
}
</code>```

Play with this code in a separate app, then work your way back through yours, integrating it as needed.

Body:
Struct that i'm using:

import SwiftUI

struct lvl4: View {
    //    @State var book: Book = Book()
    @State var books: [BookModel] = []
    @State var selection: BookModel?

    //ios 14 must to get the syntex right..
    @available(iOS 14, *)
    var body: some View {

        NavigationView {

            List(books) { book in
                ForEach(book.bookContent ?? []) { bookContent in
                    Section(header: Text(bookContent.title).font(.largeTitle) .fontWeight(.heavy)) {
                        OutlineGroup(bookContent.child, children: \.child) { item in
                            if #available(iOS 15, *) {

                                Text(attributedString(from: item.title, font: Font.system(size: 20)))

                                    .navigationBarTitle(book.bukTitle!)

                            }
                        }
                    }
                }
            }

        }

        .navigationBarTitleDisplayMode(.inline)
        .navigationViewStyle(StackNavigationViewStyle())
        //

        .listStyle(SidebarListStyle())
        //        .navigationViewStyle(.stack)
        .onAppear {
            //loadData()
        }
    }

    {

}

struct Buk: Identifiable, Codable {
    let id = UUID()
    var bukTitle: String = ""
    var isLive: Bool = false
    var userCanCopy: Bool = false
    var bookContent: [BookContent] = []

    enum CodingKeys: String, CodingKey {
        case bukTitle = "book_title"
        case isLive = "is_live"
        case userCanCopy = "user_can_copy"
        case bookContent = "book_content"
    }
}
struct BookContent: Identifiable, Codable {
    let id = UUID()
    var type,title:String
    var child: [Child]

}

struct Child: Identifiable, Codable {
    let id = UUID()
    var type,title:String
    var child: [Child]?

}

@available(iOS 15, *)
func attributedString(from str: String, font: Font) -> AttributedString {
    if let theData = str.data(using: .utf16) {
        do {
            let theString = try NSAttributedString(data: theData, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
            var attaString = AttributedString(theString)
            attaString.font = font
            return attaString
        } catch {
            print("\(error)")
        }
    }
    return AttributedString(str)
}

struct lvl4_Previews: PreviewProvider {
    static var previews: some View {
        lvl4()
    }
}

Current Situation:

There is a list of all the locally stored books(json files) that are being shown on same V-stack. Those books are fetched from local directory.  Now, when the user presses on drop down of disclosure group/outline group. "Struct"( which is lvl4()) that was made to parse the json show the nested json data.

The current data looks like following by implementing Outline group/ disclosure group.

My Attempt ::

Showed books on same view where all the books are listed. but unable to show the last description child from json on another view.
Following is my Code that i tried using Disclosure group. The outline group used in disclosure group uses children: .child which helps to make the nested data look on the view. The last nested data is shown until the coding keys of json's  is "child": null
until here:

small part of one of that json data(hundreds of similar nested data in same line):

[
  {
    "book_title": "સત્સંગિજીવન સાગર મંથન",
    "is_live": false,
    "user_can_copy": true,
    "book_content": [
      {
        "title": "સત્સંગિજીવન માહાત્મ્ય",
        "type": "title",
        "child": [
          {
            "title": "૦૧. પૂર્વભૂમિકા",
            "type": "title",
            "child": [
              {
                "title": "૦૧. મંગલાચરણ",
                "type": "title",
                "child": [
                  {
                    "title": "
સતતં નિજમૂર્તિ ચિન્તકાનામ્, અધિક શ્વેત મનોહર પ્રકાશે ।
હૃદિ દર્શિત રમ્ય દિવ્યરૂપં, ભગવન્તં તમહં હરિં નમામિ ।।

( અર્થ )

      “હંમેશાં પોતાની મૂર્તિનું ચિંતન કરનારા, ભક્તજનોના હૃદય કમળમાં જણાતા અત્યંત શ્વેત મનોહર પ્રકાશવાળા, અક્ષર બ્રહ્મમાં જેમણે બતાવ્યું છે દિવ્યરૂપ એવા ભગવાન શ્રીહરિને હું નમસ્કાર કરું છું.”

      અનંતકોટિ બ્રહ્માંડોના ઉત્પત્તિના કારણ તથા અનંત ઐશ્વર્ય યુક્ત એવા પૂર્ણપુરુષોત્તમ શ્રી સ્વામિનારાયણ મહાપ્રભુજી તથા આપણા (ઉદ્ધવ) સંપ્રદાયના આદ્ય સ્થાપક ઉદ્ધવાવતાર શ્રી રામાનંદસ્વામી તથા જેની શિષ્ય પરંપરાગતમાં મને શિષ્ય બનવાનો સુલભ અવસર પ્રાપ્ત થયો છે, જેઓને ખુદ સ્વામિનારાયણ ભગવાન ગુરુ તરીકે માનીને મર્યાદા રાખતા અને જેઓને સત્સંગની 'મા' તરીકેનું બિરુદ આપી શ્રીહરિજીએ બહુમાન કર્યું હતું, એવા સર્વગુણે સંપન્ન મારા આદિ ગુરુ સદ્ગુરુ શ્રી મુક્તાનંદ સ્વામી તથા મૂળ અક્ષરમૂર્તિ યોગીરાજ સદ્ગુરુ ગોપાળાનંદ સ્વામી તથા જેઓને ખુદ શ્રીજી મહારાજે પોતાને સ્થાને બેસાડી સંપ્રદાયની ધુરા સોંપી આચાર્યપદ અર્પણ કર્યું છે એવા, સંતોનો અપાર મહિમા સમજનારા અને ગૃહસ્થાશ્રમમાં હોવા છતાં નિષ્કામી વ્રતને ધારણ કરનાર એવા પ. પૂ. ધ. ધુ. ૧૦૦૮ આચાર્ય શ્રી રઘુવીરજી મહારાજ તથા ધ્યાનના અંગવાળા અને આત્મનિષ્ઠાને સાંગોપાંગ જીવનમાં ઉતારનારા પ.પૂ.ધ.ધુ.૧૦૦૮ આચાર્યશ્રી અયોધ્યાપ્રસાદજી મહારાજ તથા સર્વે મહાન સંતો અને મહાન ભક્તોના ચરણોમાં વંદના કરી 'ગ્રંથરાજ શ્રીમદ્ સત્સંગિજીવન' માંથી મારી અલ્પમતિ અનુસાર મંથન કરી સાર રૂપ ઘી શોધવા માટે જઇ રહ્યો છું.
",
                    "type": "content",
                    "child": null
                  }
                ]
              }
            ]
          }
        ]
      }
    ]
  }
]

The current data looks like following by implementing Disclosure group.

Following code used::

import SwiftUI
import Foundation

struct ContentView: View {

    @EnvironmentObject var booksList:BooksList
    @State var books: [BookModel] = []
    @State var selection: BookModel?

    var body: some View {

//        NavigationView {

            VStack{
                List(booksList.books) { book in

//                        NavigationLink(destination: lvl4(books: [book], selection: nil)){
//                                               Text(book.bukTitle!)
//

                    if #available(iOS 15.0, *) {
                        DisclosureGroup ("\(Text(book.bukTitle!) .fontWeight(.medium) .font(.system(size: 27)))"){
                            ForEach(book.bookContent ?? []) { bookContent in
                                DisclosureGroup("\(Text(bookContent.title).fontWeight(.light) .font(.system(size: 25)))")
                                {
                                    OutlineGroup(bookContent.child  , children: \.child) { item in
                                         if #available(iOS 15, *) {

                                             Text(attributedString(from: item.title, font: Font.system(size: 23) ))
                                                 .navigationTitle(Text(bookContent.title))

//                                             if (([Child].self as? NSNull) == nil)  {

//                                                     NavigationLink(destination: ScrollView {Text(attributedString(from: item.title, font: Font.system(size: 25) )).padding(30) .lineSpacing(10) .navigationTitle(Text(bookContent.title)) .navigationBarTitleDisplayMode(.inline)
//
//                                                        })
//                                                        {
//
//    //                                                        EmptyView()
//        //                                                    .navigationTitle(Text(bookContent.title))
//                                                        }

//                                                    }

                                         }

                                       }
                                     }
                            }

                        }
                    } else {
                        // Fallback on earlier versions
                    }

//                }

            }

        }

    }

//
//                    DisclosureGroup("\(Text(book.bukTitle!).fontWeight(.light) .font(.system(size: 23)))"){
//
//                        ForEach(book.bookContent ?? []) { bookContent in
//
//                            DisclosureGroup("\(Text(bookContent.title))" ){
//
//                                OutlineGroup(bookContent.child, children: \.child) { chld in
//
//
//                                    List(bookContent.child, children: \.child)
//                                    {
//                                      OutlineGroup(bookContent.child, children: \.child) { item in
//                                            if #available(iOS 15, *) {
//
//                                                NavigationLink(destination: ScrollView{Text(attributedString(from: item.title, font: Font.system(size: 22) )).padding(30) .lineSpacing(10) .navigationTitle(Text(bookContent.title)) .navigationBarTitleDisplayMode(.inline)}){
//                                                    EmptyView()
//
//                                                }
//                                            }
//                                        }
//                                    }
//                            }
//                        }
//                    }
//                }
//            }
//        }
//    }
//}

@available(iOS 13.0.0, *)
struct ContentView_Previews: PreviewProvider {
    @available(iOS 13.0.0, *)
    static var previews: some View {
        ContentView()
    }
}
}

struct Child is inside struct lvl4 which is given above in first code.

BookModel code is following::

import Foundation

enum BookParseError: Error {
    case bookParsingFailed
}

struct BookModelForJSONConversion: Codable {
    var id:Int
    var title: String?
    var content: [BookContent]?

    func convertToJsonString()->String?{
        let jsonEncoder = JSONEncoder()
        jsonEncoder.outputFormatting = .prettyPrinted
        var encodedString:String?
        do {
            let encodePerson = try jsonEncoder.encode(self)
            let endcodeStringPerson = String(data: encodePerson, encoding: .utf8)!
            //print(endcodeStringPerson)
            encodedString = endcodeStringPerson
        } catch {
            print(error.localizedDescription)
            return nil
        }
        return encodedString
    }
}

struct BookModel: Identifiable, Codable {
    var id:Int
    var bukTitle: String?
    var isLive: Bool?
    var userCanCopy: Bool?
    var bookContent: [BookContent]?

    enum CodingKeys: String, CodingKey {
        case id = "id"
        case bukTitle = "title"
        case isLive = "is_live"
        case userCanCopy = "user_can_copy"
        case bookContent = "content"
    }
}

//struct BookContent: Identifiable, Codable {
//    let id = UUID()
//    var title, type: String
//    var child: [Child]
//}
//
//struct Child: Identifiable, Codable {
//    let id = UUID()
//    var title, type: String
//    var child: [Child]?
//}

enum BooksDirectory {
    /// Default, system Documents directory, for persisting media files for upload.
    case downloads

    /// Returns the directory URL for the directory type.
    ///
    fileprivate var url: URL {
        let fileManager = FileManager.default
        // Get a parent directory, based on the type.
        let parentDirectory: URL
        switch self {
        case .downloads:
            parentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
        }
        return parentDirectory.appendingPathComponent(VBBooksManager.booksDirectoryName, isDirectory: true)
    }
}

class VBBooksManager:NSObject {
    fileprivate static let booksDirectoryName = "books"

    let directory: BooksDirectory

    @objc (defaultManager)
    static let `default`: VBBooksManager = {
        return VBBooksManager()
    }()

    // MARK: - Init
    /// Init with default directory of .uploads.
    ///
    /// - Note: This is particularly because the original Media directory was in the NSFileManager's documents directory.
    ///   We shouldn't change this default directory lightly as older versions of the app may rely on Media files being in
    ///   the documents directory for upload.
    ///
    init(directory: BooksDirectory = .downloads) {
        self.directory = directory
    }

    // MARK: - Instance methods
    /// Returns filesystem URL for the local Media directory.
    ///
    @objc func directoryURL() throws -> URL {
        let fileManager = FileManager.default
        let mediaDirectory = directory.url
        // Check whether or not the file path exists for the Media directory.
        // If the filepath does not exist, or if the filepath does exist but it is not a directory, try creating the directory.
        // Note: This way, if unexpectedly a file exists but it is not a dir, an error will throw when trying to create the dir.
        var isDirectory: ObjCBool = false
        if fileManager.fileExists(atPath: mediaDirectory.path, isDirectory: &isDirectory) == false || isDirectory.boolValue == false {
            try fileManager.createDirectory(at: mediaDirectory, withIntermediateDirectories: true, attributes: nil)
        }
        return mediaDirectory
    }

    func saveBook(bookName:String,bookData:String)->Error?{
        //TODO: Save book into Document directory

        do {
            var finalBookName = bookName
            if !finalBookName.contains(".json"){
                finalBookName = "\(bookName).json"
            }

            let bookPath = try? self.directoryURL().appendingPathComponent(finalBookName)
            print(bookPath?.relativePath)

            do {
                let fileManager = FileManager.default
                if fileManager.fileExists(atPath: bookPath!.relativePath){
                    try fileManager.removeItem(at: bookPath!)
                }
                let data = Data(bookData.utf8)
                try? data.write(to: bookPath!, options: .atomic)
                //Just for Testing purpose call load book
                //lodBook(bookName: finalBookName)
            }
            catch let error as NSError {
                print(error)
                return error
            }

        }
        catch let error as NSError{
            print(error)
            return error
        }

        return nil

        //fileManager.wri wr(bookPath.relativePath, contents: Data(bookData), attributes: nil)
    }

    //https://stackoverflow.com/questions/39415249/best-practice-for-swift-methods-that-can-return-or-error
    func loadBookFromDocumentDirectory(bookName:String) throws -> BookModel? {
        let fileManager = FileManager.default
        do {
            var finalBookName = bookName
            if !finalBookName.contains(".json"){
                finalBookName = "\(bookName).json"
            }
            let bookPath = try? self.directoryURL().appendingPathComponent(finalBookName)
            print(bookPath?.relativePath)

            do {
                if fileManager.fileExists(atPath: bookPath!.relativePath){
                    let jsonBookString = fileManager.contents(atPath: bookPath!.relativePath)
                    do {
                        let data = try Data(jsonBookString!)
                        guard let parsedBookObject:BookModel? = try JSONDecoder().decode(BookModel.self, from: data) else {
                            throw BookParseError.bookParsingFailed
                        }
                        return parsedBookObject ?? nil
                        //print(parsedBookObject)
                    }
                    catch let error as NSError{
                        print("error: \(error)")
                        throw error
                    }

                }else{

                }
            }
            catch let error as NSError {
                print(error)
                throw error
            }

        }
        catch let error as NSError{
            print(error)
            throw error
        }
        return nil
    }

    func loadAllSavedBooks()->[BookModel]?{
        var allBooks:[BookModel] = []
        let fileManager = FileManager.default
        guard let booksPath = try? self.directoryURL() else {
            return []
        }
        print(booksPath)

        do {
            // Get the directory contents urls (including subfolders urls)
            let directoryContents = try fileManager.contentsOfDirectory(at: booksPath, includingPropertiesForKeys: nil)
            print(directoryContents)

            // if you want to filter the directory contents you can do like this:
            let books = directoryContents.filter{ $0.pathExtension == "json" }
            let bookNames = books.map{ $0.deletingPathExtension().lastPathComponent }
            print("bookNames list:", bookNames)
            //TODO: Load all the books and send array back

            for bookName in bookNames {
                do {
                    let book = try loadBookFromDocumentDirectory(bookName:bookName)
                    allBooks.append(book!)
                } catch BookParseError.bookParsingFailed {
                    continue
                }

            }
            return allBooks

        } catch let error as NSError {
            print(error)
        }

        return allBooks
    }

}

Issues::

Issue 1:
If i try to use Navigation link (which is commented out) then it'll show Navigation Links in all the Childs of the Disclosure group instead of only the last child where the last child is obtained( "child": null).

Body:
This took some time to parse through. With the next question, please pull everything out of your code that is not necessary to the question, so it is easier to understand.

With you model, the first mistake you made was making everything optional. That gives you a level of complexity that is unnecessary. Your big concern was dealing with the arrays of Child, but you only have to deal with them if the arrays are not empty. If you make them optional, you are stuck having to unwrap them to then see if they are empty or not. That is unnecessary.

Also, as far as the data model goes, a BookContent == Child. There is absolutely no reason to have both, so I dropped Child.

Remodel the JSON so that every node has a value, even if it is simply an empty array or "" string. Since you control the JSON, keep it simple.

As you can see, I have rendered the views of each BookContent recursively, since every BookContent has an [BookContent]. If the [BookContent] is empty, the recursion ends.

Your Views:

struct ContentView: View {

    @State var booksList: [BookModel] = [
        BookModel(id: 1, bukTitle: "Book Title", isLive: false, userCanCopy: false, bookContent: [
            BookContent(title: "Content Title", type: "", children: [
                BookContent(title: "2nd Level Book Content", type: "", children: [
                    BookContent(title: "3rd Level Book Content", type: "", children: [
                        BookContent(title: "4th Level Book Content", type: "", children: [])
                    ])
                ])
            ])
        ])]

    var body: some View {
        NavigationView {
            VStack{
                List(booksList) { book in
                    Text(book.bukTitle)
                    ForEach(book.bookContent) { bookContent in
                        BookContentView(bookContent: bookContent)
                    }
                }
            }
        }
    }
}

struct BookContentView: View {

    let bookContent: BookContent

    var body: some View {
        Text(bookContent.title)
        ForEach(bookContent.children) { bookContent in
            BookContentView(bookContent: bookContent)
        }
    }
}

Your Models:

struct BookModel: Identifiable, Codable {
    var id:Int
    var bukTitle: String
    var isLive: Bool
    var userCanCopy: Bool
    var bookContent: [BookContent]

    enum CodingKeys: String, CodingKey {
        case id = "id"
        case bukTitle = "title"
        case isLive = "is_live"
        case userCanCopy = "user_can_copy"
        case bookContent = "content"
    }
}

struct BookContent: Identifiable, Codable {
    let id = UUID()
    var title, type: String
    var children: [BookContent]

    // Since your id is a let constant, adding CodingKeys without id
    // silences the Codable warning that id won't be coded.
    enum CodingKeys: String, CodingKey {
        case title = "title"
        case type = "type"
        case children = "child"
    }
}

Play with this code in a separate app, then work your way back through yours, integrating it as needed.


问:
Making an array equal by decreasing elements adjacent to each other
I was doing this exercise in my computer science class for a warm up earlier, which was to find the minimum number of moves to make all the elements in an array equal to each other, where the only operation is to subtract one from an element in an array.

This made me curious about extensions to the problem; for example I immediately thought of an extension, how many moves will it take to make all the elements in an array equal to each other, where the only operation is to subtract one from two elements that are adjacent to each other.

For example:
Given array [4, 6, 4], we can decrease elements in index 0 and 1 to get [3, 5, 4], then [3, 4, 3], then [2, 3, 3], and then decrease elements in index 1 and 2 to get [2, 2, 2]. This would take 4 moves. However, how would we extend this kind of thinking to larger arrays, where we cannot trace this out by hand like I just did above?

答:
You can find whether this is possible (and minimum number of moves) in O(n) time, in a way that should generalize to larger array decreases.

The first step is to convert our array A to the first-difference array D, whose elements are D = [A[1]-A[0], A[2]-A[1], ..., A[n-1]-A[n-2]]. We are done when D is the all-zero array. Now, think about how the operations on A translate to changes in D. It's different when n is even and odd, too, so focus on one case at a time.

Odd length

When A has odd length, there are more cases where no solution is possible.
Suppose 'A' has 7 elements. There's 6 possible moves, so let's calculate what effect each has on D.

```<code>A = [a_0,    a_1,    a_2,    a_3,    a_4,    a_5,    a_6]
D =     [d_0,    d_1,    d_2,    d_3,    d_4,    d_5]

Moves available:
d_1 += 1
(d_0 -= 1, d_2 += 1)
(d_1 -= 1, d_3 += 1)
(d_2 -= 1, d_4 += 1)
(d_3 -= 1, d_5 += 1)
d_4 -= 1
</code>```

Some observations:

The interactions between even and odd indices of D are completely disjoint (this is true for the even-length case too).

d_5 can only increase, d_0 can only decrease.

I found it helpful to think of this as a 'flow' from left to right in D:

```<code>d_0 --> d_2 --> d_4 --> SINK

SOURCE --> d_1 --> d_3 --> d_5
</code>```

this makes things easier: there's only one way to try to make D all zero, so we can just try that.

If D[0] is negative, this is impossible. If it's positive, add D[0] moves to our counter, and add D[0] to D[2]

If D[2] is negative, this is impossible. If it's positive, add D[2] moves to our counter, and add D[2] to D[4]

If D[4] is negative, this is impossible. Otherwise, add D[4] to our counter. D[4] points to a sink, so we are done.

I haven't explained the process for the odd vertices, but it's the same logic-- there's at most one way to make D all zero, following the flow.

Even-length

The even-length array case is similar, except the flow-network has different endpoints.

```<code>A = [a_0,    a_1,    a_2,    a_3,    a_4,    a_5,    a_6,    a_7]
D =     [d_0,    d_1,    d_2,    d_3,    d_4,    d_5,    d_6]

Moves available:
d_1 += 1
(d_0 -= 1, d_2 += 1)
(d_1 -= 1, d_3 += 1)
(d_2 -= 1, d_4 += 1)
(d_3 -= 1, d_5 += 1)
(d_4 -= 1, d_6 += 1)
d_5 -= 1

d_0 --> d_2 --> d_4 --> d_6

SOURCE --> d_1 --> d_3 --> d_5 --> SINK
</code>```

This means that the odd-indices can have any values without changing the solvability, while the even indices must become all zero with only positive transfers from left to right. Positive flow still moves in exactly one direction in both cases.

I've written a Python solution implementing the logic above. There's one caveat-- I haven't been able to rigorously test it against random input. There's no obviously correct brute-force solution to this problem, so there may be failing testcases that I missed.

def min_decreases_to_get_equal(nums: List[int]) -> Optional[int]:
    """Given an array of integers, returns the number of moves
    to make all elements equal, or None if impossible.
    A move is selecting two adjacent elements and dec. both by 1."""

    n = len(nums)
    assert n >= 2
    if n == 2:
        return 0 if nums[0] == nums[1] else None
    differences = [nums[i] - nums[i - 1] for i in range(1, n)]
    evens = differences[0::2]
    odds = differences[1::2]

    if n % 2 == 0:  # Even length case

        total_cost = 0
        m1 = len(evens)
        for i, x in enumerate(evens):
            if x < 0:
                return None
            elif x > 0:
                # Last element can't be decreased
                if i == m1 - 1:
                    return None

                total_cost += abs(x)
                evens[i + 1] += abs(x)

        m2 = len(odds)
        for i, x in enumerate(odds):
            if x < 0:
                total_cost += abs(x) * (i + 1)
            elif x > 0:
                total_cost += abs(x)
                if i < m2 - 1:
                    odds[i + 1] += x
        return total_cost

    else:  # Odd length case
        total_cost = 0
        m1 = len(evens)
        for i, x in enumerate(evens):
            if x < 0:
                return None
            elif x > 0:
                if i < m1 - 1:
                    evens[i + 1] += abs(x)
                total_cost += abs(x)

        m2 = len(odds)
        for i in reversed(range(m2)):
            x = odds[i]
            if x < 0:
                if i != 0:
                    odds[i - 1] -= abs(x)
                total_cost += abs(x)

            elif x > 0:
                return None

        return total_cost
```
<p>Example tests:</p>
```[4, 6, 4] --> 4,
[3, 2, 3] --> None,
[0, 8, 8, 14, 8] --> 34,
[2, 5, 1, 6, 12, 11, 7, 0, 1, 1] --> 33
```

Body:
You can find whether this is possible (and minimum number of moves) in O(n) time, in a way that should generalize to larger array decreases.

The first step is to convert our array A to the first-difference array D, whose elements are D = [A[1]-A[0], A[2]-A[1], ..., A[n-1]-A[n-2]]. We are done when D is the all-zero array. Now, think about how the operations on A translate to changes in D. It's different when n is even and odd, too, so focus on one case at a time.

Odd length

When A has odd length, there are more cases where no solution is possible.
Suppose 'A' has 7 elements. There's 6 possible moves, so let's calculate what effect each has on D.

A = [a_0,    a_1,    a_2,    a_3,    a_4,    a_5,    a_6]
D =     [d_0,    d_1,    d_2,    d_3,    d_4,    d_5]

Moves available:
d_1 += 1
(d_0 -= 1, d_2 += 1)
(d_1 -= 1, d_3 += 1)
(d_2 -= 1, d_4 += 1)
(d_3 -= 1, d_5 += 1)
d_4 -= 1

Some observations:

The interactions between even and odd indices of D are completely disjoint (this is true for the even-length case too).

d_5 can only increase, d_0 can only decrease.

I found it helpful to think of this as a 'flow' from left to right in D:

d_0 --> d_2 --> d_4 --> SINK

SOURCE --> d_1 --> d_3 --> d_5

this makes things easier: there's only one way to try to make D all zero, so we can just try that.

If D[0] is negative, this is impossible. If it's positive, add D[0] moves to our counter, and add D[0] to D[2]

If D[2] is negative, this is impossible. If it's positive, add D[2] moves to our counter, and add D[2] to D[4]

If D[4] is negative, this is impossible. Otherwise, add D[4] to our counter. D[4] points to a sink, so we are done.

I haven't explained the process for the odd vertices, but it's the same logic-- there's at most one way to make D all zero, following the flow.

Even-length

The even-length array case is similar, except the flow-network has different endpoints.

A = [a_0,    a_1,    a_2,    a_3,    a_4,    a_5,    a_6,    a_7]
D =     [d_0,    d_1,    d_2,    d_3,    d_4,    d_5,    d_6]

Moves available:
d_1 += 1
(d_0 -= 1, d_2 += 1)
(d_1 -= 1, d_3 += 1)
(d_2 -= 1, d_4 += 1)
(d_3 -= 1, d_5 += 1)
(d_4 -= 1, d_6 += 1)
d_5 -= 1

d_0 --> d_2 --> d_4 --> d_6

SOURCE --> d_1 --> d_3 --> d_5 --> SINK

This means that the odd-indices can have any values without changing the solvability, while the even indices must become all zero with only positive transfers from left to right. Positive flow still moves in exactly one direction in both cases.

I've written a Python solution implementing the logic above. There's one caveat-- I haven't been able to rigorously test it against random input. There's no obviously correct brute-force solution to this problem, so there may be failing testcases that I missed.

def min_decreases_to_get_equal(nums: List[int]) -> Optional[int]:
    """Given an array of integers, returns the number of moves
    to make all elements equal, or None if impossible.
    A move is selecting two adjacent elements and dec. both by 1."""

    n = len(nums)
    assert n >= 2
    if n == 2:
        return 0 if nums[0] == nums[1] else None
    differences = [nums[i] - nums[i - 1] for i in range(1, n)]
    evens = differences[0::2]
    odds = differences[1::2]

    if n % 2 == 0:  # Even length case

        total_cost = 0
        m1 = len(evens)
        for i, x in enumerate(evens):
            if x < 0:
                return None
            elif x > 0:
                # Last element can't be decreased
                if i == m1 - 1:
                    return None

                total_cost += abs(x)
                evens[i + 1] += abs(x)

        m2 = len(odds)
        for i, x in enumerate(odds):
            if x < 0:
                total_cost += abs(x) * (i + 1)
            elif x > 0:
                total_cost += abs(x)
                if i < m2 - 1:
                    odds[i + 1] += x
        return total_cost

    else:  # Odd length case
        total_cost = 0
        m1 = len(evens)
        for i, x in enumerate(evens):
            if x < 0:
                return None
            elif x > 0:
                if i < m1 - 1:
                    evens[i + 1] += abs(x)
                total_cost += abs(x)

        m2 = len(odds)
        for i in reversed(range(m2)):
            x = odds[i]
            if x < 0:
                if i != 0:
                    odds[i - 1] -= abs(x)
                total_cost += abs(x)

            elif x > 0:
                return None

        return total_cost

Example tests:

[4, 6, 4] --> 4,
[3, 2, 3] --> None,
[0, 8, 8, 14, 8] --> 34,
[2, 5, 1, 6, 12, 11, 7, 0, 1, 1] --> 33


问:
Extract boost log attribute values of arbitrary type
There is a logging system with the number of attributes of arbitrary types. The attributes are added by external program(s) using public API (function template). The types aren't known beforehand. The typical way to print out an attribute's value looks like (simplified):

```<code>void print(logging::attribute_value const& attr)
{
    auto val = logging::extract<int>(attr);
    if (val) {
        std::cout << "value: " << val.get() << std::endl;
    }
}
</code>```

In the example above it's already known that the attribute value type is int. What if the expected type isn't known? Of cource, I could write it like:

```<code>typedef boost::mpl::vector<int, std::string> types; // Expected types
logging::value_ref<types> val = logging::extract<types>(attr);
[..]
</code>```

however in that case I have to define all possible types and handle them separately.

Is there a way to print out (or convert to strings) all values regardless of their types, assuming the types overload streaming operator?

UPDATE

Here are some more details:

```<code>// Add new attributes with arbitrary types
template<typename T>
void addProperty(const std::string &key, T && value)
{
    auto attrs = boost::log::core::get()->get_thread_attributes();
    attrs.erase(key);
    attrs.insert(key, boost::log::attributes::make_constant(std::move(value)));
    boost::log::core::get()->set_thread_attributes(attrs);
}
</code>```

and another function that should print the properties' values

```<code>void printProperties()
{
    const auto &attrs = boost::log::core::get()->get_thread_attributes();
    for (auto const &a : attrs) {
        // Print all values. Types aren't known.
    }
}
</code>```

答:
Of cource, I could write it like:

```<code>typedef boost::mpl::vector<int, std::string> types; // Expected types
logging::value_ref<types> val = logging::extract<types>(attr);
[..]
</code>```

however in that case I have to define all possible types and handle
them separately.

Yes, this was going to be my first suggestion: consider making the type a sum type (a bound variant, where you can visit all the bound types).

Is there a way to print out (or convert to strings) all values
regardless of their types, assuming the types overload streaming
operator?

The canonical alternative is to use type erasure. Mind you, it does still have overhead, but replaces static polymorphism with dynamic polymorphism under the hood¹.

Have a look e.g. at https://www.boost.org/doc/libs/1_78_0/doc/html/boost/type_erasure/ostreamable.html

¹ which compilers in very specific circumstances and with proper hinting can sometimes devirtualize back to static invocations, but I digress

Body:
There is a logging system with the number of attributes of arbitrary types. The attributes are added by external program(s) using public API (function template). The types aren't known beforehand. The typical way to print out an attribute's value looks like (simplified):

void print(logging::attribute_value const& attr)
{
    auto val = logging::extract<int>(attr);
    if (val) {
        std::cout << "value: " << val.get() << std::endl;
    }
}

In the example above it's already known that the attribute value type is int. What if the expected type isn't known? Of cource, I could write it like:

typedef boost::mpl::vector<int, std::string> types; // Expected types
logging::value_ref<types> val = logging::extract<types>(attr);
[..]

however in that case I have to define all possible types and handle them separately.

Is there a way to print out (or convert to strings) all values regardless of their types, assuming the types overload streaming operator?

UPDATE

Here are some more details:

// Add new attributes with arbitrary types
template<typename T>
void addProperty(const std::string &key, T && value)
{
    auto attrs = boost::log::core::get()->get_thread_attributes();
    attrs.erase(key);
    attrs.insert(key, boost::log::attributes::make_constant(std::move(value)));
    boost::log::core::get()->set_thread_attributes(attrs);
}

and another function that should print the properties' values

void printProperties()
{
    const auto &attrs = boost::log::core::get()->get_thread_attributes();
    for (auto const &a : attrs) {
        // Print all values. Types aren't known.
    }
}

Body:
Of cource, I could write it like:

typedef boost::mpl::vector<int, std::string> types; // Expected types
logging::value_ref<types> val = logging::extract<types>(attr);
[..]

however in that case I have to define all possible types and handle
them separately.

Yes, this was going to be my first suggestion: consider making the type a sum type (a bound variant, where you can visit all the bound types).

Is there a way to print out (or convert to strings) all values
regardless of their types, assuming the types overload streaming
operator?

The canonical alternative is to use type erasure. Mind you, it does still have overhead, but replaces static polymorphism with dynamic polymorphism under the hood¹.

Have a look e.g. at https://www.boost.org/doc/libs/1_78_0/doc/html/boost/type_erasure/ostreamable.html

¹ which compilers in very specific circumstances and with proper hinting can sometimes devirtualize back to static invocations, but I digress


问:
Can not get textfield value fetched from MySQL in javascript
I created a model in django like below.

```<code>class MyDB(models.Model):
    pub_date = models.DateTimeField(_("Date added"),editable=True, auto_now_add=False)
    title = models.CharField(max_length=256,blank=True,null=True)
    text = models.TextField(_("Text"))
</code>```

Then I got the model and mapped into Frontend.

in views.py file

```<code>context['mydb'] = MyDB.objects.all()
</code>```

in HTML file

```<code>let plots = [];
{% for d in mydb %}
    var id = '{{ d.id }}';
    var title = '{{ d.title }}';
    var text = '{{ d.text }}';
    console.log(text)

{% endfor %}
</code>```

When  the text contains 'enter' in string. it raise error.

答:
Please try to replace ' with ` (backtick), it should fix your issue
(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#multi-line_strings)</p>

Body:
I created a model in django like below.

class MyDB(models.Model):
    pub_date = models.DateTimeField(_("Date added"),editable=True, auto_now_add=False)
    title = models.CharField(max_length=256,blank=True,null=True)
    text = models.TextField(_("Text"))

Then I got the model and mapped into Frontend.

in views.py file

context['mydb'] = MyDB.objects.all()

in HTML file

let plots = [];
{% for d in mydb %}
    var id = '{{ d.id }}';
    var title = '{{ d.title }}';
    var text = '{{ d.text }}';
    console.log(text)

{% endfor %}

When  the text contains 'enter' in string. it raise error.


问:
Why do I get "No item route associated with the type" when using Api-Platform?
My project is built in Symfony 5 and API-Platform to consume it from a JS client. In this scenario, I have a Question entity related to an Answer entity (One-to-many respectively).

Whenever I try to call /api/questions or /api/answers I get this error: "No item route associated with the type "App\Entity\Answer":

In order to API resources this is what I have configured with maker bundle:

- App\Entity\Question:

/**
 * @ORM\Entity(repositoryClass=QuestionRepository::class)
 * @ApiResource
 * @ApiFilter(SearchFilter::class, properties={"status": "exact"})
 */
class Question
{
    // ...
    /**
     * @ORM\ManyToOne(targetEntity=User::class, inversedBy="questions")
     * @ORM\JoinColumn(nullable=false)
     */
    private $owner;

    // ...

    /**
     * @ORM\OneToMany(targetEntity=Answer::class, mappedBy="question", orphanRemoval=true)
     */
    private $answers;

    // ...

    /**
     * @return Collection|Answer[]
     */
    public function getAnswers(): Collection
    {
        return $this->answers;
    }

    public function addAnswer(Answer $answer): self
    {
        if (!$this->answers->contains($answer)) {
            $this->answers[] = $answer;
            $answer->setQuestion($this);
        }

        return $this;
    }

    public function removeAnswer(Answer $answer): self
    {
        if ($this->answers->contains($answer)) {
            $this->answers->removeElement($answer);
            // set the owning side to null (unless already changed)
            if ($answer->getQuestion() === $this) {
                $answer->setQuestion(null);
            }
        }

        return $this;
    }

    // ...
}
```
<h3>- <code>App\Entity\Answer</code>:</h3>
<pre class="lang-php prettyprint-override"><code>/**
 * @ORM\Entity(repositoryClass=AnswerRepository::class)
 * @ApiResource
 */
class Answer
{
    // ...

    /**
     * @ORM\ManyToOne(targetEntity=Question::class, inversedBy="answers")
     * @ORM\JoinColumn(nullable=false)
     * @Assert\NotBlank
     */
    private $question;

    // ...

    public function getQuestion(): ?Question
    {
        return $this->question;
    }

    public function setQuestion(?Question $question): self
    {
        $this->question = $question;

        return $this;
    }

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

Not sure if this is relevant to this issue: I configured config/api_platform/resources.yaml on api_platform.yaml:

App\Entity\Answer:
  attributes:
    security: 'is_granted("ROLE_USER")'
    security_message: 'Only the authenticated user can see answers'
  collectionOperations:
    get:
      security: 'is_granted("ROLE_USER")'
      security_message: 'Only the authenticated user can get answers'
    post:
      security: 'is_granted("ROLE_USER")'
      security_message: 'Only the authenticated user can save answers'
  itemOperations:
      put:
        security: 'is_granted("ROLE_ADMIN") or object.owner == user'
        security_message: 'Only the authenticated user or administrators can update answers'
      delete:
        security: 'is_granted("ROLE_ADMIN")'
        security_message: 'Only administrators can delete answers'

App\Entity\Question:
  attributes:
    security: 'is_granted("ROLE_USER")'
    security_message: 'Only the authenticated user can see questions'
  collectionOperations:
    get:
      security: 'is_granted("ROLE_ADMIN")'
      security_message: 'Only the authenticated user or administrators can get questions'
    post:
      security: 'is_granted("ROLE_USER")'
      security_message: 'Only the authenticated user can save questions'
  itemOperations:
      get:
        security: 'is_granted("ROLE_ADMIN") or object.owner == user'
        security_message: 'Only the authenticated user or administrators can get questions'
      put:
        security: 'is_granted("ROLE_ADMIN") or object.owner == user'
        security_message: 'Only the authenticated user or administrators can update questions'
      delete:
        security: 'is_granted("ROLE_ADMIN")'
        security_message: 'Only administrators can delete questions'
```
<p>The Swagger UI displays information about <code>Question</code> and <code>Answer</code> entity resources:</p>
<p><img src="https://i.imgur.com/7PIc7Dw.png" alt="" /></p>
<p>And this is what <code>debug:route</code> displays regarding <code>Answer</code>:</p>
```  api_answers_get_collection                      GET        ANY      ANY    /api/answers.{_format}
  api_answers_post_collection                     POST       ANY      ANY    /api/answers.{_format}
  api_answers_put_item                            PUT        ANY      ANY    /api/answers/{id}.{_format}
  api_answers_delete_item                         DELETE     ANY      ANY    /api/answers/{id}.{_format}
```

What is wrong here?

答:
This can be caused also when you have an Entity with the same name but that other one doesn't have an @ApiResource setup.

Like Answer in src/Entity/Answer and Answer in src/Entity/Questions/Answer

Body:
My project is built in Symfony 5 and API-Platform to consume it from a JS client. In this scenario, I have a Question entity related to an Answer entity (One-to-many respectively).

Whenever I try to call /api/questions or /api/answers I get this error: "No item route associated with the type "App\Entity\Answer":

In order to API resources this is what I have configured with maker bundle:

- App\Entity\Question:

/**
 * @ORM\Entity(repositoryClass=QuestionRepository::class)
 * @ApiResource
 * @ApiFilter(SearchFilter::class, properties={"status": "exact"})
 */
class Question
{
    // ...
    /**
     * @ORM\ManyToOne(targetEntity=User::class, inversedBy="questions")
     * @ORM\JoinColumn(nullable=false)
     */
    private $owner;

    // ...

    /**
     * @ORM\OneToMany(targetEntity=Answer::class, mappedBy="question", orphanRemoval=true)
     */
    private $answers;

    // ...

    /**
     * @return Collection|Answer[]
     */
    public function getAnswers(): Collection
    {
        return $this->answers;
    }

    public function addAnswer(Answer $answer): self
    {
        if (!$this->answers->contains($answer)) {
            $this->answers[] = $answer;
            $answer->setQuestion($this);
        }

        return $this;
    }

    public function removeAnswer(Answer $answer): self
    {
        if ($this->answers->contains($answer)) {
            $this->answers->removeElement($answer);
            // set the owning side to null (unless already changed)
            if ($answer->getQuestion() === $this) {
                $answer->setQuestion(null);
            }
        }

        return $this;
    }

    // ...
}

- App\Entity\Answer:

/**
 * @ORM\Entity(repositoryClass=AnswerRepository::class)
 * @ApiResource
 */
class Answer
{
    // ...

    /**
     * @ORM\ManyToOne(targetEntity=Question::class, inversedBy="answers")
     * @ORM\JoinColumn(nullable=false)
     * @Assert\NotBlank
     */
    private $question;

    // ...

    public function getQuestion(): ?Question
    {
        return $this->question;
    }

    public function setQuestion(?Question $question): self
    {
        $this->question = $question;

        return $this;
    }

    // ...
}

Not sure if this is relevant to this issue: I configured config/api_platform/resources.yaml on api_platform.yaml:

App\Entity\Answer:
  attributes:
    security: 'is_granted("ROLE_USER")'
    security_message: 'Only the authenticated user can see answers'
  collectionOperations:
    get:
      security: 'is_granted("ROLE_USER")'
      security_message: 'Only the authenticated user can get answers'
    post:
      security: 'is_granted("ROLE_USER")'
      security_message: 'Only the authenticated user can save answers'
  itemOperations:
      put:
        security: 'is_granted("ROLE_ADMIN") or object.owner == user'
        security_message: 'Only the authenticated user or administrators can update answers'
      delete:
        security: 'is_granted("ROLE_ADMIN")'
        security_message: 'Only administrators can delete answers'

App\Entity\Question:
  attributes:
    security: 'is_granted("ROLE_USER")'
    security_message: 'Only the authenticated user can see questions'
  collectionOperations:
    get:
      security: 'is_granted("ROLE_ADMIN")'
      security_message: 'Only the authenticated user or administrators can get questions'
    post:
      security: 'is_granted("ROLE_USER")'
      security_message: 'Only the authenticated user can save questions'
  itemOperations:
      get:
        security: 'is_granted("ROLE_ADMIN") or object.owner == user'
        security_message: 'Only the authenticated user or administrators can get questions'
      put:
        security: 'is_granted("ROLE_ADMIN") or object.owner == user'
        security_message: 'Only the authenticated user or administrators can update questions'
      delete:
        security: 'is_granted("ROLE_ADMIN")'
        security_message: 'Only administrators can delete questions'

The Swagger UI displays information about Question and Answer entity resources:

And this is what debug:route displays regarding Answer:

  api_answers_get_collection                      GET        ANY      ANY    /api/answers.{_format}
  api_answers_post_collection                     POST       ANY      ANY    /api/answers.{_format}
  api_answers_put_item                            PUT        ANY      ANY    /api/answers/{id}.{_format}
  api_answers_delete_item                         DELETE     ANY      ANY    /api/answers/{id}.{_format}

What is wrong here?


问:
How do I see the extensions loaded by PHP?
It's got to be somewhere in the phpinfo() dump, but I just don't know where.  Is it supposed to be under the "Additional Modules" section?  Somewhere else?  I'm trying to figure out why some extensions don't appear to be loaded, but I don't even know where I should be looking.</p>

答:
You can see all extensions install by PHP by this

-Debian/Ubuntu

```<code>dpkg --get-selections | grep -i php
</code>```

-RHEL/CentOS

```<code>yum list installed | grep -i php
</code>```

-Fedora 22+

```<code>dnf list installed | grep -i php
</code>```

OwnerDisplayName: Bialecki

ContentLicense: CC BY-SA 2.5

Body:
You can see all extensions install by PHP by this

-Debian/Ubuntu

dpkg --get-selections | grep -i php

-RHEL/CentOS

yum list installed | grep -i php

-Fedora 22+

dnf list installed | grep -i php


问:
Sending a specific SCSI command to a SCSI device in Mac OS X
Is it possible to do some Inquiry requests to SCSI driver?</p>

答:
The accepted answer is not entirely correct.

If the device is not a block disk device but, for instance, a tape drive, and therefore is not driven by a macOS driver by default, then one can talk to it using the functions available in <IOKit/scsi/SCSITaskLib.h>, from a userland application. See the "SCSITaskDeviceInterface" section in Apple's SCSI docs.


问:
Creating a plugin for Redmine in a language other than Ruby?
I've been searching for this but haven't found a definitive answer, which is: other than Ruby, can other languages be used to create plugins for Redmine?

If so, will that incurr any  workarounds and difficulties in general? Or will using them be as smooth as using Ruby?

I think of Golang primarily. And also of Elixir, Rust, Python.

答:
Redmine plugins must, well, plug into Redmine. Thus, they need to use internal Redmine APIs (written in and accessible with Ruby) to register its functions and embed into the application. Very often, plugins extend or overwrite parts of Redmine to implement their functionality. Plugins embed themselves into Redmine and run in the same processes to form an integrated program.

As such, you are required to use the same Ruby version as Redmine itself run at. While it may be theoretically possible to write your plugin in C (or compatible languages) and use Ruby's C interfaces, this would most certainly be MUCH more painful than just writing Ruby and would still mostly resemble the equivalent Ruby anyways.

If you want to develop external functionality in a different language, you can however access Redmine via its REST API from any external program using any language you like. It will not be a plugin though and will not extend Redmine itself.


问:
how to show n lines above and below my grep search?
I checked out the manifest file of k8s, but i want to also see the above n lines of my search.

```<code>   cat /etc/kubernetes/manifests/kube-apiserver.yaml | grep -i authorization -A4
        - --authorization-mode=Node,RBAC
        - --client-ca-file=/etc/kubernetes/pki/ca.crt
        - --enable-admission-plugins=NodeRestriction
        - --enable-bootstrap-token-auth=true
        - --etcd-cafile=/etc/kubernetes/pki/etcd/ca.crt
</code>```

how tod this?

答:
With -C you get the context around the match:

```<code>grep -C4 -i authorization /etc/kubernetes/manifests/kube-apiserver.yaml
</code>```

From grep man page:

```<code>   Context Line Control
       -A NUM, --after-context=NUM
              Print NUM lines of trailing context after matching lines.  Places a line containing a group separator (described under --group-separator) between contiguous groups of matches.
              With the -o or --only-matching option, this has no effect and a warning is given.

       -B NUM, --before-context=NUM
              Print NUM lines of leading context before matching lines.  Places a line containing a group separator (described under --group-separator) between contiguous groups of matches.
              With the -o or --only-matching option, this has no effect and a warning is given.

       -C NUM, -NUM, --context=NUM
              Print  NUM  lines  of  output  context.   Places  a line containing a group separator (described under --group-separator) between contiguous groups of matches.  With the -o or
              --only-matching option, this has no effect and a warning is given.

</code>```

Body:
I checked out the manifest file of k8s, but i want to also see the above n lines of my search.

   cat /etc/kubernetes/manifests/kube-apiserver.yaml | grep -i authorization -A4
        - --authorization-mode=Node,RBAC
        - --client-ca-file=/etc/kubernetes/pki/ca.crt
        - --enable-admission-plugins=NodeRestriction
        - --enable-bootstrap-token-auth=true
        - --etcd-cafile=/etc/kubernetes/pki/etcd/ca.crt

how tod this?

Body:
With -C you get the context around the match:

grep -C4 -i authorization /etc/kubernetes/manifests/kube-apiserver.yaml

From grep man page:

   Context Line Control
       -A NUM, --after-context=NUM
              Print NUM lines of trailing context after matching lines.  Places a line containing a group separator (described under --group-separator) between contiguous groups of matches.
              With the -o or --only-matching option, this has no effect and a warning is given.

       -B NUM, --before-context=NUM
              Print NUM lines of leading context before matching lines.  Places a line containing a group separator (described under --group-separator) between contiguous groups of matches.
              With the -o or --only-matching option, this has no effect and a warning is given.

       -C NUM, -NUM, --context=NUM
              Print  NUM  lines  of  output  context.   Places  a line containing a group separator (described under --group-separator) between contiguous groups of matches.  With the -o or
              --only-matching option, this has no effect and a warning is given.


问:
Show ContextMenuStrip at location of StatusBar item
I want to show a ContextMenuStrip at the location of a ToolStripStatusLabel in a StatusStrip. Ordinary controls have PointToScreen / PointToClient / etc, but as ToolStripStatusLabel is derived from Component it does not.

Any help would be appreciated.

答:
A very, very late answer, just because I happened to struggle with the same issue and googled up this question. What I found as the best solution adds one nice twist to the answers so far. Here it is:

```<code>    void toolStripItem_MouseUp(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {
            var label = (ToolStripItem)sender;
            this.contextMenuStrip1.Show(this.mainStatusStrip, label.Bounds.X + e.X, label.Bounds.Y + e.Y);
        }
    }
</code>```

Adding the mouse coordinates relative to the control (e.X, e.Y) to the bounds coordinates makes the menu appear at exactly the right position. Omitting this shows the menu at the top left corner of the ToolStripItem. For the record.

OwnerDisplayName: John Taylor

Body:
A very, very late answer, just because I happened to struggle with the same issue and googled up this question. What I found as the best solution adds one nice twist to the answers so far. Here it is:

    void toolStripItem_MouseUp(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {
            var label = (ToolStripItem)sender;
            this.contextMenuStrip1.Show(this.mainStatusStrip, label.Bounds.X + e.X, label.Bounds.Y + e.Y);
        }
    }

Adding the mouse coordinates relative to the control (e.X, e.Y) to the bounds coordinates makes the menu appear at exactly the right position. Omitting this shows the menu at the top left corner of the ToolStripItem. For the record.


问:
WIX Ref Project variable issue
My Wix Installer project references the service I want installed. The project name has periods in it, MyProject.Client.Service, and therefore I receive errors when compiling. Is my only options to rename the project so it doesn't have any periods in them? Or is there another way to ref this project?

I've tried updating the ref name, but nothing.

```<code><?define MyProjectCompliedPath=$(var.MyProject.Client.Service.TargetDir)?>
</code>```

答:
I have just tried this in a test project following your description using wix 3.11 and it does not produce any errors and warnings.
I've created a setup project referencing a c# library project having dots in it's name.

What i tried:

```<code><?xml version="1.0" encoding="utf-8"?>
<Include>
    <!-- TODO: Put your code here. -->
  <?define avar=$(var.ClassLibrary1df.df.df.TargetDir)?>
</Include>
</code>```

and consuming the variable in a property.

```<code><Property Id="hfhfh" Value="$(var.avar)"/>
</code>```

Also using the variable in a file component worked just fine.

So maybe there is a different problem in your wix project.

Title: WIX Ref Project variable issue

Body:
My Wix Installer project references the service I want installed. The project name has periods in it, MyProject.Client.Service, and therefore I receive errors when compiling. Is my only options to rename the project so it doesn't have any periods in them? Or is there another way to ref this project?

I've tried updating the ref name, but nothing.

<?define MyProjectCompliedPath=$(var.MyProject.Client.Service.TargetDir)?>

Body:
I have just tried this in a test project following your description using wix 3.11 and it does not produce any errors and warnings.
I've created a setup project referencing a c# library project having dots in it's name.

What i tried:

<?xml version="1.0" encoding="utf-8"?>
<Include>
    <!-- TODO: Put your code here. -->
  <?define avar=$(var.ClassLibrary1df.df.df.TargetDir)?>
</Include>

and consuming the variable in a property.

<Property Id="hfhfh" Value="$(var.avar)"/>

Also using the variable in a file component worked just fine.

So maybe there is a different problem in your wix project.


问:
Best way to delete LRO and RLO characters in Python
Is there any elegant solution or best practice how to remove RLO and LRO characters?

Explanation of my problem: I get/parse 400 000 string from the website. I need this string convert into integer type (just 400000 number value).

Any ideas how to elegantly remove this characters? ( and )

Thanks!

//Update:

capacity_value = capacity_value.encode('ascii', 'ignore').decode().replace(" ", "")

(encode() and decode() functions works but I don't like it. Is there any better solution in this case?)

答:
The str type has a translate method which can be use to replace or remove characters. Here if you want to remove space, RLO and LRO, you could do:

```<code>transtable = str.maketrans('', '', ' \u202d\u202c')
capacity_value = capacity_value..translate(transtable)
</code>```

Body:
The str type has a translate method which can be use to replace or remove characters. Here if you want to remove space, RLO and LRO, you could do:

transtable = str.maketrans('', '', ' \u202d\u202c')
capacity_value = capacity_value..translate(transtable)