问:
ForEach animation with dynamically added elements buggy
I'm trying to mimic the TikTok style feed. This involves the following elements (Published variables are kept in an 'appState' tracking file):

First: An array that keeps track of AVPlayers to be rendered:

```<code>@Published var selectedPlayers: [PlayerWrapper] = []

// PlayerWrapper type looks like this

struct PlayerWrapper: Hashable {
    let item_id: Int?
    var player: AVPlayer
}
</code>```

Second: An array that keeps track of all metadata associated with the video. This needs to be stored in a separate array for unrelated reasons.

```<code>@Published var selectedItems: [FeatureType] = []

// FeatureType type looks like this

struct FeatureType: Codable, Hashable {
    let item_id: Int?
    // a bunch of other properties that aren't related
}
</code>```

I try to render the AVPlayer views in a VStack as seen below, using offsets to view the correct one in the stack:

```<code>struct PlayerFeed: View {
@ObservedObject var appState: AppState // contains the variables defined above
@State var relativeIndex: Int = 0
@State var viewOffset: CGSize = .zero
@State var canceledSwipe = false

var body: some View {
VStack(spacing: 0){
    ForEach(enumerating: Array(appState.selectedPlayers.enumerated()), id: \.element) { (i,player) in
        PlayerWrapperView(appState: appState, i: i)
    }
}
.offset(y: (UIScreen.main.bounds.height * CGFloat(-relativeIndex)) + viewOffset.height)
.animation({
    Animation.linear(duration: 0.25)
}())
.gesture(
    DragGesture()
        .onChanged { gesture in
            if (viewOffset.height < gesture.translation.height && viewOffset.height < -10) || (viewOffset.height > gesture.translation.height && viewOffset.height > 10) {
                canceledSwipe = true
            }
            viewOffset = gesture.translation

        }
        .onEnded { _ in
            if !canceledSwipe {
                NotificationCenter.default.removeObserver(object)
                appState.selectedPlayers[relativeIndex].player.seek(to: .zero)
                appState.selectedPlayers[relativeIndex].player.pause()

                if let current_item_id = appState.selectedPlayers[relativeIndex].item_id, let current_overall_index = appState.selectedItems.firstIndex(where: { $0.item_id == current_item_id }) {
                    if viewOffset.height > 10 && current_overall_index > 0 {
                        if relativeIndex != 2 {
                            guard let item_id = appState.selectedPlayers.first?.item_id, let foundIndex = appState.selectedItems.firstIndex(where: { $0.item_id == item_id }) else { return }

                            let nextIndex = foundIndex - 1
                            if appState.selectedItems.indices.contains(nextIndex) {
                                let item = appState.selectedItems[nextIndex]
                                let player = AVPlayer(url: URL(string: item.thumbnail[0])!)
                                let wrappedPlayer = PlayerWrapper(item_id: item.item_id, player: player)
                                appState.selectedPlayers.removeLast()
                                        appState.selectedPlayers.insert(wrappedPlayer, at: 0)
                            } else {
                                relativeIndex = 0
                            }

                        } else {
                            relativeIndex -= 1
                        }

                    } else if viewOffset.height < -10 && current_overall_index < appState.selectedItems.count - 1 {
                        if relativeIndex != 0 {
                            guard let item_id = appState.selectedPlayers.last?.item_id, let foundIndex = appState.selectedItems.firstIndex(where: { $0.item_id == item_id }) else { return }

                            let nextIndex = foundIndex + 1
                            if appState.selectedItems.indices.contains(nextIndex) {
                                let item = appState.selectedItems[nextIndex]
                                let player = AVPlayer(url: URL(string: item.thumbnail[0])!)
                                let wrappedPlayer = PlayerWrapper(item_id: item.item_id, player: player)
                                appState.selectedPlayers.removeFirst()
                                appState.selectedPlayers.append(wrappedPlayer)
                            } else {
                                relativeIndex = 2
                            }

                        } else {
                            relativeIndex += 1
                        }
                    }
                }

                viewOffset = .zero

                // playing next video...
                appState.selectedPlayers[relativeIndex].player.play()

                appState.selectedPlayers[relativeIndex].player.actionAtItemEnd = .none

                object = NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: appState.selectedPlayers[relativeIndex].player.currentItem, queue: .main) { (_) in
                    print(NotificationCenter.default.debugDescription)
                    let playerItem = appState.selectedPlayers[relativeIndex].player
                    playerItem.seek(to: .zero)
                    playerItem.play()
                }
            } else {
                viewOffset = .zero
                canceledSwipe = false
            }
        }
)
.onAppear {

    // doing it for first video because scrollview didnt dragged yet...

    appState.selectedPlayers[0].player.play()

    appState.selectedPlayers[0].player.actionAtItemEnd = .none

    object = NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: appState.selectedPlayers[0].player.currentItem, queue: .main) { (_) in

        // notification to identify at the end of the video...
        let playerItem = appState.selectedPlayers[0].player
        playerItem.seek(to: .zero)
        playerItem.play()

    }
}
.frame(height: UIScreen.main.bounds.height, alignment: .top)
.background(Color.black.edgesIgnoringSafeArea(.all))
}
}
</code>```

For simplicity purposes, PlayerWrapperView just contains a line of code 'Player' that is a UIViewControllerRepresentable and can run the AVPlayer.

```<code>Player(appState: appState, player: $appState.selectedPlayers[i].player) // the player I want to run
</code>```

I am dynamically adding/removing players from the selectedPlayers array because when they are all rendered, the phone can't handle it (besides, I think there is a hard limit of 16 on AVPlayers that can be rendered). The AVPlayer url it pulls from comes out of the selectedItems array (an equivalent array index-wise). For some reason, when I swipe between videos in the Feed, I get a kind of glitchy behavior (not a smooth animation). In addition, sometimes the AVPlayer will render black, audio will cut out, etc. Not sure how to fix these issues. Any help is much appreciated!

Body:
I'm trying to mimic the TikTok style feed. This involves the following elements (Published variables are kept in an 'appState' tracking file):

First: An array that keeps track of AVPlayers to be rendered:

@Published var selectedPlayers: [PlayerWrapper] = []

// PlayerWrapper type looks like this

struct PlayerWrapper: Hashable {
    let item_id: Int?
    var player: AVPlayer
}

Second: An array that keeps track of all metadata associated with the video. This needs to be stored in a separate array for unrelated reasons.

@Published var selectedItems: [FeatureType] = []

// FeatureType type looks like this

struct FeatureType: Codable, Hashable {
    let item_id: Int?
    // a bunch of other properties that aren't related
}

I try to render the AVPlayer views in a VStack as seen below, using offsets to view the correct one in the stack:

struct PlayerFeed: View {
@ObservedObject var appState: AppState // contains the variables defined above
@State var relativeIndex: Int = 0
@State var viewOffset: CGSize = .zero
@State var canceledSwipe = false

var body: some View {
VStack(spacing: 0){
    ForEach(enumerating: Array(appState.selectedPlayers.enumerated()), id: \.element) { (i,player) in
        PlayerWrapperView(appState: appState, i: i)
    }
}
.offset(y: (UIScreen.main.bounds.height * CGFloat(-relativeIndex)) + viewOffset.height)
.animation({
    Animation.linear(duration: 0.25)
}())
.gesture(
    DragGesture()
        .onChanged { gesture in
            if (viewOffset.height < gesture.translation.height && viewOffset.height < -10) || (viewOffset.height > gesture.translation.height && viewOffset.height > 10) {
                canceledSwipe = true
            }
            viewOffset = gesture.translation

        }
        .onEnded { _ in
            if !canceledSwipe {
                NotificationCenter.default.removeObserver(object)
                appState.selectedPlayers[relativeIndex].player.seek(to: .zero)
                appState.selectedPlayers[relativeIndex].player.pause()

                if let current_item_id = appState.selectedPlayers[relativeIndex].item_id, let current_overall_index = appState.selectedItems.firstIndex(where: { $0.item_id == current_item_id }) {
                    if viewOffset.height > 10 && current_overall_index > 0 {
                        if relativeIndex != 2 {
                            guard let item_id = appState.selectedPlayers.first?.item_id, let foundIndex = appState.selectedItems.firstIndex(where: { $0.item_id == item_id }) else { return }

                            let nextIndex = foundIndex - 1
                            if appState.selectedItems.indices.contains(nextIndex) {
                                let item = appState.selectedItems[nextIndex]
                                let player = AVPlayer(url: URL(string: item.thumbnail[0])!)
                                let wrappedPlayer = PlayerWrapper(item_id: item.item_id, player: player)
                                appState.selectedPlayers.removeLast()
                                        appState.selectedPlayers.insert(wrappedPlayer, at: 0)
                            } else {
                                relativeIndex = 0
                            }

                        } else {
                            relativeIndex -= 1
                        }

                    } else if viewOffset.height < -10 && current_overall_index < appState.selectedItems.count - 1 {
                        if relativeIndex != 0 {
                            guard let item_id = appState.selectedPlayers.last?.item_id, let foundIndex = appState.selectedItems.firstIndex(where: { $0.item_id == item_id }) else { return }

                            let nextIndex = foundIndex + 1
                            if appState.selectedItems.indices.contains(nextIndex) {
                                let item = appState.selectedItems[nextIndex]
                                let player = AVPlayer(url: URL(string: item.thumbnail[0])!)
                                let wrappedPlayer = PlayerWrapper(item_id: item.item_id, player: player)
                                appState.selectedPlayers.removeFirst()
                                appState.selectedPlayers.append(wrappedPlayer)
                            } else {
                                relativeIndex = 2
                            }

                        } else {
                            relativeIndex += 1
                        }
                    }
                }

                viewOffset = .zero

                // playing next video...
                appState.selectedPlayers[relativeIndex].player.play()

                appState.selectedPlayers[relativeIndex].player.actionAtItemEnd = .none

                object = NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: appState.selectedPlayers[relativeIndex].player.currentItem, queue: .main) { (_) in
                    print(NotificationCenter.default.debugDescription)
                    let playerItem = appState.selectedPlayers[relativeIndex].player
                    playerItem.seek(to: .zero)
                    playerItem.play()
                }
            } else {
                viewOffset = .zero
                canceledSwipe = false
            }
        }
)
.onAppear {

    // doing it for first video because scrollview didnt dragged yet...

    appState.selectedPlayers[0].player.play()

    appState.selectedPlayers[0].player.actionAtItemEnd = .none

    object = NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: appState.selectedPlayers[0].player.currentItem, queue: .main) { (_) in

        // notification to identify at the end of the video...
        let playerItem = appState.selectedPlayers[0].player
        playerItem.seek(to: .zero)
        playerItem.play()

    }
}
.frame(height: UIScreen.main.bounds.height, alignment: .top)
.background(Color.black.edgesIgnoringSafeArea(.all))
}
}

