AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / 问题

All perguntas(coding)

Martin Hope
Salvador
Asked: 2025-04-08 05:45:30 +0800 CST

Como adicionar um mapa personalizado ao addMiniMap?

  • 6

Gostaria de usar um mapa diferente em addMiniMap() do que na janela principal do folheto. Como posso fazer isso? Por exemplo, quero exibi-lo CartoDB.Positronna janela principal e Esri.NatGeoWorldMapna janela addMiniMap.

leaflet() |>
  addProviderTiles(providers$CartoDB.Positron) %>%
  setView(lng = 13.4, lat = 52.52, zoom = 14) %>%
  addMiniMap(width = 150, height = 180, "topleft") %>%
  addProviderTiles(providers$Esri.NatGeoWorldMap)

Tentei usar a addMiniMapfunção natGeoWorldMap dentro, mas não obtive sucesso.

  • 1 respostas
  • 32 Views
Martin Hope
JH Park
Asked: 2025-04-08 05:38:53 +0800 CST

Extraindo strings de um arquivo com sed e expressões regulares

  • 8

Gostaria de perguntar sobre como extrair strings específicas de um arquivo usando sed e expressões regulares.

Abaixo está o exemplo do arquivo de texto de entrada (testfile.txt):

# This file contains a short description of the columns in the
# meta-analysis summary file, named '/some/output/directory/result.txt'

# (Skipping some comment lines...)

# Input for this meta-analysis was stored in the files:
# --> Input File 1 : /some/input/directory/cohort1/dataset1_chrAll.regenie.txt
# --> Input File 2 : /some/input/directory/cohort2/subdir1/chrAll-out.txt
# --> Input File 3 : /some/input/directory/cohort2/subdir2/chrAll-out_ver2.txt
# --> Input File 4 : /some/input/directory/cohort3/resfile.txt
# --> Input File 5 : /some/input/directory/cohort4/regenie_res_chrAll.txt

Deste arquivo, gostaria de extrair a lista de nomes de arquivos de entrada, então o resultado deve ser algo como:

/some/input/directory/cohort1/dataset1_chrAll.regenie.txt
/some/input/directory/cohort2/subdir1/chrAll-out.txt
/some/input/directory/cohort2/subdir2/chrAll-out_ver2.txt
/some/input/directory/cohort3/resfile.txt
/some/input/directory/cohort4/regenie_res_chrAll.txt

Veja abaixo o que eu tentei:

Tentativa 1

Este é o comando inicial que usei.

cat testfile.txt | sed -e 's/\/some\/input\/directory\/([A-z0-9\/\.\-]*)\.txt/$1/g'

Resultado:

sed: -e expression #1, char 55: Invalid range end

Tentativa 2

Depois de alguma pesquisa, tentei escapar dos parênteses usando barras invertidas.

cat testfile.txt | sed -e 's/\/some\/input\/directory\/\([A-z0-9\/\.\-]*\).txt/$1/g'

Resultado:

sed: -e expression #1, char 56: Invalid range end

Então isso não resolveu o problema.

Tentativa 3

Também tentei escapar dos colchetes.

cat testfile.txt | sed -e 's/\/some\/input\/directory\/\(\[A-z0-9\/\.\-\]\*\)\.txt/$1/g'

Resultado:

# This file contains a short description of the columns in the
# meta-analysis summary file, named '/some/output/directory/result.txt'

# (Skipping some comment lines...)

# Input for this meta-analysis was stored in the files:
# --> Input File 1 : /some/input/directory/cohort1/dataset1_chrAll.regenie.txt
# --> Input File 2 : /some/input/directory/cohort2/subdir1/chrAll-out.txt
# --> Input File 3 : /some/input/directory/cohort2/subdir2/chrAll-out_ver2.txt
# --> Input File 4 : /some/input/directory/cohort3/resfile.txt
# --> Input File 5 : /some/input/directory/cohort4/regenie_res_chrAll.txt

Isso não gerou um erro, mas não era isso que eu queria.

Tentativa 4

Por fim, tentei adicionar a opção -r sem escapar parênteses ou colchetes.

