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 / user-10088259

Fred Hors's questions

Martin Hope
Fred Hors
Asked: 2024-11-13 23:33:24 +0800 CST

Há alguma melhoria de desempenho se eu declarar essa const dentro ou fora da função?

  • 5

Como esta é uma função de alta chamada, há alguma diferença se eu declarar const QUERYdentro ou fora dela fn insert()?

impl Player {
    pub async fn insert(
        db: sqlx::PgConnection,
        input: &InputPlayer,
    ) -> Result<Self> {
        const QUERY: &str = r#"INSERT INTO "player" ("team_id", "id", "other_fields") VALUES ($1, $2, $3, $4, $5, $6, $7)"#;

        let result = sqlx::query_as::<_, Self>(QUERY)
            .bind(input.team_id())
            .bind(input.id())
            .bind(input.other())
            .bind(input.other())
            .bind(input.other())
            .bind(input.other())
            .fetch_one(db)
            .await?;

        Ok(result)
    }
}
rust
  • 2 respostas
  • 75 Views
Martin Hope
Fred Hors
Asked: 2024-08-24 00:42:45 +0800 CST

Existe uma maneira de eliminar um valor derivado de Svelte 5 $?

  • 5

Eu tentei com:

let searchText = $derived(debounce((typedText) => typedText, 2000)(typedText));

Mas searchTextnão está atribuído!

  1. A reprodução com$derived : searchTextnão está atribuída.

  2. A reprodução com$effect() : searchTextatribuição não é rejeitada de forma alguma.

svelte
  • 1 respostas
  • 41 Views
Martin Hope
Fred Hors
Asked: 2024-08-05 23:15:12 +0800 CST

Lidar com uma função que pode ser chamada dentro de uma transação ou não

  • 5

Se uma função pode ser chamada com uma transação ou uma conexão direta (e portanto deve iniciar uma nova transação a partir daí porque precisa de uma), o que você sugere usar?

Código de exemplo:

async fn find_player_id_and_assign_goal(
    &self,
    db: Option<&mut sqlx::PgConnection>,
    id: &str,
    team_id: &str,
) -> Result<String, Error> {
    let mut tx = None;

    let db = match db {
        Some(db) => {
            // I need to detect if `db` here is already a transaction or not, in which case I should start a new one:
            db
        },
        None => &mut *tx.insert(self.pool.begin().await?),
    };

    let _ = self.team_service.find_team_id(Some(db), team_id).await?;

    let player_id = self.repo.find_player_id(Some(db), id).await?;

    self.goal_service.assign_to_player(Some(db), id).await?;

    if let Some(tx) = tx {
        tx.commit().await?;
    }

    Ok(player_id)
}

Isso pode funcionar, mas só tenho um problema:

Se Some(db) => dbeu precisar detectar se já estamos em uma transação (se dbhouver). Se não, eu deveria começar um novo.

Você acha que existe uma maneira melhor de fazer isso?

rust
  • 1 respostas
  • 32 Views
Martin Hope
Fred Hors
Asked: 2024-08-05 21:58:43 +0800 CST

Como posso commit() esta transação?

  • 5

No código abaixo estou recebendo este erro:

error[E0599]: no method named `commit` found for mutable reference `&mut sqlx::PgConnection` in the current scope
   --> src/main.rs:103:12
    |
103 |         db.commit().await?;
    |            ^^^^^^ method not found in `&mut PgConnection`

Preciso confirmar se dbfor, Nonejá que estou iniciando uma nova transação com: &mut self.pool.begin().await?.

Não há problema em usar db: Option<&mut sqlx::PgConnection>como tipo de argumento ou devo usar outra coisa, como Acquiretrait?

Código no Rust Playground

pub async fn find_player_id(
    &self,
    db: Option<&mut sqlx::PgConnection>,
    id: &str,
    team_id: &str,
) -> Result<String, Error> {
    let db = match db {
        Some(db) => db,
        None => &mut self.pool.begin().await?,
    };

    let _ = self.team_service.find_team_id(Some(db), team_id).await?;

    let player_id = self.repo.find_player_id(Some(db), id).await?;

    db.commit().await?;

    Ok(player_id)
}

ATUALIZAR:

Alguém no SO fechou a questão porque acha que é uma duplicata de Por que preciso importar uma característica para usar os métodos que ela define para um tipo? .

Isso não é, eu acho. Por favor, leia a pergunta antes de agir.

rust
  • 1 respostas
  • 34 Views
Martin Hope
Fred Hors
Asked: 2024-06-10 19:31:02 +0800 CST

O que significa o erro Rust "você pode encaixotar o valor encontrado e forçá-lo ao objeto de característica"?

  • 4

O que esse erro significa?

Reprodução

error[E0308]: mismatched types
  --> src/main.rs:50:35
   |