For simplicity purposes, PlayerWrapperView just contains a line of code 'Player' that is a UIViewControllerRepresentable and can run the AVPlayer.

Player(appState: appState, player: $appState.selectedPlayers[i].player) // the player I want to run

I am dynamically adding/removing players from the selectedPlayers array because when they are all rendered, the phone can't handle it (besides, I think there is a hard limit of 16 on AVPlayers that can be rendered). The AVPlayer url it pulls from comes out of the selectedItems array (an equivalent array index-wise). For some reason, when I swipe between videos in the Feed, I get a kind of glitchy behavior (not a smooth animation). In addition, sometimes the AVPlayer will render black, audio will cut out, etc. Not sure how to fix these issues. Any help is much appreciated!


来源: stackexchange

问:
Why can't Huggingface's Transformers module load models from custom cache in Docker container's volume?
I understand that huggingface prefers to load models from the internet. However, I have a machine that doesn't have access to the internet. So, I am trying to load a model from its cached files, which I have moved to a custom directory /tmp/models/huggingface_cache. I have a volume for the container to access these files, and I have verified the container has access.

What I don't understand is why huggingface wants to create a directory to manage cache when I specified a custom directory first. The volume access should remain as read only. Therefore, I'm curious why I'm having these issues, and whether there is a better route to workaround huggingface's functionality of loading cached models.

I'm running an interactive container built from Ubuntu with the following command:

docker run -it --rm -v /tmp:/tmp:rw generic-container /bin/bash
```
<p>I then run the following commands in python3:</p>
<pre class="lang-py prettyprint-override"><code>from transformers import pipeline
from os import environ

environ["TRANSFORMERS_OFFLINE"] = "1"
environ["TRANSFORMERS_CACHE"] = "/tmp/models/huggingface_cache"

classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli", cache_dir="/tmp/models/huggingface_cache")

</code>```

