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
lando2319
Asked: 2025-04-08 21:12:32 +0800 CST

Como executo um único arquivo de execução única no Cloudrun, não me importo com a web de forma alguma

  • 5

Desculpe por postar isso. Estou tentando executar um único arquivo, como uma tarefa executável única. Não me importo com a web, não me importo com as portas que os usuários podem acessar, não há usuários, não há nada para acessar. Quero apenas executar um único arquivo, não um servidor web, mas um arquivo.

Aqui está meu index.jsarquivo

// Retrieve Job-defined env vars
const { CLOUD_RUN_TASK_INDEX = 0, CLOUD_RUN_TASK_ATTEMPT = 0 } = process.env;
// Retrieve User-defined env vars
const { SLEEP_MS, FAIL_RATE } = process.env;

// Define main script
const main = async () => {
    console.log(
        `Starting Task #${CLOUD_RUN_TASK_INDEX}, Attempt #${CLOUD_RUN_TASK_ATTEMPT}...`
    );
    // Simulate work
    if (SLEEP_MS) {
        await sleep(SLEEP_MS);
    }
    // Simulate errors
    if (FAIL_RATE) {
        try {
            randomFailure(FAIL_RATE);
        } catch (err) {
            err.message = `Task #${CLOUD_RUN_TASK_INDEX}, Attempt #${CLOUD_RUN_TASK_ATTEMPT} failed.\n\n${err.message}`;
            throw err;
        }
    }
    console.log(`Completed Task #${CLOUD_RUN_TASK_INDEX}.`);
};

// Wait for a specific amount of time
const sleep = ms => {
    return new Promise(resolve => setTimeout(resolve, ms));
};

// Throw an error based on fail rate
const randomFailure = rate => {
    rate = parseFloat(rate);
    if (!rate || rate < 0 || rate > 1) {
        console.warn(
            `Invalid FAIL_RATE env var value: ${rate}. Must be a float between 0 and 1 inclusive.`
        );
        return;
    }

    const randomFailure = Math.random();
    if (randomFailure < rate) {
        throw new Error('Task failed.');
    }
};

// Start script
main().catch(err => {
    console.error(err);
    process.exit(1); // Retry Job Task by exiting the process
});

Então eu tenho meu package.jsonlike então

{
    "name": "jobs",
    "version": "1.0.0",
    "description": "Node.js sample for Cloud Run jobs",
    "main": "index.js",
    "scripts": {
        "start": "node index.js"
    },
    "engines": {
        "node": ">=16.0.0"
    },
    "author": "Google LLC",
    "license": "Apache-2.0"
}

Esses arquivos foram retirados diretamente dos documentos, sem nenhuma alteração.

E eu estou conseguindo isso

Deployment failed                                                                                   
ERROR: (gcloud.run.deploy) Revision 'cloudruntest-00001-fdl' is not ready and cannot serve traffic. The user-provided container failed to start and listen on the port defined provided by the PORT=8080 environment variable within the allocated timeout. This can happen when the container port is misconfigured or if the timeout is too short. The health check timeout can be extended. Logs for this revision might contain more information.

Servidores web são legais e tudo mais, mas agora eu só quero executar um arquivo, só isso. O que eu preciso fazer para executar um arquivo no CloudRun?

  • 1 respostas
  • 35 Views
Martin Hope
Autumn Mannsfeld
Asked: 2025-04-08 21:00:08 +0800 CST

Como alterar o separador de tempo de decimal para dois pontos em R

  • 6

Tenho um conjunto de dados brutos que usa um decimal como separador de tempo e quero que ele tenha dois pontos, mas não tenho ideia de como alterá-lo. Meu tempo bruto (com decimais) está na coluna "df$Time", e meu tempo correto (com os dois pontos) estará em "df$time" (para manter a consistência com os outros dataframes no meu código). df$Date é uma coluna de caracteres, df$Time é uma coluna numérica. Estou usando uma infinidade de bibliotecas, algumas incluindo dplyre stringr.

Não sei bem como criar uma tabela bonita com dados recriáveis. Escrever nesta plataforma é novidade para mim. Mas abaixo, incluo um trecho dos dados de tempo e alguns métodos que tentei. Qualquer ajuda é bem-vinda! Parece tão simples, mas realmente não consigo entender.