cat testfile.txt | sed -re 's/\/some\/input\/directory\/([A-z0-9\/\.\-]*)\.txt/$1/g'

Resultado:

sed: -e expression #1, char 55: Invalid range end

Apareceu a mesma mensagem de erro na primeira tentativa.

Gostaria de perguntar quais são os problemas nas minhas linhas de comando e se há alguma solução possível para isso.

Obrigado.

regex
  • 5 respostas
  • 71 Views
Martin Hope
Luiz
Asked: 2025-04-08 05:28:56 +0800 CST

Como desenhar juntas arredondadas (côncavas e convexas) em um PictureBox?

  • 6

Estou tentando configurar uma barra de progresso com uma caixa de imagem. Ela tem 4 cores e cantos e centros arredondados. Já consegui configurar a caixa de imagem com as cores e cantos arredondados, mas não consigo fazer o centro.

Este é um exemplo do que estou tentando reproduzir:

exemplo do que estou tentando reproduzir

Isso é o que eu já consegui fazer:

isso é o que eu já consegui fazer

Este é o código que estou usando:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim pictureBox As New PictureBox()
    pictureBox.Size = New Size(280, 30)
    pictureBox.Location = New Point(10, 80)
    AddHandler pictureBox.Paint, AddressOf Me.PictureBox_Paint
    Me.Controls.Add(pictureBox)
End Sub

    Private Sub PictureBox_Paint(sender As Object, e As PaintEventArgs)
    Dim g As Graphics = e.Graphics
    g.SmoothingMode = SmoothingMode.AntiAlias ' Essencial para bordas suaves

    Dim pb As PictureBox = CType(sender, PictureBox)
    
    Dim area As Rectangle = pb.ClientRectangle
   
    Dim colors() As Color = {
        Color.FromArgb(85, 85, 135), 
        Color.FromArgb(217, 83, 79),  
        Color.FromArgb(240, 173, 78), 
        Color.FromArgb(91, 192, 222)  
    }
    Dim proportions() As Double = {0.25, 0.15, 0.35, 0.25}

    Dim totalWidth As Single = area.Width
    Dim totalHeight As Single = area.Height

    Dim cornerRadius As Single = CSng(Math.Min(totalWidth * 0.1, totalHeight / 2.0)) 
    If cornerRadius <= 0 Then cornerRadius = 1 

    Dim currentX As Single = area.X
    Dim numSegments As Integer = colors.Length

    
    For i As Integer = 0 To numSegments - 1
        Dim segmentWidth As Single
        If i = numSegments - 1 Then
            segmentWidth = (area.X + totalWidth) - currentX
        Else
            segmentWidth = CSng(totalWidth * proportions(i))
        End If

        If segmentWidth <= 0 Then Continue For

        Dim segmentRect As New RectangleF(currentX, area.Y, segmentWidth, totalHeight)

        Dim roundLeft As Boolean = (i = 0) 
        Dim roundRight As Boolean = (i = numSegments - 1) 

        Using segmentPath As GraphicsPath = CreateSegmentPath(segmentRect, cornerRadius, roundLeft, roundRight)
            Using segmentBrush As New SolidBrush(colors(i))
                g.FillPath(segmentBrush, segmentPath)
            End Using 
        End Using 

        currentX += segmentWidth
    Next
End Sub