And I get the following error:

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.8/dist-packages/transformers/pipelines/__init__.py", line 645, in pipeline
    config = AutoConfig.from_pretrained(model, _from_pipeline=task, **hub_kwargs, **model_kwargs)
  File "/usr/local/lib/python3.8/dist-packages/transformers/models/auto/configuration_auto.py", line 809, in from_pretrained
    config_dict, unused_kwargs = PretrainedConfig.get_config_dict(pretrained_model_name_or_path, **kwargs)
  File "/usr/local/lib/python3.8/dist-packages/transformers/configuration_utils.py", line 559, in get_config_dict
    config_dict, kwargs = cls._get_config_dict(pretrained_model_name_or_path, **kwargs)
  File "/usr/local/lib/python3.8/dist-packages/transformers/configuration_utils.py", line 614, in _get_config_dict
    resolved_config_file = cached_file(
  File "/usr/local/lib/python3.8/dist-packages/transformers/utils/hub.py", line 409, in cached_file
    resolved_file = hf_hub_download(
  File "/usr/local/lib/python3.8/dist-packages/huggingface_hub/utils/_validators.py", line 124, in _inner_fn
    return fn(*args, **kwargs)
  File "/usr/local/lib/python3.8/dist-packages/huggingface_hub/file_download.py", line 1038, in hf_hub_download
    os.makedirs(storage_folder, exist_ok=True)
  File "/usr/lib/python3.8/os.py", line 213, in makedirs
    makedirs(head, exist_ok=exist_ok)
  File "/usr/lib/python3.8/os.py", line 213, in makedirs
    makedirs(head, exist_ok=exist_ok)
  File "/usr/lib/python3.8/os.py", line 213, in makedirs
    makedirs(head, exist_ok=exist_ok)
  File "/usr/lib/python3.8/os.py", line 223, in makedirs
    mkdir(name, mode)
PermissionError: [Errno 13] Permission denied: '/.cache'
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I understand that huggingface prefers to load models from the internet. However, I have a machine that doesn't have access to the internet. So, I am trying to load a model from its cached files, which I have moved to a custom directory /tmp/models/huggingface_cache. I have a volume for the container to access these files, and I have verified the container has access.

What I don't understand is why huggingface wants to create a directory to manage cache when I specified a custom directory first. The volume access should remain as read only. Therefore, I'm curious why I'm having these issues, and whether there is a better route to workaround huggingface's functionality of loading cached models.

I'm running an interactive container built from Ubuntu with the following command:

docker run -it --rm -v /tmp:/tmp:rw generic-container /bin/bash

I then run the following commands in python3:

from transformers import pipeline
from os import environ

environ["TRANSFORMERS_OFFLINE"] = "1"
environ["TRANSFORMERS_CACHE"] = "/tmp/models/huggingface_cache"

classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli", cache_dir="/tmp/models/huggingface_cache")

And I get the following error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.8/dist-packages/transformers/pipelines/__init__.py", line 645, in pipeline
    config = AutoConfig.from_pretrained(model, _from_pipeline=task, **hub_kwargs, **model_kwargs)
  File "/usr/local/lib/python3.8/dist-packages/transformers/models/auto/configuration_auto.py", line 809, in from_pretrained
    config_dict, unused_kwargs = PretrainedConfig.get_config_dict(pretrained_model_name_or_path, **kwargs)
  File "/usr/local/lib/python3.8/dist-packages/transformers/configuration_utils.py", line 559, in get_config_dict
    config_dict, kwargs = cls._get_config_dict(pretrained_model_name_or_path, **kwargs)
  File "/usr/local/lib/python3.8/dist-packages/transformers/configuration_utils.py", line 614, in _get_config_dict
    resolved_config_file = cached_file(
  File "/usr/local/lib/python3.8/dist-packages/transformers/utils/hub.py", line 409, in cached_file
    resolved_file = hf_hub_download(
  File "/usr/local/lib/python3.8/dist-packages/huggingface_hub/utils/_validators.py", line 124, in _inner_fn
    return fn(*args, **kwargs)
  File "/usr/local/lib/python3.8/dist-packages/huggingface_hub/file_download.py", line 1038, in hf_hub_download
    os.makedirs(storage_folder, exist_ok=True)
  File "/usr/lib/python3.8/os.py", line 213, in makedirs
    makedirs(head, exist_ok=exist_ok)
  File "/usr/lib/python3.8/os.py", line 213, in makedirs
    makedirs(head, exist_ok=exist_ok)
  File "/usr/lib/python3.8/os.py", line 213, in makedirs
    makedirs(head, exist_ok=exist_ok)
  File "/usr/lib/python3.8/os.py", line 223, in makedirs
    mkdir(name, mode)
PermissionError: [Errno 13] Permission denied: '/.cache'


问:
Batik Update Manager does not track changes to CSS Styles
I want to update an already parsed SVG document and create an off-screen buffered image. I use the BATIK UpdateManager to do this.

The code for the updates is:

```<code>public void update(BTransform.Scale scale){
    RunnableQueue rq = updateManager.getUpdateRunnableQueue();
    try {
       rq.invokeAndWait(() ->{
           System.out.println("***UPDATE MANAGER ***"+": updating document");
        updateDocument(svgDocument, owner);
         });
    }catch (InterruptedException ie){
    //         do nothing for now.
    }
}
</code>```

The updateDocument method does several things:

It changes existing svg tags, e.g. by adding different text content to text tags or changing the attributes of tags for transformations etc.

It replaces the CSS styles tag that is contained in the SVG by an updated styles tag. The content of the styles tag is created in form of a string and then put into the styles node. See code below.

While changing the SVG elements is perfectly reflected in the resulting buffered image, the change to the style tag seems not to be tracked completely by Batik:

While the changed styles seem to be applied correctly to SVG tags that receives any other update (e.g. attribute change or content change), it is not applied to elements that do NOT undergo other updates. In my specific case, I have a circle that is filled with a gradient. The SVG circle remains unchanged. However the style in CSS changes. THis change is not tracked by the update manager. How can I enforce a re-application of the styles to all elements?

The circle looks as follows:

```<code><circle class="format1 gradient1" cx="100" cy="100" r="20"/>
</code>```

The corresponding CSS Style looks as follows:

```<code><style id="styles">  </style>
  :root{
    .format1 {
        fill: **#808080;**
        stroke: black;
        stroke-width: 3px;
    }
    .gradient1-start {
        stop-color:white;
        stop-opacity: 1;
    }
    .gradient1-mid {
        stop-color:white;
        stop-opacity: 1;
    }
    .gradient1-stop {
        stop-color: **#808080;**
        stop-opacity: 1;
    }
  </style>
  <defs id="Patterns_And_Gradients">
    <radialGradient id="radialGradient1" cx="0.5" cy="0.5" r="0.73">
        <stop class="gradient1-start" offset="0%"/>
        <stop class="gradient1-mid" offset="10%"/>
        <stop class="gradient1-stop" offset="100%"/>
    </radialGradient>
   </defs>
</code>```

The items indicated in bold are replace by the update method.

The updateDocument method is updating the styles node by replacing it by a new one. I do this, because simply changing the text content is not picked up either:

```<code> public void updateDocument(SVGOMDocument svgDocument, BSvgPicture owner) {
      NodeList styleNodes = svgDocument.getElementsByTagName("style");
      //if the original styles are not yet initialized,
      //retrieve them from document
      if (originalStylesContent ==null){
      ArrayList<String> styleContent=new ArrayList<>();
      for (int i=0; i<styleNodes.getLength(); i++){
         styleContent.add(styleNodes.item(i).getTextContent());
      }
      originalStylesContent = styleContent.toArray(new String[0]);
      }
      String[] newStylesContent=updateCssProperties(originalStylesContent, owner);
    //      SVGSVGElement rootElement=svgDocument.getRootElement();
    //      SVGTransform st= rootElement.createSVGTransform();
      newStylesContent= updateCssRulesets(svgDocument, newStylesContent, owner);
      for (int i=0; i<styleNodes.getLength(); i++){
         SVGStyleElement existingStyleNode = (SVGStyleElement) styleNodes.item(i);

         //BATIK does not seem to pick up changes to the content of style tags
         // when they are done through "setTextContent"
         //Therefore, I create a new style node and then replace the entire
         //existing style node with the new style,
         // which batik will hopefully pick up.
         //Create a new style tag
         SVGStyleElement newStyle = (SVGStyleElement)svgDocument
                                      .createElementNS(SVGConstants.SVG_NAMESPACE_URI, "style");
    //         newStyle.setAttributeNS(null, "type", "text/css");
         //Set the content of the new style tag to the updated formats
         newStyle.appendChild(svgDocument.createCDATASection(newStylesContent[i]));
         //Replace the existing style node it with the newly created style,
         //so that the DOM is (hopefully) updated.
         existingStyleNode.getParentNode().replaceChild(newStyle, existingStyleNode);
      }
   }
</code>```

Body:
I want to update an already parsed SVG document and create an off-screen buffered image. I use the BATIK UpdateManager to do this.

The code for the updates is:

public void update(BTransform.Scale scale){
    RunnableQueue rq = updateManager.getUpdateRunnableQueue();
    try {
       rq.invokeAndWait(() ->{
           System.out.println("***UPDATE MANAGER ***"+": updating document");
        updateDocument(svgDocument, owner);
         });
    }catch (InterruptedException ie){
    //         do nothing for now.
    }
}

The updateDocument method does several things:

It changes existing svg tags, e.g. by adding different text content to text tags or changing the attributes of tags for transformations etc.

It replaces the CSS styles tag that is contained in the SVG by an updated styles tag. The content of the styles tag is created in form of a string and then put into the styles node. See code below.

While changing the SVG elements is perfectly reflected in the resulting buffered image, the change to the style tag seems not to be tracked completely by Batik:

While the changed styles seem to be applied correctly to SVG tags that receives any other update (e.g. attribute change or content change), it is not applied to elements that do NOT undergo other updates. In my specific case, I have a circle that is filled with a gradient. The SVG circle remains unchanged. However the style in CSS changes. THis change is not tracked by the update manager. How can I enforce a re-application of the styles to all elements?

The circle looks as follows:

<circle class="format1 gradient1" cx="100" cy="100" r="20"/>

The corresponding CSS Style looks as follows:

  :root{
    .format1 {
        fill: **#808080;**
        stroke: black;
        stroke-width: 3px;
    }
    .gradient1-start {
        stop-color:white;
        stop-opacity: 1;
    }
    .gradient1-mid {
        stop-color:white;
        stop-opacity: 1;
    }
    .gradient1-stop {
        stop-color: **#808080;**
        stop-opacity: 1;
    }
  </style>
  <defs id="Patterns_And_Gradients">
    <radialGradient id="radialGradient1" cx="0.5" cy="0.5" r="0.73">
        <stop class="gradient1-start" offset="0%"/>
        <stop class="gradient1-mid" offset="10%"/>
        <stop class="gradient1-stop" offset="100%"/>
    </radialGradient>
   </defs>

The items indicated in bold are replace by the update method.

The updateDocument method is updating the styles node by replacing it by a new one. I do this, because simply changing the text content is not picked up either:

 public void updateDocument(SVGOMDocument svgDocument, BSvgPicture owner) {
      NodeList styleNodes = svgDocument.getElementsByTagName("style");
      //if the original styles are not yet initialized,
      //retrieve them from document
      if (originalStylesContent ==null){
      ArrayList<String> styleContent=new ArrayList<>();
      for (int i=0; i


问:
Django monolith: How to render front-end while still loading one function from backend
I have a django 4.0 monolith project; however, one of the objects (a graph) that I pass to the template context to display in the html is slow to load.

I'd like to have the rest of the page render first, while this function is still running/loading. That way, users can see the rest of the page while the graph is still loading. Thoughts on the best approach to this?

I tried creating a custom tag to load the graph, but the browser still waited for the everything to load before showing anything on the page.

I'm wondering if some type of javascript call would accomplish this. Perhaps an ajax call? Or the asyncio python package?


问:
Devices are not supported by this Flutter project
Theres is a project made on flutter which i have to continue, it's my first time using flutter, basically i already downloaded the project from github and installed the dependencies as well, but when i try to run the project this message apperars:

```<code>No supported devices connected.

The following devices were found, but are not supported by this project:

macOS (desktop) • macos  • darwin-x64     • macOS 12.5.1 21G83 darwin-x64

Chrome (web)    • chrome • web-javascript • Google Chrome 108.0.5359.124

If you would like your app to run on macos or web, consider running `flutter create .` to generate projects for these platforms.
</code>```

I don't want to create another project, i just need to run this one.

I'm using VS Code and i was told at the bottom right corner there is a button for choosing a device. When i click on it this shows up:

enter imaImage description here

I'm using a mac PC

I searched on internet but still dont know what to do, i watched lot of videos explaining how to start a new project of flutter but it's not the same for my project, obviously i'm missing something

Body:
Theres is a project made on flutter which i have to continue, it's my first time using flutter, basically i already downloaded the project from github and installed the dependencies as well, but when i try to run the project this message apperars:

No supported devices connected.

The following devices were found, but are not supported by this project:

macOS (desktop) • macos  • darwin-x64     • macOS 12.5.1 21G83 darwin-x64

Chrome (web)    • chrome • web-javascript • Google Chrome 108.0.5359.124

If you would like your app to run on macos or web, consider running `flutter create .` to generate projects for these platforms.

I don't want to create another project, i just need to run this one.

I'm using VS Code and i was told at the bottom right corner there is a button for choosing a device. When i click on it this shows up:

enter imaImage description here

I'm using a mac PC

I searched on internet but still dont know what to do, i watched lot of videos explaining how to start a new project of flutter but it's not the same for my project, obviously i'm missing something


问:
Why addEventListener not working on an appendChild?
I create a couple of "a" elements at the load of the webpage like this, with a default class called "link-block-2", and with a custom id. Then, I add an image inside this "a" element with an image:

```<code>function creatediv(div_projectname) {
  var div1 = document.createElement('a');
  div1.className = "link-block-2";
  div1.setAttribute("id", `${div_projectname}_btn`);
  document.getElementById('div-container-other-projects').appendChild(div1);
  //add div for image
  var divimage = document.createElement('div');
  divimage.className = "div-block-7";
  document.getElementById(`${div_projectname}_btn`).appendChild(divimage)
}
</code>```

And this is the finall result:

```<code>    <div class="div-block" id="div-container-other-projects">
      <a class="link-block-2" id="p1_btn"><div class="div-block-7" id="p1_btn"></div></a>
      <a class="link-block-2" id="p2_btn"><div class="div-block-7" id="p2_btn"></div></a>
      <a class="link-block-2" id="p3_btn"><div class="div-block-7" id="p3_btn"></div></a>
      <a class="link-block-2" id="p4_btn"><div class="div-block-7" id="p4_btn"></div></a>
    </div>
</code>```

I have a function where I detect which "a" element I click:

```<code>const buttonscontainer = document.getElementById('div-container-other-projects')
buttonscontainer.addEventListener('click', event => {
  const target = event.target
  if (target.className !== 'link-block-2') return
  Array.from(buttonscontainer.children).forEach(child =>
    child.classList.remove('link-block-2--selected'))
  target.classList.add('link-block-2--selected')
})
</code>```

This doesn't work because of, when I click on the div appended that has an image (id="p1_btn","p2_btn"..) does not recognize that I am clickin because of the z-index value. I think that by default the div with an image that I append after the "a" element has a zindex value superior than the "a", but no matter what I put on the css class (zindex=100, position aboslute, relative..) that the last div that I append has a zindex bigger thant the previous "a" and the click event listener doesnt work...

I've tried a lot of other solutions and doesn't really work as I want, anyone can help?

Thanks!:)

Body:
I create a couple of "a" elements at the load of the webpage like this, with a default class called "link-block-2", and with a custom id. Then, I add an image inside this "a" element with an image:

function creatediv(div_projectname) {
  var div1 = document.createElement('a');
  div1.className = "link-block-2";
  div1.setAttribute("id", `${div_projectname}_btn`);
  document.getElementById('div-container-other-projects').appendChild(div1);
  //add div for image
  var divimage = document.createElement('div');
  divimage.className = "div-block-7";
  document.getElementById(`${div_projectname}_btn`).appendChild(divimage)
}

And this is the finall result:

I have a function where I detect which "a" element I click:

const buttonscontainer = document.getElementById('div-container-other-projects')
buttonscontainer.addEventListener('click', event => {
  const target = event.target
  if (target.className !== 'link-block-2') return
  Array.from(buttonscontainer.children).forEach(child =>
    child.classList.remove('link-block-2--selected'))
  target.classList.add('link-block-2--selected')
})

This doesn't work because of, when I click on the div appended that has an image (id="p1_btn","p2_btn"..) does not recognize that I am clickin because of the z-index value. I think that by default the div with an image that I append after the "a" element has a zindex value superior than the "a", but no matter what I put on the css class (zindex=100, position aboslute, relative..) that the last div that I append has a zindex bigger thant the previous "a" and the click event listener doesnt work...

I've tried a lot of other solutions and doesn't really work as I want, anyone can help?

Thanks!:)


问:
Different behaviour when producing annotations with Erlang Typer
I am using the typer_core module of Dialyzer to automatically infer typespecs. However, I am obtaining different behaviour based on whether the files specified are prepended with the . character or not. The behaviour described below only affects files located in the directory where the typer command is run; files in child directories are processed as expected by Typer.

Consider the module test.erl:

-module(test).

is_a_ok(a) -> ok.
```
<p>The behaviour below is produced when evaluating the following expressions on the REPL:</p>
<pre class="lang-erlang prettyprint-override"><code>% Prepending with the '.' character.

% Creates the file ./typer_ann/test.ann.erl, but is NOT annotated.
typer_core:run(#{mode => annotate, files => ["./test.erl"]}).
      Processing file: "./test.erl"
             Saved as: "./typer_ann/test.ann.erl"

% Does NOT annotate the file ./test.erl.
typer_core:run(#{mode => annotate_in_place, files => ["./test.erl"]}).
      Processing file: "./test.erl"
             Saved as: "./test.erl"

% Without the '.' character.

% Creates the file ./typer_ann/test.ann.erl, and is annotated.
typer_core:run(#{mode => annotate, files => ["test.erl"]}).
      Processing file: "test.erl"
             Saved as: "./typer_ann/test.ann.erl"

% Annotates the file ./test.erl.
typer_core:run(#{mode => annotate_in_place, files => ["test.erl"]}).
      Processing file: "test.erl"
             Saved as: "test.erl"
</code>```

Using . in conjunction with the files_r key (equivalent to the -r command line switch) processes directories recursively. I observed the same behaviour described above when attempting to annotate files with the files_r key, specifying . as the starting directory:

% Does NOT annotate any of the files in the current directory.
typer_core:run(#{mode => annotate_in_place, files_r => ["."]}).
      Processing file: "./test.erl"
             Saved as: "./test.erl"
```
<p>This can be reproduced using Typer on the command line:</p>
<pre class="lang-bash prettyprint-override"><code># Does NOT annotate the file ./test.erl.
$ typer --annotate-in-place ./test.erl
      Processing file: "./test.erl"
             Saved as: "./test.erl"

# Does NOT annotate any of the files in the current directory.
$ typer --annotate-in-place -r .
      Processing file: "./test.erl"
             Saved as: "./test.erl"
</code>```

Note that, however, *.erl files in child directories do get annotated in the first and last examples, i.e. using typer_core:run(#{mode => annotate_in_place, files_r => ["."]}) and typer --annotate-in-place -r . The following examples also work:

# Annotates the file ./test.erl (no . in front of the file name).
$ typer --annotate-in-place test.erl
      Processing file: "test.erl"
             Saved as: "test.erl"

# Annotates the file test.erl (. in front of the directory, one directory up).
$ typer --annotate-in-place ./typer_test/test.erl
      Processing file: "./typer_test/test.erl"
             Saved as: "./typer_test/test.erl"
```

I might be missing something and would appreciate any suggestions regarding this behaviour. I am using OTP 25.0.4.

Body:
I am using the typer_core module of Dialyzer to automatically infer typespecs. However, I am obtaining different behaviour based on whether the files specified are prepended with the . character or not. The behaviour described below only affects files located in the directory where the typer command is run; files in child directories are processed as expected by Typer.

Consider the module test.erl:

-module(test).

is_a_ok(a) -> ok.

The behaviour below is produced when evaluating the following expressions on the REPL:

% Prepending with the '.' character.

% Creates the file ./typer_ann/test.ann.erl, but is NOT annotated.
typer_core:run(#{mode => annotate, files => ["./test.erl"]}).
      Processing file: "./test.erl"
             Saved as: "./typer_ann/test.ann.erl"

% Does NOT annotate the file ./test.erl.
typer_core:run(#{mode => annotate_in_place, files => ["./test.erl"]}).
      Processing file: "./test.erl"
             Saved as: "./test.erl"

% Without the '.' character.

% Creates the file ./typer_ann/test.ann.erl, and is annotated.
typer_core:run(#{mode => annotate, files => ["test.erl"]}).
      Processing file: "test.erl"
             Saved as: "./typer_ann/test.ann.erl"

% Annotates the file ./test.erl.
typer_core:run(#{mode => annotate_in_place, files => ["test.erl"]}).
      Processing file: "test.erl"
             Saved as: "test.erl"

Using . in conjunction with the files_r key (equivalent to the -r command line switch) processes directories recursively. I observed the same behaviour described above when attempting to annotate files with the files_r key, specifying . as the starting directory:

% Does NOT annotate any of the files in the current directory.
typer_core:run(#{mode => annotate_in_place, files_r => ["."]}).
      Processing file: "./test.erl"
             Saved as: "./test.erl"

This can be reproduced using Typer on the command line:

# Does NOT annotate the file ./test.erl.
$ typer --annotate-in-place ./test.erl
      Processing file: "./test.erl"
             Saved as: "./test.erl"

# Does NOT annotate any of the files in the current directory.
$ typer --annotate-in-place -r .
      Processing file: "./test.erl"
             Saved as: "./test.erl"

Note that, however, *.erl files in child directories do get annotated in the first and last examples, i.e. using typer_core:run(#{mode => annotate_in_place, files_r => ["."]}) and typer --annotate-in-place -r . The following examples also work:

# Annotates the file ./test.erl (no . in front of the file name).
$ typer --annotate-in-place test.erl
      Processing file: "test.erl"
             Saved as: "test.erl"

# Annotates the file test.erl (. in front of the directory, one directory up).
$ typer --annotate-in-place ./typer_test/test.erl
      Processing file: "./typer_test/test.erl"
             Saved as: "./typer_test/test.erl"

I might be missing something and would appreciate any suggestions regarding this behaviour. I am using OTP 25.0.4.


问:
Why are some values in Sklearn K-Nearest Neighbors affinity matrix for spectral clustering equal to 0.5?
I am trying to understand how KNN works for spectral clustering. The affinity information I am getting below have a few values being 0.5.

I added the affinity matrix to its transpose and took the average of it but there are still a few discrepancies with the result that this code gives.

I specifically want to know how the 0.5's below come about.

```<code>from sklearn.cluster import SpectralClustering
import matplotlib.pyplot as plt
import numpy as np
X = np.array([[1, 0], [1, 1], [1, 2], [2,0], [2, 1],
              [3, 5], [3, 6], [4, 7]])
sc = SpectralClustering(n_clusters=2, affinity='nearest_neighbors', n_neighbors=3, assign_labels='discretize', random _state=0).fit(X)
</code>```
```<code>  (0, 1)    1.0
  (0, 3)    1.0
  (0, 0)    1.0
  (1, 4)    0.5
  (1, 0)    1.0
  (1, 2)    1.0
  (1, 1)    1.0
  (2, 4)    0.5
  (2, 1)    1.0
  (2, 2)    1.0
  (3, 0)    1.0
  (3, 4)    1.0
  (3, 3)    1.0
  (4, 2)    0.5
  (4, 1)    0.5
  (4, 3)    1.0
  (4, 4)    1.0
  (5, 7)    1.0
  (5, 6)    1.0
  (5, 5)    1.0
  (6, 7)    1.0
  (6, 5)    1.0
  (6, 6)    1.0
  (7, 5)    1.0
  (7, 6)    1.0
  (7, 7)    1.0

I added the affinity matrix to its transpose and took the average of it but there are still a few discrepancies with the result that this code gives.
</code>```

Body:
I am trying to understand how KNN works for spectral clustering. The affinity information I am getting below have a few values being 0.5.

I added the affinity matrix to its transpose and took the average of it but there are still a few discrepancies with the result that this code gives.

I specifically want to know how the 0.5's below come about.

from sklearn.cluster import SpectralClustering
import matplotlib.pyplot as plt
import numpy as np
X = np.array([[1, 0], [1, 1], [1, 2], [2,0], [2, 1],
              [3, 5], [3, 6], [4, 7]])
sc = SpectralClustering(n_clusters=2, affinity='nearest_neighbors', n_neighbors=3, assign_labels='discretize', random _state=0).fit(X)

  (0, 1)    1.0
  (0, 3)    1.0
  (0, 0)    1.0
  (1, 4)    0.5
  (1, 0)    1.0
  (1, 2)    1.0
  (1, 1)    1.0
  (2, 4)    0.5
  (2, 1)    1.0
  (2, 2)    1.0
  (3, 0)    1.0
  (3, 4)    1.0
  (3, 3)    1.0
  (4, 2)    0.5
  (4, 1)    0.5
  (4, 3)    1.0
  (4, 4)    1.0
  (5, 7)    1.0
  (5, 6)    1.0
  (5, 5)    1.0
  (6, 7)    1.0
  (6, 5)    1.0
  (6, 6)    1.0
  (7, 5)    1.0
  (7, 6)    1.0
  (7, 7)    1.0

I added the affinity matrix to its transpose and took the average of it but there are still a few discrepancies with the result that this code gives.


问:
xlsx output is updated with #VALUE! when opened a second time
When I close the output xlsx file and re-open it then values I populated turn into #VALUE!...Not sure what is wrong. This peculiar thing happens only with this worksheet.</p>
```<code># Run Macro from Python for 'DailyApps' Output
# Open Workbooks
wb1 = xw.Book('DailyApps_v2.xlsb')
wb = xw.Book('DailyApps_reduced_columns.xlsx')

macro_DailyApps = wb1.macro("Module1.DailyApps_reduced_columns")
macro_DailyApps()
wb.save()
</code>```

Body:
When I close the output xlsx file and re-open it then values I populated turn into #VALUE!...Not sure what is wrong. This peculiar thing happens only with this worksheet.

# Run Macro from Python for 'DailyApps' Output
# Open Workbooks
wb1 = xw.Book('DailyApps_v2.xlsb')
wb = xw.Book('DailyApps_reduced_columns.xlsx')

macro_DailyApps = wb1.macro("Module1.DailyApps_reduced_columns")
macro_DailyApps()
wb.save()


问:
node.js/typescript test: Unit test should return json body (proper typescript)
I have a test "should return json body"

orderController.test.ts

```<code>import { Request, Response } from "express";
import { createOrder } from "../../controllers/orderController";
import { Orders } from "../../models/orders";
import httpMocks from 'node-mocks-http'
import newOrder from '../mock-data/new-order.json'

Orders.create = jest.fn()

let req: Request, res: Response
beforeEach(() => {
  req = httpMocks.createRequest()
  res = httpMocks.createResponse()
})

describe("createOrder", () => {
  beforeEach(() => {
    req.body = newOrder
  })

  it("should return json body", async() => {
    Orders.create.mockReturnValue(newOrder)
    await createOrder(req, res)
    expect(res._getJSONData()).toBe(newOrder)
  })
})
</code>```

But typescript when hover over mockReturnValue, shows:

'any
Property 'mockReturnValue' does not exist on type '{ <DocContents = AnyKeys<{ createdAt: NativeDate; updatedAt: NativeDate; } & { type: string; color: string; price: number; textLabel?: string | undefined; imageUrl?: string | undefined; }>>(docs: (({ ...; } & { ...; }) | DocContents)[], options?: SaveOptions | undefined): Promise<...>; <DocContents = AnyKeys<...>>(d...'.ts(2339)'

Also, _getJSONData, shows

'any
Property '_getJSONData' does not exist on type 'Response<any, Record<string, any>>'.ts(2339)'

How properly mock model Orders.create and res (maybe req as well) in case it is typescript?

Body:
I have a test "should return json body"

orderController.test.ts

import { Request, Response } from "express";
import { createOrder } from "../../controllers/orderController";
import { Orders } from "../../models/orders";
import httpMocks from 'node-mocks-http'
import newOrder from '../mock-data/new-order.json'

Orders.create = jest.fn()

let req: Request, res: Response
beforeEach(() => {
  req = httpMocks.createRequest()
  res = httpMocks.createResponse()
})

describe("createOrder", () => {
  beforeEach(() => {
    req.body = newOrder
  })

  it("should return json body", async() => {
    Orders.create.mockReturnValue(newOrder)
    await createOrder(req, res)
    expect(res._getJSONData()).toBe(newOrder)
  })
})

But typescript when hover over mockReturnValue, shows:

'any
Property 'mockReturnValue' does not exist on type '{ <DocContents = AnyKeys<{ createdAt: NativeDate; updatedAt: NativeDate; } & { type: string; color: string; price: number; textLabel?: string | undefined; imageUrl?: string | undefined; }>>(docs: (({ ...; } & { ...; }) | DocContents)[], options?: SaveOptions | undefined): Promise<...>; <DocContents = AnyKeys<...>>(d...'.ts(2339)'

Also, _getJSONData, shows

'any
Property '_getJSONData' does not exist on type 'Response<any, Record<string, any>>'.ts(2339)'

How properly mock model Orders.create and res (maybe req as well) in case it is typescript?


问:
MoviePy TextClip set_position not working
I am working on my free time on a project that uses:

MoviePy latest release (1.0.3)

ImageMagick 7.1.0-53

Python >=3.8,<4

Windows 10

The goal is to concatenate clips and for each, I want to show a text at the top left of the screen.

But none of my many tries is concluant (some are listed below). I run out of ideas to test...
The text is always centered at the left.

textclip: TextClip = TextClip(
   some_text,
   method="caption",
   align="center",
   fontsize=60,
   color="white"
)

textclip = textclip.set_position(("left", "top"))
textclip = textclip.set_duration(videoclip.duration)
```
<pre class="lang-py prettyprint-override"><code>textclip: TextClip = TextClip(
   some_text,
   method="caption",
   align="center",
   fontsize=60,
   color="white"
).set_position(("left", "top")).set_duration(videoclip.duration) # neither set_pos is working
</code>```

Hope i will find some help here, you guys are amazing !

Body:
I am working on my free time on a project that uses:

MoviePy latest release (1.0.3)

ImageMagick 7.1.0-53

Python >=3.8,<4

Windows 10

The goal is to concatenate clips and for each, I want to show a text at the top left of the screen.

But none of my many tries is concluant (some are listed below). I run out of ideas to test...
The text is always centered at the left.

textclip: TextClip = TextClip(
   some_text,
   method="caption",
   align="center",
   fontsize=60,
   color="white"
)

textclip = textclip.set_position(("left", "top"))
textclip = textclip.set_duration(videoclip.duration)

textclip: TextClip = TextClip(
   some_text,
   method="caption",
   align="center",
   fontsize=60,
   color="white"
).set_position(("left", "top")).set_duration(videoclip.duration) # neither set_pos is working

Hope i will find some help here, you guys are amazing !


问:
OpenGL C++ undefined reference to symbol 'glViewport'
When I try to compile it, I get a strange error:

[domon@archlinux TileVox-engine]$ g++ -c engine_main.cpp
[domon@archlinux TileVox-engine]$ g++ engine_main.o -o game -L -lGL -lglfw -lGLEW -lglut -lGLU
/usr/bin/ld: engine_main.o: undefined reference to symbol 'glViewport'
/usr/bin/ld: /usr/lib/libGL.so.1: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status
```
<p>Code:</p>
```#include <iostream>
#define GLEW_STATIC
#include <GL/glew.h>
#include <GLFW/glfw3.h>

using namespace std;

int window_width = 1280;
int window_height = 720;

int main()
{
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    GLFWwindow* window = glfwCreateWindow(window_width, window_height, "TileVox-engine: Main scene", nullptr, nullptr);
    if (window == nullptr){
        cout << "TileVox-engine Error: failed to create OpenGL profile";
        glfwTerminate();

        return -1;
    }

    glfwMakeContextCurrent(window);

    glewExperimental = GL_TRUE;

    if (glewInit() != GLEW_OK){
        cout << "OpenGL Error: starting failed";
    }

    glViewport(0,0, window_width, window_height);

    while (!glfwWindowShouldClose(window))
    {
        glfwPollEvents();
        glfwSwapBuffers(window);
    }
    glfwTerminate();
    return 0;
}
```

But there are no errors here, and I compiled and added the libraries correctly, what could be the problem?

Body:
When I try to compile it, I get a strange error:

[domon@archlinux TileVox-engine]$ g++ -c engine_main.cpp
[domon@archlinux TileVox-engine]$ g++ engine_main.o -o game -L -lGL -lglfw -lGLEW -lglut -lGLU
/usr/bin/ld: engine_main.o: undefined reference to symbol 'glViewport'
/usr/bin/ld: /usr/lib/libGL.so.1: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status

Code:

#include <iostream>
#define GLEW_STATIC
#include <GL/glew.h>
#include <GLFW/glfw3.h>

using namespace std;

int window_width = 1280;
int window_height = 720;

int main()
{
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    GLFWwindow* window = glfwCreateWindow(window_width, window_height, "TileVox-engine: Main scene", nullptr, nullptr);
    if (window == nullptr){
        cout << "TileVox-engine Error: failed to create OpenGL profile";
        glfwTerminate();

        return -1;
    }

    glfwMakeContextCurrent(window);

    glewExperimental = GL_TRUE;

    if (glewInit() != GLEW_OK){
        cout << "OpenGL Error: starting failed";
    }

    glViewport(0,0, window_width, window_height);

    while (!glfwWindowShouldClose(window))
    {
        glfwPollEvents();
        glfwSwapBuffers(window);
    }
    glfwTerminate();
    return 0;
}

But there are no errors here, and I compiled and added the libraries correctly, what could be the problem?


问:
Cannot render image as wallpaper when compositor is running
I've been trying to learn both Imlib & X11, as I've been working on a project that includes both of them, and I've came across a weird issue with it. Basically, whenever I try to render my wallpaper, it will just do it "in the background," and will only show when I kill off my compositor (feh.) When I use programs like feh or xsetroot, they are both able to draw over picom, but my code cannot for some reason. I have a wrapper over it written in haskell, but I will omit that for simplicity. Here is the code I've been working with:

#include <X11/Xlib.h>
#include <Imlib2.h>
#include <stdio.h>
#include <stdlib.h>
static void
die(int err, char *msg)
{
    fprintf(stderr, "%s: %s\n", "qzbg", msg);
    exit(err);
}

struct dSize {
    uint32_t w;
    uint32_t h;
};

struct System {
    Display *dpy;
    Screen *screen;
    Window root;
    uint32_t screen_count;
};

static inline struct dSize
get_display_size()
{
    struct dSize x;
    Display *dpy = XOpenDisplay(NULL);
    if (!dpy) {
        die (-1, "Failed to open display.");
    }
    Screen *screen = DefaultScreenOfDisplay(dpy);
    if (!screen) {
        die (-1, "Failed to obtain the default screen.");
    }
    x.w = screen->width;
    x.h = screen->height;
    return x;
}

static void
set_wallpaper(int h, int w, struct System sys)
{
    Pixmap pix;

    sys.dpy = XOpenDisplay(NULL);

    sys.screen_count = DefaultScreen(sys.dpy);
    sys.root = RootWindow(sys.dpy, sys.screen_count);

    pix = XCreatePixmap(sys.dpy, sys.root,
                        h, w,
                        DefaultDepth(sys.dpy, sys.screen_count));

    imlib_context_set_display(sys.dpy);
    imlib_context_set_visual(DefaultVisual(sys.dpy, sys.screen_count));
    imlib_context_set_colormap(DefaultColormap(sys.dpy, sys.screen_count));
    imlib_context_set_drawable(pix);
    imlib_render_image_on_drawable(0, 0);

    XSetWindowBackgroundPixmap(sys.dpy, sys.root, pix);

    XClearWindow(sys.dpy, sys.root);

    while (XPending(sys.dpy)) {
        XEvent ev;
        XNextEvent(sys.dpy, &ev);
    }
    XFreePixmap(sys.dpy, pix);

    imlib_free_image_and_decache();

    XCloseDisplay(sys.dpy);
}
void
set_background(char *filename, struct System sys)
{
    Imlib_Image image;
    int img_w, img_h;

    image = imlib_load_image(filename);
    if (!image)
        die(-1, "Could not load image.");

    imlib_context_set_image(image);

    img_w = imlib_image_get_width();
    img_h = imlib_image_get_height();

    set_wallpaper(img_w, img_h, sys);
}

int
render(char *prog)
{
    struct dSize size = get_display_size();
    struct System sys;
    set_background(prog, sys);
}
```
<p>The structs are just for convenience. I am able to render the image properly as my wallpaper whenever I don't have picom active, but I cannot seem to figure out why it does not work with the compositor active.</p>
<p>When I run my program to set the wallpaper (with picom active,) it returns 0 (shown below)</p>
<pre class="lang-bash prettyprint-override"><code>~ via λ 9.4.2
❯ qzbg -t ~/.wallpaper/sub/haskell_gray.jpg
Set wallpaper: 0
</code>```

I am assuming that picom adds a layer to the desktop, though I'm not sure exactly how that works for overwriting it.

Body:
I've been trying to learn both Imlib & X11, as I've been working on a project that includes both of them, and I've came across a weird issue with it. Basically, whenever I try to render my wallpaper, it will just do it "in the background," and will only show when I kill off my compositor (feh.) When I use programs like feh or xsetroot, they are both able to draw over picom, but my code cannot for some reason. I have a wrapper over it written in haskell, but I will omit that for simplicity. Here is the code I've been working with:

#include <X11/Xlib.h>
#include <Imlib2.h>
#include <stdio.h>
#include <stdlib.h>
static void
die(int err, char *msg)
{
    fprintf(stderr, "%s: %s\n", "qzbg", msg);
    exit(err);
}

struct dSize {
    uint32_t w;
    uint32_t h;
};

struct System {
    Display *dpy;
    Screen *screen;
    Window root;
    uint32_t screen_count;
};

static inline struct dSize
get_display_size()
{
    struct dSize x;
    Display *dpy = XOpenDisplay(NULL);
    if (!dpy) {
        die (-1, "Failed to open display.");
    }
    Screen *screen = DefaultScreenOfDisplay(dpy);
    if (!screen) {
        die (-1, "Failed to obtain the default screen.");
    }
    x.w = screen->width;
    x.h = screen->height;
    return x;
}

static void
set_wallpaper(int h, int w, struct System sys)
{
    Pixmap pix;

    sys.dpy = XOpenDisplay(NULL);

    sys.screen_count = DefaultScreen(sys.dpy);
    sys.root = RootWindow(sys.dpy, sys.screen_count);

    pix = XCreatePixmap(sys.dpy, sys.root,
                        h, w,
                        DefaultDepth(sys.dpy, sys.screen_count));

    imlib_context_set_display(sys.dpy);
    imlib_context_set_visual(DefaultVisual(sys.dpy, sys.screen_count));
    imlib_context_set_colormap(DefaultColormap(sys.dpy, sys.screen_count));
    imlib_context_set_drawable(pix);
    imlib_render_image_on_drawable(0, 0);

    XSetWindowBackgroundPixmap(sys.dpy, sys.root, pix);

    XClearWindow(sys.dpy, sys.root);

    while (XPending(sys.dpy)) {
        XEvent ev;
        XNextEvent(sys.dpy, &ev);
    }
    XFreePixmap(sys.dpy, pix);

    imlib_free_image_and_decache();

    XCloseDisplay(sys.dpy);
}
void
set_background(char *filename, struct System sys)
{
    Imlib_Image image;
    int img_w, img_h;

    image = imlib_load_image(filename);
    if (!image)
        die(-1, "Could not load image.");

    imlib_context_set_image(image);

    img_w = imlib_image_get_width();
    img_h = imlib_image_get_height();

    set_wallpaper(img_w, img_h, sys);
}

int
render(char *prog)
{
    struct dSize size = get_display_size();
    struct System sys;
    set_background(prog, sys);
}

The structs are just for convenience. I am able to render the image properly as my wallpaper whenever I don't have picom active, but I cannot seem to figure out why it does not work with the compositor active.

When I run my program to set the wallpaper (with picom active,) it returns 0 (shown below)

~ via λ 9.4.2
❯ qzbg -t ~/.wallpaper/sub/haskell_gray.jpg
Set wallpaper: 0

I am assuming that picom adds a layer to the desktop, though I'm not sure exactly how that works for overwriting it.


问:
NavigationView inside UIHostingController inside UITabBarController (SwiftUI inside objective C) adds gray bottom area
I have an app in Objectice C

I started to add some SwiftUI views

Everything works great but when I add a NavigationView inside the SwiftUI view automatically adds a gray space at the bottom that I cannot remove.

Other tabs that are in objective c dont have this space.
If I remove the NavigationView,  then the view automatically covers all the screen.

any idea what could it be ?

I tried with frame and safearea but no luck


问:
Laravel Backpack Inline Create not showing button to insert NEW ITEMS
I can't get the ADD NEW ITEM Button to that opens the modal with Inline create

But, strangely, in the primary class, I see the items that are related, inside a box, showed as buttons with an [x] to delete them.

Primary Class (FairCrudController.php)

namespace App\Http\Controllers\Admin;

use App\Http\Requests\FairRequest;
use Backpack\CRUD\app\Http\Controllers\CrudController;
use Backpack\CRUD\app\Library\CrudPanel\CrudPanelFacade as CRUD;

/**
 * Class FairCrudController
 * @package App\Http\Controllers\Admin
 * @property-read \Backpack\CRUD\app\Library\CrudPanel\CrudPanel $crud
 */
class FairCrudController extends CrudController
{
    use \Backpack\CRUD\app\Http\Controllers\Operations\ListOperation;
    use \Backpack\CRUD\app\Http\Controllers\Operations\CreateOperation;
    use \Backpack\CRUD\app\Http\Controllers\Operations\InlineCreateOperation;
    use \Backpack\CRUD\app\Http\Controllers\Operations\UpdateOperation;
    use \Backpack\CRUD\app\Http\Controllers\Operations\DeleteOperation;
    use \Backpack\CRUD\app\Http\Controllers\Operations\ShowOperation;

    use \Backpack\CRUD\app\Http\Controllers\Operations\FetchOperation;

    use \Backpack\CRUD\app\Http\Controllers\Operations\BulkDeleteOperation;

    use \Backpack\EditableColumns\Http\Controllers\Operations\MinorUpdateOperation;

    /**
     * Configure the CrudPanel object. Apply settings to all operations.
     *
     * @return void
     */
    public function setup()
    {
        CRUD::setModel(\App\Models\Fair::class);
        CRUD::setRoute(config('backpack.base.route_prefix') . '/fair');
        CRUD::setEntityNameStrings('feria', 'Ferias');
    }

    /**
     * Define what happens when the List operation is loaded.
     *
     * @see  https://backpackforlaravel.com/docs/crud-operation-list-entries
     * @return void
     */
    protected function setupListOperation()
    {
        CRUD::addColumn([
            'name'             => 'name',
            'type'             => 'editable_text',
            'label'            => 'Nombre',
            'underlined'       => true,
            'min_width'        => '120px',
            'select_on_click'  => false,
            'save_on_focusout' => false,
            'auto_update_row' => true,
          ]);

        CRUD::column('hero_image')->label('Imagen')->type('image');
        CRUD::column('start_at')->label('Empieza');
        CRUD::column('end_at')->label('Termina');
        CRUD::column('date_limit')->label('Límite');
        CRUD::addColumn([
          'name'  => 'status',
          'label' => 'Activada',
          'type'  => 'editable_switch',
          'color'   => 'success',
          'onLabel' => '✓',
          'offLabel' => '✕',
        ]);

        $this->crud->enableBulkActions();
        $this->crud->setDefaultPageLength(100);

        $this->crud->orderBy('start_at', 'DESC');
    }

    /**
     * Define what happens when the Create operation is loaded.
     *
     * @see https://backpackforlaravel.com/docs/crud-operation-create
     * @return void
     */
    protected function setupCreateOperation()
    {
        CRUD::setValidation(FairRequest::class);

        CRUD::field('name')->label('Nombre');
        CRUD::field('website')->label('Sitio Web');
        CRUD::field('invoice_prefix')->label('Prefijo de Facturas');
        CRUD::field('address')->label('Dirección');
        CRUD::field('city')->label('Ciudad');
        CRUD::field('state')->label('Estado/Provincia');
        CRUD::field('zip_code')->label('Código Postal');
        CRUD::field('country')->label('Pais');
        CRUD::field('contactperson')->type('relationship')->label('Personas de Contacto');
        CRUD::field('contact_persons_copy')->label('Poner en copia de los emails (separados por punto y coma)');
        CRUD::field('start_at')->label('Comienza');
        CRUD::field('end_at')->label('Termina');
        CRUD::field('date_limit')->label('Límite');
        $this->crud->addField([
            'label' => "Imagen de Presentación",
            'name' => "hero_image",
            'type' => 'image',
            'crop' => true,
            'aspect_ratio' => 0,
        ]);
        $this->crud->addField([
            'type' => "relationship",
            'name' => 'images',
            'label' => 'Imágenes',
            'ajax' => true,
            'inline_create' => true,
        ]);
        $this->crud->addField([
            'type' => "relationship",
            'name' => 'dossiers',
            'ajax' => true,
            'inline_create' => [ 'entity' => 'dossier' ],
            'data_source' => backpack_url('fair/fetch/dossier')
        ]);
        $this->crud->addField([
            'type' => "relationship",
            'name' => 'newsletters',
            'ajax' => true,
            'inline_create' => true,
        ]);
        CRUD::field('stands')->type('relationship')->label('Stands');
        CRUD::field('status')->label('Activa')->default(1);
    }

    /**
     * Define what happens when the Update operation is loaded.
     *
     * @see https://backpackforlaravel.com/docs/crud-operation-update
     * @return void
     */
    protected function setupUpdateOperation()
    {
        $this->setupCreateOperation();
    }

    /**
     * Define what happens when the View operation is loaded.
     *
     * @see https://backpackforlaravel.com/docs/5.x/crud-operation-show
     * @return void
     */
    protected function setupShowOperation()
    {
        CRUD::column('name')->label('Nombre');
        CRUD::column('website')->label('Sitio Web');
        CRUD::column('invoice_prefix')->label('Prefijo de Facturas');
        CRUD::column('address')->label('Dirección');
        CRUD::column('city')->label('Ciudad');
        CRUD::column('state')->label('Estado/Provincia');
        CRUD::column('zip_code')->label('Código Postal');
        CRUD::column('country')->label('Pais');
        CRUD::column('contact_persons_copy')->label('Poner en copia de los emails (separados por punto y coma)');
        CRUD::column('start_at')->label('Comienza');
        CRUD::column('end_at')->label('Termina');
        CRUD::column('date_limit')->label('Límite');

        CRUD::column('hero_image')->label('Imagen')->type('image');

        CRUD::column('status')->label('Activada')->type('check');
    }

    public function setupInlineCreateOperation() {
        $this->setupCreateOperation();
    }

    protected function fetchDossier()
    {
        return $this->fetch(\App\Models\Dossier::class);
    }
}

```
<p>Secondary Class (DossierCrudController.php)</p>
<pre class="lang-php prettyprint-override"><code>namespace App\Http\Controllers\Admin;

use App\Http\Requests\DossierRequest;
use Backpack\CRUD\app\Http\Controllers\CrudController;
use Backpack\CRUD\app\Library\CrudPanel\CrudPanelFacade as CRUD;

/**
 * Class DossierCrudController
 * @package App\Http\Controllers\Admin
 * @property-read \Backpack\CRUD\app\Library\CrudPanel\CrudPanel $crud
 */
class DossierCrudController extends CrudController
{
    use \Backpack\CRUD\app\Http\Controllers\Operations\ListOperation;
    use \Backpack\CRUD\app\Http\Controllers\Operations\CreateOperation;
    use \Backpack\CRUD\app\Http\Controllers\Operations\InlineCreateOperation;
    use \Backpack\CRUD\app\Http\Controllers\Operations\UpdateOperation;
    use \Backpack\CRUD\app\Http\Controllers\Operations\DeleteOperation;
    use \Backpack\CRUD\app\Http\Controllers\Operations\ShowOperation;

    use \Backpack\CRUD\app\Http\Controllers\Operations\BulkDeleteOperation;

    use \Backpack\EditableColumns\Http\Controllers\Operations\MinorUpdateOperation;

    /**
     * Configure the CrudPanel object. Apply settings to all operations.
     *
     * @return void
     */
    public function setup()
    {
        CRUD::setModel(\App\Models\Dossier::class);
        CRUD::setRoute(config('backpack.base.route_prefix') . '/dossier');
        CRUD::setEntityNameStrings('dossier de la feria', 'dossiers de la feria');
    }

    /**
     * Define what happens when the List operation is loaded.
     *
     * @see  https://backpackforlaravel.com/docs/crud-operation-list-entries
     * @return void
     */
    protected function setupListOperation()
    {
        CRUD::addColumn([
            'name'    => 'fair_id',
            'label'   => 'Feria',
            'type'    => 'editable_select',
            'options' => \App\Models\Fair::all()->pluck('name', 'id')->toArray(),
            'underlined'       => true,
            'save_on_focusout' => true,
            'save_on_change'   => true,
            'auto_update_row' => true,
          ]);

        CRUD::addColumn([
            'name'             => 'name',
            'type'             => 'editable_text',
            'label'            => 'Nombre',
            'underlined'       => true,
            'min_width'        => '120px',
            'select_on_click'  => false,
            'save_on_focusout' => false,
            'auto_update_row' => true,
          ]);
          CRUD::addColumn([
            'name'  => 'status',
            'label' => 'Activado',
            'type'  => 'editable_switch',
            'color'   => 'success',
            'onLabel' => '✓',
            'offLabel' => '✕',
          ]);

          $this->crud->enableBulkActions();
          $this->crud->setDefaultPageLength(100);

          $this->crud->orderBy('fair_id', 'ASC');
    }

    /**
     * Define what happens when the Create operation is loaded.
     *
     * @see https://backpackforlaravel.com/docs/crud-operation-create
     * @return void
     */
    protected function setupCreateOperation()
    {
        CRUD::setValidation(DossierRequest::class);

        CRUD::field('fair')->type('select')->label('Feria');
        CRUD::field('name')->label('Nombre');
        CRUD::field('status')->label('Activo')->default(1);
        $this->crud->addField([
            'label' => "Archivo (Tamaño: 16MB máx.)",
            'name' => "file",
            'upload' => true,
            'type' => 'upload',
        ]);
    }

    /**
     * Define what happens when the Update operation is loaded.
     *
     * @see https://backpackforlaravel.com/docs/crud-operation-update
     * @return void
     */
    protected function setupUpdateOperation()
    {
        $this->setupCreateOperation();
    }

    protected function setupShowOperation()
    {
        CRUD::column('fair')->label('Feria');
        CRUD::column('name')->label('Nombre');
        CRUD::column('file')->label('Archivo')->type('file');
        CRUD::column('status')->label('Activado')->type('check');
    }

    public function setupInlineCreateOperation() {
        $this->setupCreateOperation();
    }

}
</code>```

/routes/backpack/custom.php

....
Route::get('fair/fetch/dossier', [DossierCrudController::class, "fetchDossier"]);
....
```
<p>Fair.php Model</p>
<pre class="lang-php prettyprint-override"><code>use App\Models\Dossier;
...
    public function dossiers()
    {
        return $this->hasMany(Dossier::class);
    }
....
</code>```

Dossier.php Model

use App\Models\Fair;
...
    public function fair()
    {
        return $this->belongsTo(Fair::class);
    }
....
```

Body:
I can't get the ADD NEW ITEM Button to that opens the modal with Inline create

But, strangely, in the primary class, I see the items that are related, inside a box, showed as buttons with an [x] to delete them.

Primary Class (FairCrudController.php)

namespace App\Http\Controllers\Admin;

use App\Http\Requests\FairRequest;
use Backpack\CRUD\app\Http\Controllers\CrudController;
use Backpack\CRUD\app\Library\CrudPanel\CrudPanelFacade as CRUD;

/**
 * Class FairCrudController
 * @package App\Http\Controllers\Admin
 * @property-read \Backpack\CRUD\app\Library\CrudPanel\CrudPanel $crud
 */
class FairCrudController extends CrudController
{
    use \Backpack\CRUD\app\Http\Controllers\Operations\ListOperation;
    use \Backpack\CRUD\app\Http\Controllers\Operations\CreateOperation;
    use \Backpack\CRUD\app\Http\Controllers\Operations\InlineCreateOperation;
    use \Backpack\CRUD\app\Http\Controllers\Operations\UpdateOperation;
    use \Backpack\CRUD\app\Http\Controllers\Operations\DeleteOperation;
    use \Backpack\CRUD\app\Http\Controllers\Operations\ShowOperation;

    use \Backpack\CRUD\app\Http\Controllers\Operations\FetchOperation;

    use \Backpack\CRUD\app\Http\Controllers\Operations\BulkDeleteOperation;

    use \Backpack\EditableColumns\Http\Controllers\Operations\MinorUpdateOperation;

    /**
     * Configure the CrudPanel object. Apply settings to all operations.
     *
     * @return void
     */
    public function setup()
    {
        CRUD::setModel(\App\Models\Fair::class);
        CRUD::setRoute(config('backpack.base.route_prefix') . '/fair');
        CRUD::setEntityNameStrings('feria', 'Ferias');
    }

    /**
     * Define what happens when the List operation is loaded.
     *
     * @see  https://backpackforlaravel.com/docs/crud-operation-list-entries
     * @return void
     */
    protected function setupListOperation()
    {
        CRUD::addColumn([
            'name'             => 'name',
            'type'             => 'editable_text',
            'label'            => 'Nombre',
            'underlined'       => true,
            'min_width'        => '120px',
            'select_on_click'  => false,
            'save_on_focusout' => false,
            'auto_update_row' => true,
          ]);

        CRUD::column('hero_image')->label('Imagen')->type('image');
        CRUD::column('start_at')->label('Empieza');
        CRUD::column('end_at')->label('Termina');
        CRUD::column('date_limit')->label('Límite');
        CRUD::addColumn([
          'name'  => 'status',
          'label' => 'Activada',
          'type'  => 'editable_switch',
          'color'   => 'success',
          'onLabel' => '✓',
          'offLabel' => '✕',
        ]);

        $this->crud->enableBulkActions();
        $this->crud->setDefaultPageLength(100);

        $this->crud->orderBy('start_at', 'DESC');
    }

    /**
     * Define what happens when the Create operation is loaded.
     *
     * @see https://backpackforlaravel.com/docs/crud-operation-create
     * @return void
     */
    protected function setupCreateOperation()
    {
        CRUD::setValidation(FairRequest::class);

        CRUD::field('name')->label('Nombre');
        CRUD::field('website')->label('Sitio Web');
        CRUD::field('invoice_prefix')->label('Prefijo de Facturas');
        CRUD::field('address')->label('Dirección');
        CRUD::field('city')->label('Ciudad');
        CRUD::field('state')->label('Estado/Provincia');
        CRUD::field('zip_code')->label('Código Postal');
        CRUD::field('country')->label('Pais');
        CRUD::field('contactperson')->type('relationship')->label('Personas de Contacto');
        CRUD::field('contact_persons_copy')->label('Poner en copia de los emails (separados por punto y coma)');
        CRUD::field('start_at')->label('Comienza');
        CRUD::field('end_at')->label('Termina');
        CRUD::field('date_limit')->label('Límite');
        $this->crud->addField([
            'label' => "Imagen de Presentación",
            'name' => "hero_image",
            'type' => 'image',
            'crop' => true,
            'aspect_ratio' => 0,
        ]);
        $this->crud->addField([
            'type' => "relationship",
            'name' => 'images',
            'label' => 'Imágenes',
            'ajax' => true,
            'inline_create' => true,
        ]);
        $this->crud->addField([
            'type' => "relationship",
            'name' => 'dossiers',
            'ajax' => true,
            'inline_create' => [ 'entity' => 'dossier' ],
            'data_source' => backpack_url('fair/fetch/dossier')
        ]);
        $this->crud->addField([
            'type' => "relationship",
            'name' => 'newsletters',
            'ajax' => true,
            'inline_create' => true,
        ]);
        CRUD::field('stands')->type('relationship')->label('Stands');
        CRUD::field('status')->label('Activa')->default(1);
    }

    /**
     * Define what happens when the Update operation is loaded.
     *
     * @see https://backpackforlaravel.com/docs/crud-operation-update
     * @return void
     */
    protected function setupUpdateOperation()
    {
        $this->setupCreateOperation();
    }

    /**
     * Define what happens when the View operation is loaded.
     *
     * @see https://backpackforlaravel.com/docs/5.x/crud-operation-show
     * @return void
     */
    protected function setupShowOperation()
    {
        CRUD::column('name')->label('Nombre');
        CRUD::column('website')->label('Sitio Web');
        CRUD::column('invoice_prefix')->label('Prefijo de Facturas');
        CRUD::column('address')->label('Dirección');
        CRUD::column('city')->label('Ciudad');
        CRUD::column('state')->label('Estado/Provincia');
        CRUD::column('zip_code')->label('Código Postal');
        CRUD::column('country')->label('Pais');
        CRUD::column('contact_persons_copy')->label('Poner en copia de los emails (separados por punto y coma)');
        CRUD::column('start_at')->label('Comienza');
        CRUD::column('end_at')->label('Termina');
        CRUD::column('date_limit')->label('Límite');

        CRUD::column('hero_image')->label('Imagen')->type('image');

        CRUD::column('status')->label('Activada')->type('check');
    }

    public function setupInlineCreateOperation() {
        $this->setupCreateOperation();
    }

    protected function fetchDossier()
    {
        return $this->fetch(\App\Models\Dossier::class);
    }
}

Secondary Class (DossierCrudController.php)

namespace App\Http\Controllers\Admin;

use App\Http\Requests\DossierRequest;
use Backpack\CRUD\app\Http\Controllers\CrudController;
use Backpack\CRUD\app\Library\CrudPanel\CrudPanelFacade as CRUD;

/**
 * Class DossierCrudController
 * @package App\Http\Controllers\Admin
 * @property-read \Backpack\CRUD\app\Library\CrudPanel\CrudPanel $crud
 */
class DossierCrudController extends CrudController
{
    use \Backpack\CRUD\app\Http\Controllers\Operations\ListOperation;
    use \Backpack\CRUD\app\Http\Controllers\Operations\CreateOperation;
    use \Backpack\CRUD\app\Http\Controllers\Operations\InlineCreateOperation;
    use \Backpack\CRUD\app\Http\Controllers\Operations\UpdateOperation;
    use \Backpack\CRUD\app\Http\Controllers\Operations\DeleteOperation;
    use \Backpack\CRUD\app\Http\Controllers\Operations\ShowOperation;

    use \Backpack\CRUD\app\Http\Controllers\Operations\BulkDeleteOperation;

    use \Backpack\EditableColumns\Http\Controllers\Operations\MinorUpdateOperation;

    /**
     * Configure the CrudPanel object. Apply settings to all operations.
     *
     * @return void
     */
    public function setup()
    {
        CRUD::setModel(\App\Models\Dossier::class);
        CRUD::setRoute(config('backpack.base.route_prefix') . '/dossier');
        CRUD::setEntityNameStrings('dossier de la feria', 'dossiers de la feria');
    }

    /**
     * Define what happens when the List operation is loaded.
     *
     * @see  https://backpackforlaravel.com/docs/crud-operation-list-entries
     * @return void
     */
    protected function setupListOperation()
    {
        CRUD::addColumn([
            'name'    => 'fair_id',
            'label'   => 'Feria',
            'type'    => 'editable_select',
            'options' => \App\Models\Fair::all()->pluck('name', 'id')->toArray(),
            'underlined'       => true,
            'save_on_focusout' => true,
            'save_on_change'   => true,
            'auto_update_row' => true,
          ]);

        CRUD::addColumn([
            'name'             => 'name',
            'type'             => 'editable_text',
            'label'            => 'Nombre',
            'underlined'       => true,
            'min_width'        => '120px',
            'select_on_click'  => false,
            'save_on_focusout' => false,
            'auto_update_row' => true,
          ]);
          CRUD::addColumn([
            'name'  => 'status',
            'label' => 'Activado',
            'type'  => 'editable_switch',
            'color'   => 'success',
            'onLabel' => '✓',
            'offLabel' => '✕',
          ]);

          $this->crud->enableBulkActions();
          $this->crud->setDefaultPageLength(100);

          $this->crud->orderBy('fair_id', 'ASC');
    }

    /**
     * Define what happens when the Create operation is loaded.
     *
     * @see https://backpackforlaravel.com/docs/crud-operation-create
     * @return void
     */
    protected function setupCreateOperation()
    {
        CRUD::setValidation(DossierRequest::class);

        CRUD::field('fair')->type('select')->label('Feria');
        CRUD::field('name')->label('Nombre');
        CRUD::field('status')->label('Activo')->default(1);
        $this->crud->addField([
            'label' => "Archivo (Tamaño: 16MB máx.)",
            'name' => "file",
            'upload' => true,
            'type' => 'upload',
        ]);
    }

    /**
     * Define what happens when the Update operation is loaded.
     *
     * @see https://backpackforlaravel.com/docs/crud-operation-update
     * @return void
     */
    protected function setupUpdateOperation()
    {
        $this->setupCreateOperation();
    }

    protected function setupShowOperation()
    {
        CRUD::column('fair')->label('Feria');
        CRUD::column('name')->label('Nombre');
        CRUD::column('file')->label('Archivo')->type('file');
        CRUD::column('status')->label('Activado')->type('check');
    }

    public function setupInlineCreateOperation() {
        $this->setupCreateOperation();
    }

}

/routes/backpack/custom.php

....
Route::get('fair/fetch/dossier', [DossierCrudController::class, "fetchDossier"]);
....

Fair.php Model

use App\Models\Dossier;
...
    public function dossiers()
    {
        return $this->hasMany(Dossier::class);
    }
....

Dossier.php Model

use App\Models\Fair;
...
    public function fair()
    {
        return $this->belongsTo(Fair::class);
    }
....


问:
Intel PIN misses RTN_InsertCall at certain positions (instrumenting malloc function)
I was testing the malloctrace example shown on the official Intel PIN website: https://software.intel.com/sites/landingpage/pintool/docs/98484/Pin/html/index.html#FunctionArguments

I have a very simple testing binary file with the source code of:

```<code>
int main()
{
    char *buf = malloc(sizeof(char)*50);
    //printf("Buf addr: %p\n", buf); // sanity check
    char *bar_buf = malloc(sizeof(char)*50);
    //printf("Bar_buf addr: %p\n", bar_buf); // sanity check
    free(buf);
    free(bar_buf);
}
</code>```

Upon executing the above malloctrace example with this simple binary file, the output looks like this:

```<code>...
malloc(0x32) <- first malloc
malloc(0x32) <- second malloc
  returns 0x55cb2b4222e0
free(0x55cb2b4222a0) <- free of first malloc
free(0x55cb2b4222e0) <- free of second malloc
</code>```

Interestingly enough, for whatever reason, the first malloc does not return the address it obtains from the malloc call, similar to what is shown for the second malloc.

What I am expecting is the return value for the first malloc is 0x55cb2b4222a0 as that is the input argument to the free(buf) for the test source code.

I have done some additional instrumentation and testing (such as checking all read/write to the memory location) to conclude that this is simply that Intel PIN cannot find the proper instrumentation point to insert the profiling code after the first malloc, but I was nevertheless wondering if anyone else had to face this issue, and potentially know the solution to solving this "missing instrumentation" problem.

Body:
I was testing the malloctrace example shown on the official Intel PIN website: https://software.intel.com/sites/landingpage/pintool/docs/98484/Pin/html/index.html#FunctionArguments

I have a very simple testing binary file with the source code of:

int main()
{
    char *buf = malloc(sizeof(char)*50);
    //printf("Buf addr: %p\n", buf); // sanity check
    char *bar_buf = malloc(sizeof(char)*50);
    //printf("Bar_buf addr: %p\n", bar_buf); // sanity check
    free(buf);
    free(bar_buf);
}

Upon executing the above malloctrace example with this simple binary file, the output looks like this:

...
malloc(0x32) <- first malloc
malloc(0x32) <- second malloc
  returns 0x55cb2b4222e0
free(0x55cb2b4222a0) <- free of first malloc
free(0x55cb2b4222e0) <- free of second malloc

Interestingly enough, for whatever reason, the first malloc does not return the address it obtains from the malloc call, similar to what is shown for the second malloc.

What I am expecting is the return value for the first malloc is 0x55cb2b4222a0 as that is the input argument to the free(buf) for the test source code.

I have done some additional instrumentation and testing (such as checking all read/write to the memory location) to conclude that this is simply that Intel PIN cannot find the proper instrumentation point to insert the profiling code after the first malloc, but I was nevertheless wondering if anyone else had to face this issue, and potentially know the solution to solving this "missing instrumentation" problem.


问:
How to make a for loop comparing one column of a dataframe to the rest of the columns of the dataframe?
I've been trying to make a for loop that gives me a graph comparing an independent variable, called Status (type of gene mutated) to 64 other dependent variables. I want the for loop to create one graph per dependent variable, comparing Status to each dependant variable on my dataframe.

Status is the name of one column, and I want to compare Status (x axis) with the rest of the columns (y axis):

I have a for loop that I attempted to construct here, but whenever I open the pdf that it gives me all I get is a blank graph.

```<code>pdf("Leuk_Frac.pdf")

FORLOOP2 = for(i in 5:ncol(Leuk_Frac)){
  print(ggplot(Leuk_Frac, aes(x = unlist(Status), y = unlist(Leuk_Frac[,i]), fill = Status)))+
    geom_violin()+
    geom_boxplot()+
    xlab("Status")+
    ylab(colnames(Leuk_Frac[i]))+
    stat_cor(method = "pearson", label.x = 0, label.y = 0)
}

</code>```

What am I doing wrong?

There are multiple things that go wrong - the y axis on the graphs come out as "Leuk_frac[i]" which is obviously not intended, how can I fix this?
The graphs are empty, there is no data on them, why is this?
This is my first time asking a question on here, what else could I have put?

Body:
I've been trying to make a for loop that gives me a graph comparing an independent variable, called Status (type of gene mutated) to 64 other dependent variables. I want the for loop to create one graph per dependent variable, comparing Status to each dependant variable on my dataframe.

Status is the name of one column, and I want to compare Status (x axis) with the rest of the columns (y axis):

I have a for loop that I attempted to construct here, but whenever I open the pdf that it gives me all I get is a blank graph.

pdf("Leuk_Frac.pdf")

FORLOOP2 = for(i in 5:ncol(Leuk_Frac)){
  print(ggplot(Leuk_Frac, aes(x = unlist(Status), y = unlist(Leuk_Frac[,i]), fill = Status)))+
    geom_violin()+
    geom_boxplot()+
    xlab("Status")+
    ylab(colnames(Leuk_Frac[i]))+
    stat_cor(method = "pearson", label.x = 0, label.y = 0)
}

What am I doing wrong?

There are multiple things that go wrong - the y axis on the graphs come out as "Leuk_frac[i]" which is obviously not intended, how can I fix this?
The graphs are empty, there is no data on them, why is this?
This is my first time asking a question on here, what else could I have put?


问:
Using Paste command in Delphi OleContainer (MS Word)
I have an application working with MS Word (2007) OleContainer in Delphi 10.2.
I copy/paste an image on it with following command:

Copy:

```<code>  vBmp:=iAssinatura.Picture.Bitmap;
  Clipboard.Assign(vBmp);
  Clip:=1;
</code>```

Paste:

```<code>  dm.WordApp.ActiveDocument.ActiveWindow.Selection.Paste;
</code>```

(I tryed this as well: dm.WordApp.Selection.Paste;)

However, when the PC runs MS Word 2016 or higher, paste commands (both above) return the following errors:
"The remote procedure call failed" and "RPC server is unavailable"

I tryed declare Uses Office2010 and Word20100 instead Office2000 and Word2000, but without success.
Has anyone experienced this problem and could help me to fix it?

Body:
I have an application working with MS Word (2007) OleContainer in Delphi 10.2.
I copy/paste an image on it with following command:

Copy:

  vBmp:=iAssinatura.Picture.Bitmap;
  Clipboard.Assign(vBmp);
  Clip:=1;

Paste:

  dm.WordApp.ActiveDocument.ActiveWindow.Selection.Paste;

(I tryed this as well: dm.WordApp.Selection.Paste;)

However, when the PC runs MS Word 2016 or higher, paste commands (both above) return the following errors:
"The remote procedure call failed" and "RPC server is unavailable"

I tryed declare Uses Office2010 and Word20100 instead Office2000 and Word2000, but without success.
Has anyone experienced this problem and could help me to fix it?


问:
Kotlin Sealed Class Inheritance
I'm using Kotlin Sealed Class for state management in Android.

```<code>sealed class StateA {
    data class State1(val s: String)
    object State2
    object State3
}
</code>```

Now I need another Sealed Class for state management which shared a few states with StateA class.

```<code>sealed class StateB {
    data class State1(val s: String)
    object State2
    object State4
}
</code>```

data class State1 and object State2 are identical in both Sealed Classes. I'm wondering if I can introduce an Inheritance (something like abstract classes) that both could share the states. Something like

```<code>sealed class SuperState {
    data class State1(val s: String)
    object State2
}
sealed class StateA: SuperState() {
    object State3
}

sealed class StateB: SuperState() {
    object State4
}
</code>```

Unfortunately, this doesn't work and I can't access for example StateA.State1.
Is there a solution for this?

Title: Kotlin Sealed Class Inheritance

Body:
I'm using Kotlin Sealed Class for state management in Android.

sealed class StateA {
    data class State1(val s: String)
    object State2
    object State3
}

Now I need another Sealed Class for state management which shared a few states with StateA class.

sealed class StateB {
    data class State1(val s: String)
    object State2
    object State4
}

data class State1 and object State2 are identical in both Sealed Classes. I'm wondering if I can introduce an Inheritance (something like abstract classes) that both could share the states. Something like

sealed class SuperState {
    data class State1(val s: String)
    object State2
}
sealed class StateA: SuperState() {
    object State3
}

sealed class StateB: SuperState() {
    object State4
}

Unfortunately, this doesn't work and I can't access for example StateA.State1.
Is there a solution for this?


问:
How to GET campaign activity ID Constant Contact on Make/Integromat?
I have created an Integromat scenario where the automation creates a new contact, then creates an email campaign and then schedules an email campaign for Constant Contact. To schedule an email you need the campaign activity ID. The GET API Call should retrieve the data with the campaign activity ID, the only problem is when I make a GET API call, the Campaign Activity ID is not returning. Is there anyone with thoughts on how to retrieve the campaign activity ID?

Here is the error I get


问:
web server http request not always showing same result

function get_comic_from_xkcd() {
    stream_context_set_default( [
        'ssl' => [
            'verify_peer' => false,
            'verify_peer_name' => false,
        ],
    ]);
    $url = 'https://c.xkcd.com/random/comic/';
    try {
        $head  = get_headers( $url );
        $comic_link = $head[8];
        preg_match( '/[0-9]+/', $comic_link,$matches);
        $rand_comic = $matches[0];

    } catch (\Throwable$th) {
        print($th->getMessage());
    }

    $url    = 'https://xkcd.com/' . $rand_comic . '/info.0.json';
    $result = json_decode( file_get_contents( $url ), true );
    return $result;
}
```

i have a task to get random xkcd comics every time. i have created above code its working fine on my local server but after uploading to webhosting platform i always get same result after every refresh. how can i get unique result on my web sever.

Body:
function get_comic_from_xkcd() {
    stream_context_set_default( [
        'ssl' => [
            'verify_peer' => false,
            'verify_peer_name' => false,
        ],
    ]);
    $url = 'https://c.xkcd.com/random/comic/';
    try {
        $head  = get_headers( $url );
        $comic_link = $head[8];
        preg_match( '/[0-9]+/', $comic_link,$matches);
        $rand_comic = $matches[0];

    } catch (\Throwable$th) {
        print($th->getMessage());
    }

    $url    = 'https://xkcd.com/' . $rand_comic . '/info.0.json';
    $result = json_decode( file_get_contents( $url ), true );
    return $result;
}

i have a task to get random xkcd comics every time. i have created above code its working fine on my local server but after uploading to webhosting platform i always get same result after every refresh. how can i get unique result on my web sever.