(Também peço desculpas pelo formato dos meus dados abaixo, tentei fazer uma tabela, mas uma que parecesse melhor e, novamente, nada funcionou. Acho que preciso dar uma pausa na solução de problemas, rs)

Aqui está o resultado após a execução dput(head(df)):

structure(list(Date = c("01/03/2024", "01/03/2024", "01/03/2024", "01/03/2024", "01/03/2024", "01/03/2024"), Time = c(0, 0.05, 0.1, 0.15, 0.2, 0.25)), row.names = c(NA, 6L), class = "data.frame")

Aqui está um trecho de duas horas de dados simplificados (incluindo apenas colunas relevantes) que mostra o problema:

          Date  Time
181 01/03/2024 15.00  
182 01/03/2024 15.05
183 01/03/2024 15.10
184 01/03/2024 15.15
185 01/03/2024 15.20
186 01/03/2024 15.25
187 01/03/2024 15.30
188 01/03/2024 15.35
189 01/03/2024 15.40
190 01/03/2024 15.45
191 01/03/2024 15.50
192 01/03/2024 15.55
193 01/03/2024 16.00
194 01/03/2024 16.05
195 01/03/2024 16.10
196 01/03/2024 16.15
197 01/03/2024 16.20
198 01/03/2024 16.25
199 01/03/2024 16.30
200 01/03/2024 16.35
201 01/03/2024 16.40
202 01/03/2024 16.45
203 01/03/2024 16.50
204 01/03/2024 16.55
205 01/03/2024 17.00

Aqui estão alguns dos métodos que tentei:

Método 1:

df$time <- df %>% mutate(across(everything(), ~str_replace(., ",", ".")))

Método 2:

df$time <- str_replace(df$Time, ".", ":")

Método 3:

df$Time <- as.character(df$Time)

df$time <- gsub(".", ":", df$Time, fixed = T)

Método 4:

df$time <- strptime(as.character(df$Time), "%H.%M")

df$time <- format(df$time, "%H:%M")

Método 5:

df$time <- as.POSIXlt(df$Time)

Método 6:

df$time <- df$Time df$time <- gsub(".", ":", df$time)

Método 7:

df$time <- df$Time df$time <- str_replace_all(df$time, ".", ":")

  • 4 respostas
  • 37 Views
Martin Hope
Simon Wyns
Asked: 2025-04-08 20:58:15 +0800 CST

O tipo '{ id: string; }' não possui as seguintes propriedades do tipo 'Promise<any>': then, catch, finally

  • 5

Sou meio novo no uso do next.js. Recebi esse erro e não consigo

Erro de tipo: O tipo 'ComposerPageProps' não atende à restrição 'PageProps'. Os tipos da propriedade 'params' são incompatíveis. O tipo '{ id: string; }' não possui as seguintes propriedades do tipo 'Promise': then, catch, finally, [Symbol.toStringTag]

32 | 33 | // Verifique o tipo de suporte da função de entrada

34 | checkFields<Diff<PageProps, FirstArg<TEntry['default']>, 'default'>>() | ^ 35 | 36 | // Verifique os argumentos e o tipo de retorno da função generateMetadata 37 | if ('generateMetadata' in entry) {

Este é o meu código que pode causar o erro:

interface ComposerPageProps {
    params: {
        id: string
    }
}

export async function generateMetadata({params}: ComposerPageProps): Promise<Metadata> {
    const composer = await getComposer(params.id)

    if (!composer) {
        return {
            title: "Composer Not Found | Sheetly",
        }
    }

    return {
        title: `${composer.name} | Composer | Sheetly`,
        description: `Explore sheet music by ${composer.name}, ${composer.periods} composer. Download and play beautiful arrangements of their most famous works.`,
    }
}

export default async function ComposerPage({params}: ComposerPageProps) {
    return (
        <ComposerPageClient id={params.id}/>
    )
}

e meu componente cliente

export default async function ComposerPageClient({id}: { id: string }) {
    const composer = await getComposer(id);
    const sheets = await getAllSheetsFromComposer(id);
    const favorites = await getFavorites();

    return (
        <div className="container mx-auto px-4 py-8">
            <ComposerProfile composer={composer} sheets={sheets}/>

            <div className="mt-12">
                <ComposerSheets sheets={sheets} userFavorites={favorites}/>
            </div>
        </div>
    )
}
next.js
  • 1 respostas
  • 19 Views