Private Function CreateSegmentPath(rectF As RectangleF, radius As Single, makeLeftRound As Boolean, makeRightRound As Boolean) As GraphicsPath
    Dim path As New GraphicsPath()
    Dim diameter As Single = Math.Max(0, radius * 2) 

    If diameter > rectF.Width Then diameter = rectF.Width
    If diameter > rectF.Height Then diameter = rectF.Height
    radius = diameter / 2.0F 

    Dim Left As Single = rectF.Left
    Dim Top As Single = rectF.Top
    Dim Right As Single = rectF.Right
    Dim Bottom As Single = rectF.Bottom

    If radius <= 0 OrElse rectF.Width <= 0 OrElse rectF.Height <= 0 Then
        path.AddRectangle(rectF)
        Return path
    End If

    If makeLeftRound Then
        path.AddArc(Left, Top, diameter, diameter, 180, 90)
    Else
        ' Começa com uma linha reta no canto
        path.AddLine(Left, Top + radius, Left, Top) 
        path.AddLine(Left, Top, Left + radius, Top)
    End If

    path.AddLine(Left + radius, Top, Right - radius, Top)

    If makeRightRound Then
        path.AddArc(Right - diameter, Top, diameter, diameter, 270, 90)
    Else
        path.AddLine(Right - radius, Top, Right, Top) 
        path.AddLine(Right, Top, Right, Top + radius) 
    End If

    path.AddLine(Right, Top + radius, Right, Bottom - radius)

    If makeRightRound Then
        path.AddArc(Right - diameter, Bottom - diameter, diameter, diameter, 0, 90)
    Else
        path.AddLine(Right, Bottom - radius, Right, Bottom) ' Termina a linha direita
        path.AddLine(Right, Bottom, Right - radius, Bottom) ' Começa a linha inferior
    End If

    path.AddLine(Right - radius, Bottom, Left + radius, Bottom)

    If makeLeftRound Then
        path.AddArc(Left, Bottom - diameter, diameter, diameter, 90, 90)
    Else
        path.AddLine(Left + radius, Bottom, Left, Bottom) 
        path.AddLine(Left, Bottom, Left, Bottom - radius) 
    End If

    path.CloseFigure() 
    Return path
End Function

Agradeço qualquer ajuda para resolver este problema

Atualizar meu código:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim pictureBox As New PictureBox()
pictureBox.Size = New Size(280, 30)
pictureBox.Location = New Point(10, 80)
AddHandler pictureBox.Paint, AddressOf Me.PictureBox_Paint
Me.Controls.Add(pictureBox)

End Sub

Private Sub PictureBox_Paint(sender As Object, e As PaintEventArgs)
Dim g As Graphics = e.Graphics
g.SmoothingMode = SmoothingMode.AntiAlias

Dim pb As PictureBox = CType(sender, PictureBox)
Dim area As Rectangle = pb.ClientRectangle
Dim colors As New List(Of Color) From {
    Color.FromArgb(70, 71, 117), ' Produtivo
    Color.FromArgb(210, 50, 45), ' Não Produtivo
    Color.FromArgb(237, 156, 40), ' Atenção
    Color.FromArgb(91, 192, 222) ' Não Definido
}
Dim proportions As New List(Of Double) From {0.25, 0.15, 0.35, 0.25}

Dim totalWidth As Single = area.Width
Dim totalHeight As Single = area.Height
Dim cornerRadius As Single = CSng(Math.Min(totalWidth * 0.1, totalHeight / 2.0))
If cornerRadius <= 0 Then cornerRadius = 1

Dim currentX As Single = area.X
paths.Clear() ' Limpar a lista antes de adicionar novos caminhos

' Criar os caminhos para cada segmento
For i As Integer = 0 To colors.Count - 1
    Dim segmentWidth As Single = CSng(totalWidth * proportions(i))
    If segmentWidth <= 0 Then Continue For

    Dim segmentRect As New RectangleF(currentX, area.Y, segmentWidth, totalHeight)
    Dim roundLeft As Boolean = (i = 0)
    Dim roundRight As Boolean = (i = colors.Count - 1)

    Dim segmentPath As GraphicsPath = CreateSegmentPath(segmentRect, cornerRadius, roundLeft, roundRight)
    paths.Add(segmentPath)

    currentX += segmentWidth
Next

' Pintar os caminhos de trás para frente
For i As Integer = paths.Count - 1 To 0 Step -1
    Using segmentBrush As New SolidBrush(colors(i))
        g.FillPath(segmentBrush, paths(i))
    End Using
Next
End Sub

Private Function CreateSegmentPath(rectF As RectangleF, radius As Single, makeLeftRound As Boolean, makeRightRound As Boolean) As GraphicsPath
Dim path As New GraphicsPath()
Dim diameter As Single = Math.Max(0, radius * 2)

If diameter > rectF.Width Then diameter = rectF.Width
If diameter > rectF.Height Then diameter = rectF.Height
radius = diameter / 2.0F