50 |           PaymentType::InvoiceIn => InvoiceIn {
   |  ___________________________________^
51 | |             name: "Invoice 1".to_string(),
52 | |             payed: false,
53 | |         },
   | |_________^ expected `dyn Payable`, found `InvoiceIn`
   |
   = note: expected trait object `dyn Payable`
                    found struct `InvoiceIn`
   = help: `InvoiceIn` implements `Payable` so you could box the found value and coerce it to the trait object `Box<dyn Payable>`, you will have to change the expected type as well

For more information about this error, try `rustc --explain E0308`.

Código:

trait Payable {
    fn toggle_payed(&mut self);
}

enum PaymentType {
    InvoiceOut,
    InvoiceIn,
}

struct Payment {
    r#type: PaymentType,
}

struct InvoiceOut {
    name: String,
    payed: bool,
}

impl Payable for InvoiceOut {
    fn toggle_payed(&mut self) {
        self.payed = !self.payed
    }
}

struct InvoiceIn {
    name: String,
    payed: bool,
}

impl Payable for InvoiceIn {
    fn toggle_payed(&mut self) {
        self.payed = !self.payed
    }
}

fn save_invoice_in(invoice: &InvoiceIn) {
    println!("{}", invoice.name)
}

fn save_invoice_out(invoice: &InvoiceOut) {
    println!("{}", invoice.name)
}

fn main() {
    let payment = Payment {
        r#type: PaymentType::InvoiceOut, // This comes from user!
    };

    let payable: dyn Payable = match payment.r#type {
        PaymentType::InvoiceIn => InvoiceIn {
            name: "Invoice 1".to_string(),
            payed: false,
        },
        PaymentType::InvoiceOut => InvoiceOut {
            name: "Invoice 2".to_string(),
            payed: false,
        },
    };

    // Do something else with payable here

    payable.toggle_payed();

    // Do something else with payable here

    match payment.r#type {
        PaymentType::InvoiceIn => save_invoice_in(&payable),
        PaymentType::InvoiceOut => save_invoice_out(&payable),
    };
}
rust
  • 1 respostas
  • 67 Views
Martin Hope
Fred Hors
Asked: 2024-02-01 22:46:14 +0800 CST

Existe uma maneira de corrigir esse código ou devo pedir para alterar a estrutura de dados?

  • 3

Estou enlouquecendo com isso (porque não sou uma pessoa muito lógica).

Ferrugem Parque Infantil

Não consigo alterar a parte dos dados.

A string retornada do código abaixo é A = 1 AND (B = 2 OR C = 3 OR D = 4 OR )o que eu preciso ( A = 1 AND (B = 2 OR C = 3 OR D = 4)).

O que não entendo é como evitar o último “OU”.

Como posso corrigir o código abaixo?

enum Token {
    Str(&'static str),
    Value(&'static str),
    StartGroup(&'static str),
    EndGroup,
}

fn main() {
    let data: Vec<Vec<Token>> = vec![
        vec![Token::Str("A = "), Token::Value("1")],
        vec![Token::Str(" AND ("), Token::StartGroup(" OR ")],
        vec![Token::Str("B = "), Token::Value("2")],
        vec![Token::Str("C = "), Token::Value("3")],
        vec![Token::Str("D = "), Token::Value("4")],
        vec![Token::EndGroup, Token::Str(")")],
    ];

    let result = construct_string(data);

    assert_eq!("A = 1 AND (B = 2 OR C = 3 OR D = 4)", result);
}

fn construct_string(tokens: Vec<Vec<Token>>) -> String {
    let mut result = String::new();

    let mut current = String::new();
    let mut next = String::new();

    for token in tokens {
        for part in token {
            match part {
                Token::Str(str) => {
                    result.push_str(str);
                }
                Token::Value(val) => {
                    result.push_str(val);
                }
                Token::StartGroup(group) => {
                    next = group.to_string();
                }
                Token::EndGroup => {
                    current = String::new();
                    next = String::new();
                }
            }
        }

        if !current.is_empty() {
            result.push_str(&current);
        }

        current = next.to_string();
    }

    result
}
loops
  • 1 respostas
  • 78 Views
Martin Hope
Fred Hors
Asked: 2024-01-18 23:35:15 +0800 CST

Existe uma maneira de simplificar esse código evitando chamar `onDestroy` manualmente todas as vezes?

  • 5

Estamos usando o EventSource em vários lugares do aplicativo SvelteKit, assim:

<script>
  import { onDestroy } from 'svelte';
  import { customEventSource } from '$lib/events';

  const callback = (event: MessageEvent) => {
    console.log('event:', event);
  };

  customEventSource.addEventListener('message', callback);

  onDestroy(() => {
    customEventSource.removeEventListener('message', callback);
  });
</script>

Como você pode ver, há muito o que escrever a cada vez.

Não existe uma maneira mágica – como Svelte nos ensinou – de simplificar?

Principalmente para não precisar ligar manualmenteonDestroy todas as vezes?

svelte
  • 1 respostas
  • 18 Views

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