Martin Hope
kevin rowe
Asked: 2025-04-08 20:57:01 +0800 CST

A versão 1.2025.328.300 do Outlook causa erro OLE ao executar um código que funciona perfeitamente na versão anterior

  • 5

Temos um aplicativo powerbuilder que executa automação OLE no Outlook com

li_rc = lole_outlook.ConnectToNewObject("outlook.application")

Este código funciona bem com versões anteriores do Outlook, mas depois que o usuário foi atualizado para a versão 1.2025.328.300 (o Office mostra como 16.0.18623.20156), ele falha todas as vezes, exibindo um erro OLE informando que não foi possível iniciar o servidor OLE. Agora, temos vários clientes com o mesmo problema.

Configurar a máquina para usar a versão anterior do Outlook resolve o problema em todos os casos.

Alguns usuários relataram que tiveram problemas para atualizar e isso pode ter resultado em uma instalação incorreta ou parcial da nova versão que não foi configurada corretamente para OLE.

Existe uma versão mais recente que corrige esse problema? Existe alguma correção com edição do registro que possa ajudar?

Obrigado por qualquer feedback.

outlook
  • 1 respostas
  • 52 Views
Martin Hope
mnol
Asked: 2025-04-08 20:55:46 +0800 CST

Como tornar a consulta LINQ mais rápida

  • 5

A execução de NbLinksExpirationStatus leva cerca de 12 segundos, o que não é rápido o suficiente para o que estou tentando alcançar. Poderia ser um problema com Contains()? Existe alguma maneira de torná-lo mais rápido? Estou trabalhando com EF6 e SQL Server. Por favor, me diga se, também neste caso, é melhor usar apenas sqlquery ou não?

OBSERVAÇÃO :

HashSet<int> oneEntitiesPerimeter = oneEquipment.Select(x => x.ID_ONE).ToHashSet();
HashSet<int> twoEntitiesPerimeter = twoEquipment.Select(x => x.ID_TWO).ToHashSet();

O método onde há a consulta:

public static Tuple<int, int> NbLinksExpirationStatus(HashSet<int> oneEntitiesPerimeter, HashSet<int> twoEntitiesPerimeter)
{
    using (DbEntities context = new DbEntities())
    {
        int aboutToExpireValue = Constants.LinkStatusAboutToExpire; #1
        int expiredValue = Constants.LinkStatusExpired; #2

        var oneIds = oneEntitiesPerimeter ?? new HashSet<int>();
        var twoIds = twoEntitiesPerimeter ?? new HashSet<int>();

        var joinedQuery = (from t in context.ONE_DISTRIBUTION_STATUS
                            join o in context.TWO_DISTRIBUTION_STATUS on t.ID_ent equals o.ID_ent into joined
                            from o in joined.DefaultIfEmpty()
                            where oneIds.Contains(t.ID_ONE) && (o == null || twoIds.Contains(o.ID_TWO))
                            select new { oneExpirationStatus = t.LINK_STATUS_EXPIRATION, twoExpirationStatus = o.LINK_STATUS_EXPIRATION }).ToList();

        var aboutToExpireCount = joinedQuery.Where(j =>
            j.oneExpirationStatus == aboutToExpireValue || j.twoExpirationStatus == aboutToExpireValue).Count();

        var expiredCount = joinedQuery.Where(j =>
            j.oneExpirationStatus == expiredValue || j.twoExpirationStatus == expiredValue).Count();

        return new Tuple<int, int>(aboutToExpireCount, expiredCount);
    }
}

EDIT: tentei usar SQL, mas a velocidade de execução não melhora. Esta é a tentativa:

string oneIds = "NULL";            
if(oneEntitiesPerimeter != null && oneEntitiesPerimeter.Count > 0)
{
    oneIds = string.Join(",", oneEntitiesPerimeter);
}
string twoIds = "NULL";
if (twoEntitiesPerimeter != null && twoEntitiesPerimeter.Count > 0)
{
    twoIds = string.Join(",", twoEntitiesPerimeter);
}