Dim Left As Single = rectF.Left
Dim Top As Single = rectF.Top
Dim Right As Single = rectF.Right
Dim Bottom As Single = rectF.Bottom

If radius <= 0 OrElse rectF.Width <= 0 OrElse rectF.Height <= 0 Then
    path.AddRectangle(rectF)
    Return path
End If

' --- Construção do Caminho ---
' Canto Superior Esquerdo
If makeLeftRound Then
    path.AddArc(Left, Top, diameter, diameter, 180, 90)
Else
    ' Começa com uma linha reta no canto
    path.AddLine(Left, Top + radius, Left, Top) ' Garante o ponto inicial correto
    path.AddLine(Left, Top, Left + radius, Top)
End If

' Linha Superior (entre os cantos/arcos)
path.AddLine(Left + radius, Top, Right - radius, Top)

' Canto Superior Direito
If makeRightRound Then
    path.AddArc(Right - diameter, Top, diameter, diameter, 270, 90)
Else
    path.AddLine(Right - radius, Top, Right, Top) ' Termina a linha superior
    path.AddLine(Right, Top, Right, Top + radius) ' Começa a linha direita
End If

' Linha Direita (Vertical)
path.AddLine(Right, Top + radius, Right, Bottom - radius)

' Canto Inferior Direito
If makeRightRound Then
    path.AddArc(Right - diameter, Bottom - diameter, diameter, diameter, 0, 90)
Else
    path.AddLine(Right, Bottom - radius, Right, Bottom) ' Termina a linha direita
    path.AddLine(Right, Bottom, Right - radius, Bottom) ' Começa a linha inferior
End If

' Linha Inferior
path.AddLine(Right - radius, Bottom, Left + radius, Bottom)

' Canto Inferior Esquerdo
If makeLeftRound Then
    path.AddArc(Left, Bottom - diameter, diameter, diameter, 90, 90)
Else
    path.AddLine(Left + radius, Bottom, Left, Bottom) ' Termina a linha inferior
    path.AddLine(Left, Bottom, Left, Bottom - radius) ' Começa a linha esquerda (para fechar)
End If

path.CloseFigure() ' Fecha o caminho conectando a última linha ao início
Return path
End Function
vb.net
  • 1 respostas
  • 97 Views
Martin Hope
the-mad-statter
Asked: 2025-04-08 05:27:58 +0800 CST

Como mapear valores de coeficientes para nomes do pipeline ajustado {sparklyr}?

  • 5

Depois de ajustar um modelo linear generalizado usando {sparklyr} em um notebook do Azure Databricks, como mapear os valores dos coeficientes do modelo para nomes de preditores?

Aqui está um exemplo de ajuste de um modelo e extração dos coeficientes. Gostaria de determinar os nomes associados a cada coeficiente.

library(sparklyr)

sc <- spark_connect(method = "databricks")

data <- copy_to(sc, mtcars, "mtcars", overwrite = TRUE)

pipeline <- ml_pipeline(sc) %>%
  ft_r_formula(vs ~ cyl + carb) %>%
  ml_generalized_linear_regression(family = "binomial")

partitioned_data <- sdf_random_split(data, train = 0.80, test = 0.20, seed = 42)

fitted_pipeline <- ml_fit(pipeline, partitioned_data$train)

glrm_transformer <- ml_stage(fitted_pipeline, length(fitted_pipeline$stages))

with(glrm_transformer, c(intercept, coefficients))

Esta pergunta é bem parecida com esta , mas em R em vez de Python.

  • 1 respostas
  • 26 Views
Martin Hope
Roman R.
Asked: 2025-04-08 05:21:31 +0800 CST

O ActiveMQ Artemis falha imediatamente após iniciar no contêiner

  • 5

Estou prestes a usar a imagem mais recente do Docker do ActiveMQ Artemis 2.40.0 (não Alpine), e ela falha logo após a execução com o seguinte erro:

$ podman run -ti --name mycontainer --security-opt label=disable -p 61616:61616 -p 8161:8161 --rm  apache/activemq-artemis:2.40.0
...
2025-04-07 21:14:35,462 WARN  [org.apache.activemq.artemis.core.io.aio.AIOSequentialFileFactory] Error while calling io_getevents IO: Operation not permitted
java.io.IOException: Error while calling io_getevents IO: Operation not permitted
    at org.apache.activemq.artemis.nativo.jlibaio.LibaioContext.blockedPoll(Native Method) ~[activemq-artemis-native-2.0.0.jar:2.0.0]
    at org.apache.activemq.artemis.nativo.jlibaio.LibaioContext.poll(LibaioContext.java:368) ~[activemq-artemis-native-2.0.0.jar:2.0.0]
    at org.apache.activemq.artemis.core.io.aio.AIOSequentialFileFactory$PollerThread.run(AIOSequentialFileFactory.java:449) [artemis-journal-2.40.0.jar:2.40.0]
2025-04-07 21:14:35,476 INFO  [org.apache.activemq.artemis.core.server] AMQ221034: Waiting indefinitely to obtain primary lock
2025-04-07 21:14:35,477 INFO  [org.apache.activemq.artemis.core.server] AMQ221035: Primary Server Obtained primary lock
2025-04-07 21:14:35,480 WARN  [org.apache.activemq.artemis.journal] AMQ144010: Critical IO Exception happened: Error while calling io_getevents IO: Operation not permitted
org.apache.activemq.artemis.api.core.ActiveMQException: Error on libaio poll
    at org.apache.activemq.artemis.core.io.aio.AIOSequentialFileFactory$PollerThread.run(AIOSequentialFileFactory.java:452) [artemis-journal-2.40.0.jar:2.40.0]
2025-04-07 21:14:35,481 ERROR [org.apache.activemq.artemis.core.server] AMQ222010: Critical IO Error, shutting down the server. file=Error while calling io_getevents IO: Operation not permitted, message=NULL
org.apache.activemq.artemis.api.core.ActiveMQException: Error on libaio poll
    at org.apache.activemq.artemis.core.io.aio.AIOSequentialFileFactory$PollerThread.run(AIOSequentialFileFactory.java:452) [artemis-journal-2.40.0.jar:2.40.0]

Não está muito claro o que é isso e como consertar. As imagens Alpine funcionam bem, mas eu preferiria não usar Alpine.

Eu uso o Podman versão 5.4.0 e o Fedora Linux 41.

java
  • 2 respostas
  • 59 Views
Martin Hope
Petlover620
Asked: 2025-04-08 05:06:08 +0800 CST

Existe uma função auxiliar na biblioteca Midnight JS para replicar a função pad() interna do Compact?

  • 5

Estou tentando usar a tokenType()função na linguagem compacta do Midnight para calcular o TokenType de uma nova moeda. Existe alguma função auxiliar que eu possa usar na biblioteca Midnight JS para replicar pad()a função interna do Compact?

Estou com dificuldades para criar um Uint8Array que corresponda ao tipo Compact Bytes<32> que criei com a função pad no meu contrato. Alguma sugestão de como fazer isso?

typescript
  • 1 respostas
  • 26 Views
Martin Hope
Nikhil Nathanael
Asked: 2025-04-08 04:52:52 +0800 CST

Por que essas duas implementações de características não são conflitantes?

  • 7

Tenho uma situação na minha base de código em que uma função possui um objeto de característica em caixa chamando uma função que espera um implementador dessa característica, e recebi a mensagem de erro mostrada abaixo. Por algum motivo, a Box não implementa Trait por padrão.

use std::any::Any;

trait SubTrait: DynClone {}

trait DynClone: Any {
    fn dyn_clone(&self) -> Box<dyn DynClone>;
}

impl<T: Any + Clone + 'static> DynClone for T {
    fn dyn_clone(&self) -> Box<dyn DynClone> {
        Box::new(Clone::clone(self))
    }
}

fn test_outer() {
    test::<Box<dyn SubTrait>>();
}

fn test<L: SubTrait>() {}
error[E0277]: the trait bound `Box<(dyn SubTrait + 'static)>: SubTrait` is not satisfied
   --> src\ecs\schedule.rs:124:9
    |