string sqlQuery = "SELECT " +
    "COALESCE(SUM(CASE WHEN t.LINK_STATUS_EXPIRATION = " + aboutToExpireValue + " OR COALESCE(o.LINK_STATUS_EXPIRATION, '')= " + aboutToExpireValue + " THEN 1 ELSE 0 END), 0) AS AboutToExpire," +
    "COALESCE(SUM(CASE WHEN t.LINK_STATUS_EXPIRATION = " + expiredValue + " OR COALESCE(o.LINK_STATUS_EXPIRATION, '') = " + expiredValue + " THEN 1 ELSE 0 END), 0) AS Expired "+
    "FROM ONE_DISTRIBUTION_STATUS t LEFT JOIN TWO_DISTRIBUTION_STATUS o ON t.ID_ent = o.ID_ent WHERE t.ID_ONE in (" + oneIds + ") AND (o.ID_TWO in (" + twoIds + ") OR o.ID_TWO IS NULL)";

var counter = context.Database.SqlQuery<LinkExpirationStatusWidget>(sqlQuery).FirstOrDefault();           
result = new Tuple<int, int>(counter.AboutToExpire, counter.Expired);

A classe adicionou para armazenar resultados:

public class LinkExpirationStatusWidget
{
    /// <summary>
    /// Gets or sets count of links about to expire
    /// </summary>
    /// <value>About To Expire count</value>
    public int AboutToExpire { get; set; }

    /// <summary>
    /// Gets or sets count of links expired
    /// </summary>
    /// <value>Expired count</value>
    public int Expired { get; set; }
}
c#
  • 2 respostas
  • 109 Views
Martin Hope
Vaiz
Asked: 2025-04-08 20:30:29 +0800 CST

Como obter um valor de array a partir de uma chave de pesquisa de array?

  • 6

Quero obter a produtividade total do funcionário de acordo com o SPV selecionado em uma célula, com várias chaves de busca (matriz). Tentei a fórmula "xlookup", mas ela só mostra a primeira matriz, enquanto há muita produtividade do funcionário.

Minha planilha

Esta é a fórmula que mostra apenas a 1ª matriz.

ARRAYFORMULA(XLOOKUP(FILTER(A3:A9,B3:B9=E3),A13:A48,B13:B48))
google-sheets
  • 2 respostas
  • 46 Views
Martin Hope
Ale
Asked: 2025-04-08 20:09:26 +0800 CST

regex substitui números entre dois caracteres

  • 5

Eu tenho uma corda 'manual__2025-04-08T11:37:13.757109+00:00'e quero'manual__2025-04-08T11_37_13_00_00'

Eu sei como substituir o :e +usando

'manual__2025-04-08T11:37:13.757109+00:00'.replace(':','_').replace('+','_')

mas também quero me livrar dos números entre os dois caracteres '.' e '+'.

Estou usando python.

python
  • 4 respostas
  • 58 Views
Martin Hope
Elarbe
Asked: 2025-04-08 19:56:44 +0800 CST

Provedor Terraform v1.11.3 não encontrado no local filesystem_mirror

  • 5

Estou tentando instalar este provedor de API "burro" para me permitir usar o Terraform com uma API que atualmente não tem um provedor disponível no registro:

https://github.com/Mastercard/terraform-provider-restapi

Baixei o .zip da versão mais recente com cURLe extraí o executável com chmod +x.

Seguindo a documentação da Hashicorp, criei um arquivo de configuração conforme necessário ~/.terraformrc , pelo método de instalação explícito com o seguinte conteúdo:

provider_installation {
  filesystem_mirror {
    path    = "/home/lukerb/.terraform.d/plugins/registry.terraform.io/hashicorp/restapi/1.20.0/linux_amd64/"
    include = ["registry.terraform.io/*/*"]
  }
  direct {
    exclude = ["registry.terraform.io/*/*"]
  }
}

Este caminho existe e é exatamente onde se encontra o executável que extraí anteriormente, porém ao executar terraform initno mesmo diretório que main.tf, recebo o seguinte erro

 Error: Failed to query available provider packages
│
│ Could not retrieve the list of available versions for provider hashicorp/restiapi: provider registry.terraform.io/hashicorp/restiapi was not found in any of the search
│ locations
│
│   - /home/lukerb/.terraform.d/plugins/registry.terraform.io/hashicorp/restapi/1.20.0/linux_amd64/
╵
╷
│ Error: Failed to query available provider packages
│
│ Could not retrieve the list of available versions for provider hashicorp/restapi: provider registry.terraform.io/hashicorp/restapi was not found in any of the search
│ locations
│
│   - /home/lukerb/.terraform.d/plugins/registry.terraform.io/hashicorp/restapi/1.20.0/linux_amd64/

Meu main.tf contém

terraform {
  required_providers {
    restapi = {
      source = "hashicorp/restapi"
      version = "1.20.0"
    }
  }
}

Ativei os logs detalhados para tentar entender qual é o problema e, pelo que posso ver, ao tentar inicializar, o local é verificado, mas nada é encontrado

[TRACE] Selected provider installation method cliconfig.ProviderInstallationFilesystemMirror("/home/lukerb/.terraform.d/plugins/registry.terraform.io/hashicorp/restapi/1.20.0/linux_amd64/") with includes [registry.terraform.io/*/*] and excludes []
[TRACE] Selected provider installation method cliconfig.ProviderInstallationDirect with includes [] and excludes [registry.terraform.io/*/*]
[INFO]  CLI command args: []string{"init"}
Initializing the backend...
[TRACE] Meta.Backend: no config given or present on disk, so returning nil config
[TRACE] Meta.Backend: backend has not previously been initialized in this working directory
[TRACE] Meta.Backend: using default local state only (no backend configuration, and no existing initialized backend)
[TRACE] Meta.Backend: instantiated backend of type <nil>
[DEBUG] checking for provisioner in "."
[DEBUG] checking for provisioner in "/usr/bin"
[DEBUG] checking for provisioner in "/home/lukerb/.terraform.d/plugins"

Alguém vê onde estou cometendo um erro ou qual é exatamente o problema?

EDITAR:

Depois de fazer as alterações sugeridas por @Matthew Schuchard, estou recebendo um erro semelhante