124 |     test::<Box<dyn SubTrait>>();
    |            ^^^^^^^^^^^^^^^^^ the trait `SubTrait` is not implemented for `Box<(dyn SubTrait + 'static)>`
    |

Não entendo completamente por que isso acontece, mas estou mais perplexo com uma correção que funcionou

impl DynClone for Box<dyn SubTrait> {
    fn dyn_clone(&self) -> Box<dyn DynClone> {
        (self as &dyn DynClone).dyn_clone()
    }
}

impl SubTrait for Box<dyn SubTrait> {}

Tentei fazer isso esperando que fosse rejeitado devido a uma implementação conflitante, mas foi aceito por algum motivo.

Por que essas implementações não são conflitantes?


impl DynClone for Box<dyn SubTrait> {
    fn dyn_clone(&self) -> Box<dyn DynClone> {
        (self as &dyn DynClone).dyn_clone()
    }
}

impl<T: Any + Clone + 'static> DynClone for T {
    fn dyn_clone(&self) -> Box<dyn DynClone> {
        Box::new(Clone::clone(self))
    }
}

Eu sei que não é por causa dos limites de características em T, porque Rust não considera limites de características ou cláusulas where ao verificar conflitos.

Eu até verifiquei que os limites de características em T não são a correção com outro tipo que não é clone, o que leva a essa mensagem de erro.

use std::sync::mpsc::Receiver;
impl DynClone for Receiver<()> {
    fn dyn_clone(&self) -> Box<dyn DynClone> {
        Box::new(25_i32)
    }
}
error[E0119]: conflicting implementations of trait `schedule::test::DynClone` for type `std::sync::mpsc::Receiver<()>`
   --> src\ecs\schedule.rs:138:1
    |
117 | impl<T: Any + Clone + 'static> DynClone for T {
    | --------------------------------------------- first implementation here