2025-04-08T15:33:07.564+0200 [INFO]  Terraform version: 1.11.3
2025-04-08T15:33:07.564+0200 [DEBUG] using github.com/hashicorp/go-tfe v1.70.0
2025-04-08T15:33:07.564+0200 [DEBUG] using github.com/hashicorp/hcl/v2 v2.23.0
2025-04-08T15:33:07.564+0200 [DEBUG] using github.com/hashicorp/terraform-svchost v0.1.1
2025-04-08T15:33:07.564+0200 [DEBUG] using github.com/zclconf/go-cty v1.16.0
2025-04-08T15:33:07.564+0200 [INFO]  Go runtime version: go1.23.3
2025-04-08T15:33:07.564+0200 [INFO]  CLI args: []string{"terraform", "init"}
2025-04-08T15:33:07.564+0200 [TRACE] Stdout is a terminal of width 120
2025-04-08T15:33:07.564+0200 [TRACE] Stderr is a terminal of width 120
2025-04-08T15:33:07.564+0200 [TRACE] Stdin is a terminal
2025-04-08T15:33:07.564+0200 [DEBUG] Attempting to open CLI config file: /home/lukerb/.terraformrc
2025-04-08T15:33:07.564+0200 [INFO]  Loading CLI configuration from /home/lukerb/.terraformrc
2025-04-08T15:33:07.564+0200 [DEBUG] checking for credentials in "/home/lukerb/.terraform.d/plugins"
2025-04-08T15:33:07.564+0200 [DEBUG] Explicit provider installation configuration is set
2025-04-08T15:33:07.564+0200 [TRACE] Selected provider installation method cliconfig.ProviderInstallationFilesystemMirror("/home/lukerb/.terraform.d/plugins/registry.terraform.io/Mastercard/restapi/1.20.0/linux_amd64") with includes [registry.terraform.io/*/*] and excludes []
2025-04-08T15:33:07.565+0200 [INFO]  CLI command args: []string{"init"}
Initializing the backend...
2025-04-08T15:33:07.565+0200 [TRACE] Meta.Backend: no config given or present on disk, so returning nil config
2025-04-08T15:33:07.565+0200 [TRACE] Meta.Backend: backend has not previously been initialized in this working directory
2025-04-08T15:33:07.565+0200 [TRACE] Meta.Backend: using default local state only (no backend configuration, and no existing initialized backend)
2025-04-08T15:33:07.565+0200 [TRACE] Meta.Backend: instantiated backend of type <nil>
2025-04-08T15:33:07.565+0200 [DEBUG] checking for provisioner in "."
2025-04-08T15:33:07.567+0200 [DEBUG] checking for provisioner in "/usr/bin"
2025-04-08T15:33:07.568+0200 [DEBUG] checking for provisioner in "/home/lukerb/.terraform.d/plugins"
2025-04-08T15:33:07.568+0200 [TRACE] Meta.Backend: backend <nil> does not support operations, so wrapping it in a local backend
2025-04-08T15:33:07.568+0200 [TRACE] backend/local: state manager for workspace "default" will:
 - read initial snapshot from terraform.tfstate
 - write new snapshots to terraform.tfstate
 - create any backup at terraform.tfstate.backup
2025-04-08T15:33:07.568+0200 [TRACE] statemgr.Filesystem: reading initial snapshot from terraform.tfstate
2025-04-08T15:33:07.568+0200 [TRACE] statemgr.Filesystem: snapshot file has nil snapshot, but that's okay
2025-04-08T15:33:07.568+0200 [TRACE] statemgr.Filesystem: read nil snapshot
Initializing provider plugins...
- Finding mastercard/restapi versions matching "1.20.0"...
╷
│ Error: Failed to query available provider packages
│
│ Could not retrieve the list of available versions for provider mastercard/restapi: provider
│ registry.terraform.io/mastercard/restapi was not found in any of the search locations
│
│   - /home/lukerb/.terraform.d/plugins/registry.terraform.io/Mastercard/restapi/1.20.0/linux_amd64
terraform
  • 2 respostas
  • 41 Views
Martin Hope
Alex
Asked: 2025-04-08 19:47:45 +0800 CST

Desabilitar a opção "Enviar para endereço de cobrança" do PayPal

  • 6

Nosso aplicativo ASP.NET vende apenas produtos digitais e não precisa da caixa de seleção "Enviar para endereço de cobrança". Usando o exemplo de código da documentação do PayPal Checkout , obtive a seguinte index.htmlpágina:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>PayPal JS SDK Standard Integration</title>
</head>
<body>
    <div id="paypal-button-container"></div>
    <p id="result-message"></p>

    <!-- Initialize the JS-SDK -->
    <script src="https://www.paypal.com/sdk/js?client-id=<my_client_id>&buyer-country=US&currency=USD&components=buttons&enable-funding=card&commit=false&disable-funding=paylater&debug=true"
            data-sdk-integration-source="developer-studio"></script>
    <script src="Scripts/paypal/app.js"></script>
</body>
</html>

O código app.jsé:

const paypalButtons = window.paypal.Buttons({
    style: {
        shape: "rect",
        layout: "vertical",
        color: "gold",
        label: "paypal",
    },
    message: {
        amount: 100,
    },
    
    async createOrder() {
        try {
            const response = await fetch("/api/paypal/orders", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                // use the "body" param to optionally pass additional order information
                // like product ids and quantities
                body: JSON.stringify({
                    cart: [
                        {
                            id: "YOUR_PRODUCT_ID",
                            quantity: "YOUR_PRODUCT_QUANTITY",
                        },
                    ]
                })
            });

            const orderData = await response.json();

            if (orderData.id) {
                return orderData.id;
            }
            const errorDetail = orderData?.details?.[0];
            const errorMessage = errorDetail
                ? `${errorDetail.issue} ${errorDetail.description} (${orderData.debug_id})`
                : JSON.stringify(orderData);

            throw new Error(errorMessage);
        } catch (error) {
            console.error(error);
            // resultMessage(`Could not initiate PayPal Checkout...<br><br>${error}`);
        }
    },
    async onApprove(data, actions) {
        try {
            const response = await fetch(
                `/api/paypal/orders/${data.orderID}/capture`,
                {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                    },
                }
            );

            const orderData = await response.json();
            // Three cases to handle:
            //   (1) Recoverable INSTRUMENT_DECLINED -> call actions.restart()
            //   (2) Other non-recoverable errors -> Show a failure message
            //   (3) Successful transaction -> Show confirmation or thank you message

            const errorDetail = orderData?.details?.[0];

            if (errorDetail?.issue === "INSTRUMENT_DECLINED") {
                // (1) Recoverable INSTRUMENT_DECLINED -> call actions.restart()
                // recoverable state, per
                // https://developer.paypal.com/docs/checkout/standard/customize/handle-funding-failures/
                return actions.restart();
            } else if (errorDetail) {
                // (2) Other non-recoverable errors -> Show a failure message
                throw new Error(
                    `${errorDetail.description} (${orderData.debug_id})`
                );
            } else if (!orderData.purchase_units) {
                throw new Error(JSON.stringify(orderData));
            } else {
                // (3) Successful transaction -> Show confirmation or thank you message
                // Or go to another URL:  actions.redirect('thank_you.html');
                const transaction =
                    orderData?.purchase_units?.[0]?.payments?.captures?.[0] ||
                    orderData?.purchase_units?.[0]?.payments
                        ?.authorizations?.[0];
                resultMessage(
                    `Transaction ${transaction.status}: ${transaction.id}<br>
          <br>See console for all available details`
                );
                console.log(
                    "Capture result",
                    orderData,
                    JSON.stringify(orderData, null, 2)
                );
            }
        } catch (error) {
            console.error(error);
            resultMessage(
                `Sorry, your transaction could not be processed...<br><br>${error}`
            );
        }
    }
});
paypalButtons.render("#paypal-button-container");

// Example function to show a result to the user. Your site's UI library can be used instead.
function resultMessage(message) {
    const container = document.querySelector("#result-message");
    container.innerHTML = message;
}

O código acima precisa incluir o seguinte para desabilitar a opção de envio, mas onde adicioná-lo?

application_context: {
    shipping_preference: "NO_SHIPPING"
}

Esta questão , application_contextmas observe que não há nenhum lugar para colocar o ponto de extremidade da API do servidor, como fetchno meu código acima.

Agradecemos sua ajuda.

Atualização: Tentei adicionar o application_contextao bodyparâmetro e não teve efeito:

body: JSON.stringify({
    cart: [
        {
            id: "YOUR_PRODUCT_ID",
            quantity: "YOUR_PRODUCT_QUANTITY",
        },
    ],
    application_context: {
        shipping_preference: "NO_SHIPPING"
    }
})

insira a descrição da imagem aqui

Atualização 2: Aqui está o código C# relevante (.NET 4.8). Observe o " PaymentSourcemas o que você adiciona a ele?".

[System.Web.Http.Route("orders")]
[System.Web.Http.HttpPost]
public async Task<IHttpActionResult> CreateOrderAsync([FromBody] dynamic cart)
{
    try
    {
        var result = await _CreateOrderAsync(cart);
        return Json(result.Data);
    }
    catch (Exception ex)
    {
        Console.Error.WriteLine("Failed to create order:", ex);
        return GetInternalServerError("Failed to create order.");
    }
}

private async Task<dynamic> _CreateOrderAsync(dynamic cart)
{
    var createOrderInput = new CreateOrderInput
    {
        Body = new OrderRequest
        {
            Intent = _paymentIntentMap["CAPTURE"],
            PaymentSource = new PaymentSource
            {
                // What goes here?
            },
            PurchaseUnits = new List<PurchaseUnitRequest>
            {
                new PurchaseUnitRequest
                {
                    Amount = new AmountWithBreakdown
                    {
                        CurrencyCode = "USD",
                        MValue = "100",
                        Breakdown = new AmountBreakdown
                        {
                            ItemTotal = new Money
                            {
                                CurrencyCode = "USD",
                                MValue = "100",
                            }
                        }
                    },
                    // lookup item details in `cart` from database
                    Items = new List<Item>
                    {
                        new Item
                        {
                            Name = "T-Shirt",
                            UnitAmount = new Money
                            {
                                CurrencyCode = "USD",
                                MValue = "100",
                            },
                            Quantity = "1",
                            Description = "Super Fresh Shirt",
                            Sku = "sku01",
                            Category = ItemCategory.DigitalGoods,
                        },
                    }
                }
            }
        }
    };

    ApiResponse<Order> result = await _ordersController.CreateOrderAsync(createOrderInput);
    return result;
}

protected IHttpActionResult GetInternalServerError(string content)
{
    var message = new HttpResponseMessage(HttpStatusCode.InternalServerError)
    {
        Content = new StringContent(content)
    };
    return new ResponseMessageResult(message);
}

Atualização 3: Corrigimos os links da postagem. Peço desculpas pelo erro anterior.


Solução: Aqui está o código na _CreateOrderAsync()ação do controlador que corrigiu o problema, graças a @PrestonPHX:

PaymentSource = new PaymentSource
{
    Paypal = new PaypalWallet
    {
        ExperienceContext = new PaypalWalletExperienceContext
        {
            ShippingPreference = PaypalWalletContextShippingPreference.NoShipping
        }
    }
},
javascript
  • 1 respostas
  • 87 Views
Martin Hope
Enric Terradellas
Asked: 2025-04-08 18:49:17 +0800 CST

Como abrir meu aplicativo Android ao tocar em um arquivo?

  • 5

Quero permitir que meu aplicativo angular iônico apareça como uma opção quando os usuários tocarem em arquivos .gpx em um dispositivo Android.

Para fazer isso, editei meu AndroidManifest.xml, mas não consegui fazê-lo funcionar. Agora, meu manifesto está assim:

<?xml version='1.0' encoding='utf-8'?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <application
        android:allowBackup="false"
        android:fullBackupContent="false"
        android:largeHeap="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:usesCleartextTraffic="true"
        android:requestLegacyExternalStorage="true">
        <activity
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode|navigation"
            android:exported="true"
            android:label="@string/title_activity_main"
            android:launchMode="singleInstance"
            android:name=".MainActivity"
            android:theme="@style/AppTheme.NoActionBarLaunch">
          <!-- Primary filter for GPX with correct MIME type -->
          <intent-filter>
              <action android:name="android.intent.action.VIEW" />
              <category android:name="android.intent.category.DEFAULT" />
              <category android:name="android.intent.category.BROWSABLE" />
              <data android:scheme="content" />
              <data android:mimeType="application/gpx+xml" />
          </intent-filter>

          <!-- Fallback filter for content URI with any MIME type but .gpx extension -->
          <intent-filter>
              <action android:name="android.intent.action.VIEW" />
              <category android:name="android.intent.category.DEFAULT" />
              <category android:name="android.intent.category.BROWSABLE" />
              <data android:scheme="content" />
              <data android:mimeType="*/*" />
              <data android:host="*" />
              <data android:pathPattern=".*\\.gpx" />
          </intent-filter>

          <!-- Filter for file:// URIs with .gpx extension -->
          <intent-filter>
              <action android:name="android.intent.action.VIEW" />
              <category android:name="android.intent.category.DEFAULT" />
              <category android:name="android.intent.category.BROWSABLE" />
              <data android:scheme="file" />
              <data android:mimeType="*/*" />
              <data android:pathPattern=".*\\.gpx" />
          </intent-filter>

          <!-- Additional filters for common MIME types used for GPX files -->
          <intent-filter>
              <action android:name="android.intent.action.VIEW" />
              <category android:name="android.intent.category.DEFAULT" />
              <category android:name="android.intent.category.BROWSABLE" />
              <data android:scheme="content" />
              <data android:mimeType="application/xml" />
          </intent-filter>

          <intent-filter>
              <action android:name="android.intent.action.VIEW" />
              <category android:name="android.intent.category.DEFAULT" />
              <category android:name="android.intent.category.BROWSABLE" />
              <data android:scheme="content" />
              <data android:mimeType="text/xml" />
          </intent-filter>
        </activity>
        <provider
            android:authorities="${applicationId}.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true"
            android:name="androidx.core.content.FileProvider">
            <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" />
        </provider>
        <receiver android:name="io.capawesome.capacitorjs.plugins.foregroundservice.NotificationActionBroadcastReceiver" />
        <service
            android:name="io.capawesome.capacitorjs.plugins.foregroundservice.AndroidForegroundService"
            android:foregroundServiceType="location"
            android:stopWithTask="true" />
    </application>
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
    <uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
    <uses-feature android:name="android.hardware.location.gps" />
</manifest>

Eu verifiquei no meu dispositivo Android 15. Toquei em um arquivo .gpx em dois gerenciadores de arquivos diferentes, bem como em um arquivo compartilhado via WhatsApp, mas meu aplicativo nunca aparece.

  • 2 respostas
  • 52 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