...
138 | impl DynClone for Receiver<()> {
    | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `std::sync::mpsc::Receiver<()>`
    |
    = note: upstream crates may add a new impl of trait `std::clone::Clone` for type `std::sync::mpsc::Receiver<()>` in future versions

Alguém pode explicar o que está acontecendo aqui?

rust
  • 1 respostas
  • 47 Views
Martin Hope
Jose Serra
Asked: 2025-04-08 04:44:25 +0800 CST

Botões ao clicar funcionam com o mesmo ID e atributos diferentes

  • 5

Tenho uma página HTML com um exemplo de botões, como mostrado, parte de um aplicativo Django que preenche o nome e a cidade após inserir os valores:

{% for person in page_obj %}
       <button id="NotifyBtn" name="person.FName" town="person.LName">Press Me</button>
{% endfor %}
<button id="NotifyBtn" name="Billy" town="Bob">Press Me</button>
<button id="NotifyBtn" name="Timmy" town="Tawin">Press Me</button>
<button id="NotifyBtn" name="Milly" town="House">Press Me</button>

Então eu tenho um JS que faz o seguinte:

document.getElementById("NotifyBtn").addEventListener("click", function(){
            var name = this.getAttribute("name");
            var town = this.getAttribute("town");
            fetch("{% url 'alert_via_JSON_Response' %}", {
                method: "POST",
                headers: {
                    "X-CSRFToken": "{{ csrf_token }}",
                    "Content-Type": "application/json"
                },
                body: JSON.stringify({ message: "Hi there: " + `${name} born in ${town}`
                 })
                }).then(response => response.json())
                    .then(data => alert(data.status));
        });

Na minha aplicação Django tenho o seguinte:

def alert_via_JSON_Response(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        message = data.get('message', "Error in sending email")
        return JsonResponse({"status": f"{message}"})
    return JsonResponse({"status": f"No Message"})

No momento, quando clico na página, apenas um botão funciona e envia uma resposta JSON para a página. Não funciona se eu pressionar outro botão depois de pressionar o primeiro. Existe uma maneira de pressionar cada botão quando necessário e exibir a resposta JSON para cada botão?

javascript
  • 1 respostas
  • 48 Views
Martin Hope
Marcelo de Sá
Asked: 2025-04-08 04:43:27 +0800 CST

Projeção angular com diretiva

  • 6

Estou criando modelos usando projeção em angular 18. Tenho um componente base html chamado base-list.component.html

...
<mat-drawer-content class="bg-white">
  <div class="d-flex flex-column h-100" [loading]="isLoading">
    <ng-content select="[table]"></ng-content>
  </div>
</mat-drawer-content>
...

e uma classe base BaseListComponent

@Component({
    selector: 'app-base-list',
    templateUrl: './base-list.component.html',
    standalone: true,
    imports: [
        LoadingDirective
    ]
})
export class BaseListComponent<TType> {

    protected isLoading: boolean = false
...

No componente filho tenho um html list.component.html

<app-base-list>
  <ng-container table>
    <table mat-table matSort [dataSource]="dataSource">
      <ng-container matColumnDef="name">
        <th mat-header-cell *matHeaderCellDef>
          Name
        </th>
        <td mat-cell *matCellDef="let element" class="text-start">{{element.name}}</td>
      </ng-container>
    </table>
  </ng-container>
</app-base-list>

e uma classe

@Component({
    selector: 'app-lista',
    standalone: true,
    imports: [
    ],
    templateUrl: './lista.component.html',
    styleUrls: ['./lista.component.scss']
})
export class ListaComponent extends BaseListComponent<IData> implements AfterViewInit {
   ngAfterViewInit() {
        this.seacrh()
    }

    private seacrh = () => {
        this.loading = true
        ...
        this.http.get<IData[]>()
            .subscribe(resp => {
                if (resp.error) {
                    ...
                }
                else {
                    ...
                }
            });
    }

}

Se eu colocar a diretiva na página filha sem modificar o código, o carregamento aparece, mas com a diretiva no componente pai, o valor do sinalizador isLoading não muda e o carregamento não aparece.

Meu modelo tem vários outros métodos e propriedades, este é apenas um exemplo usando variáveis

É possível criar esse tipo de modelo em que o componente filho pode modificar os valores criados no modelo sem usar Emit?

angular
  • 1 respostas
  • 43 Views
Martin Hope
NEA
Asked: 2025-04-08 04:41:33 +0800 CST

O elemento de tema "tbl_summary-arg:type" no gtsummary não funciona

  • 5

O elemento de tema "tbl_summary-arg:type" no gtsummary não funciona, embora o argumento de tipo funcione bem com o mesmo código

library(gtsummary)
packageVersion("gtsummary")
#> [1] '2.1.0.9010'

# Reset theme to defaults first
reset_gtsummary_theme()
tbl_summary(trial) |> 
  # Converting to a flextable object because gtsummary 
  # objects aren't rendered properly on Stack Overflow
  as_flex_table()


# Apply my theme
set_gtsummary_theme(list("tbl_summary-arg:type" =
                           list(all_dichotomous() ~ "categorical")))
# check if it works
trial |>
  tbl_summary() |> 
  as_flex_table()
#Not working Patient Died   is still presented as dichotomous

#Checking type argument
reset_gtsummary_theme()
trial |>
  tbl_summary(type = all_dichotomous() ~ "categorical") |> 
  as_flex_table()
#works well

Criado em 2025-04-07 com reprex v2.1.1

Estou esquecendo de algo que está fazendo com que não funcione?

  • 2 respostas
  • 22 Views
Prev
Próximo

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Reformatar números, inserindo separadores em posições fixas

    • 6 respostas
  • Marko Smith

    Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não?

    • 2 respostas
  • Marko Smith

    Problema com extensão desinstalada automaticamente do VScode (tema Material)

    • 2 respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Martin Hope
    Fantastic Mr Fox Somente o tipo copiável não é aceito na implementação std::vector do MSVC 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant Encontre o próximo dia da semana usando o cronógrafo 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor O inicializador de membro do construtor pode incluir a inicialização de outro membro? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul O C++20 mudou para permitir a conversão de `type(&)[N]` de matriz de limites conhecidos para `type(&)[]` de matriz de limites desconhecidos? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann Como/por que {2,3,10} e {x,3,10} com x=2 são ordenados de forma diferente? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve