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
chintan patel
Asked: 2025-04-14 20:20:30 +0800 CST

Estou enfrentando um problema ao clicar no elemento suspenso

  • 5

Estou tentando acessar dados de "https://www.nseindia.com/report-detail/eq_security", mas quando insiro um símbolo, por exemplo, "INFY", preciso selecionar a ação no menu suspenso. Tentei usar o Selenium para clicar na primeira opção do menu suspenso, pois os símbolos são únicos, então a primeira opção deveria ser minha ação. Mas não consigo visualizar o menu suspenso. Alguém pode sugerir como clico na primeira opção do menu suspenso e, em seguida, obtenho os dados da tabela abaixo?

Até agora construí abaixo:

import undetected_chromedriver as uc
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import random

# Start undetected Chrome
driver = uc.Chrome()
driver.get("https://www.nseindia.com/report-detail/eq_security")

# Wait for the page to load
time.sleep(5)

# Step 1: Find the symbol input field
symbol_input = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.XPATH, '//*[@id="hsa-symbol"]'))
)

# Step 2: Click on it and type 'INFY' with delays
symbol_input.click()
time.sleep(1)

# Human-like typing
for char in "INFY":
    symbol_input.send_keys(char)
    time.sleep(random.uniform(0.3, 0.6))

# Step 3: Wait for the dropdown to be visible
try:
    # Wait for the dropdown to be visible
    dropdown = WebDriverWait(driver, 15).until(
        EC.visibility_of_element_located((By.XPATH, '//ul[contains(@class, "ui-autocomplete")]'))
    )

    # Print the HTML of the dropdown to verify it's visible
    dropdown_html = driver.page_source
    if 'ui-autocomplete' in dropdown_html:
        print("✅ Dropdown is visible.")
    else:
        print("❌ Dropdown not visible.")

    # Locate all the dropdown items
    dropdown_items = driver.find_elements(By.XPATH, '//ul[contains(@class, "ui-autocomplete")]/li')
    
    if dropdown_items:
        print("✅ Dropdown items found.")
        for item in dropdown_items:
            print(item.text)  # Print all options
        # Ensure the first item is in view
        driver.execute_script("arguments[0].scrollIntoView();", dropdown_items[0])

        # Click the first item using JavaScript
        driver.execute_script("arguments[0].click();", dropdown_items[0])
        print("✅ Clicked on the first dropdown item.")
    else:
        print("❌ No dropdown items found.")
except Exception as e:
    print(f"❌ Error: {str(e)}")
python
  • 2 respostas
  • 53 Views
Martin Hope
gusto2
Asked: 2025-04-14 20:02:54 +0800 CST

Dados de publicidade Bluetooth

  • 5

Criei um pequeno PoC no rp-pico usando o btstack, basicamente uma reformulação do serviço BLE simples e autônomo .

Como no exemplo, o BLE usa dados de anúncios e, no exemplo, há alguns valores constantes sem explicação, assim como a documentação não é muito clara sobre os dados

Dados de anúncios em server_common.c :

#define APP_AD_FLAGS 0x06
static uint8_t adv_data[] = {
    // Flags general discoverable
    0x02, BLUETOOTH_DATA_TYPE_FLAGS, APP_AD_FLAGS,
    // Name
    0x17, BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME, 'P', 'i', 'c', 'o', ' ', '0', '0', ':', '0', '0', ':', '0', '0', ':', '0', '0', ':', '0', '0', ':', '0', '0',
    0x03, BLUETOOTH_DATA_TYPE_COMPLETE_LIST_OF_16_BIT_SERVICE_CLASS_UUIDS, 0x1a, 0x18,
};

Gostaria de saber: qual é o significado dos valores?

  • APP_AD_FLAGS 0x06
  • UUIDS_DE_CLASSE_DE_SERVIÇO, 0x1a, 0x18
bluetooth-lowenergy
  • 1 respostas
  • 31 Views
Martin Hope
c0sx86
Asked: 2025-04-14 20:02:23 +0800 CST

Arduino Nano não lê dados do UART Shell corretamente

  • 7

Ultimamente, tenho me dedicado à programação bare-metal com o Arduino-Nano e queria brincar com o UART protocool. Criei um "shell" simples usando Rust na minha máquina host que, ao enviar o comando "ledON" ou "ledOFF", ligava ou desligava o LED embutido no nano.

O código C no Nano é o seguinte

Arquivo de cabeçalho (avr-uart.h):

#include <stdint.h>


// Register Defines

#define UBRR0L      (*(volatile uint8_t *)0xC4)
#define UBRR0H      (*(volatile uint8_t *)0xC5)
#define UCSR0A      (*(volatile uint8_t *)0xC0)
#define UCSR0B      (*(volatile uint8_t *)0xC1)
#define UCSR0C      (*(volatile uint8_t *)0xC2)
#define UDR0        (*(volatile uint8_t *)0xC6)


// Register Bit Defines  
#define RXEN0       5                   // USART Receiver
#define TXEN0       4                   // USART Transmitter 
#define USBS0       3                   // Sets number of stop bits 
#define UCSZ00      1                   // Sets Character Size
#define UDRE0       5
#define RXC0        7

// Constant Defines 
#define CLOCK_SPEED     16000000                // MCU Clock Speed 
#define BAUD        115200                  // BAUD rate 
#define MYUBRR      CLOCK_SPEED / 16 / BAUD - 1         // UART Baud Rate 



/*
 * Function Desc: Function to handle Data buffer transfer
 * @param data  => Buffer holding the data to be transmitted 
*/
void USART_Transmit(unsigned char data) {

    // Wait for empty transmit buffer
    while ( !( UCSR0A & (1 << UDRE0)));

    // Puts data in the buffer and sends data 
    UDR0 = data; 
}




/*
 * Function Desc: Function to handle Data Reception 
*/
volatile uint8_t USART_Recieve(void) {
    
    while ( !( UCSR0A & (1 << RXC0)));

    return UDR0;

}

/*
 * Function Desc: Function to handling Printing strings to UART
 * @param *data => Pointer to data buffer
*/
void USART_Print(const char* data) {

    while (*data) {
        USART_Transmit(*data++);
    }
}

/*
 * Function Desc: Function to handle USART setup for Data Transmission and Reception
 * @param ubrr  => BAUD Rate 
*/
void USART_Init(unsigned int ubrr) {

    // This sets BAUD Rate 
    UBRR0H = (unsigned char) (ubrr >> 8);   // Zeroes out higher bit register (according to datasheet) 
    UBRR0L = (unsigned char) ubrr;      // Sets lower bit register baud rate 


    // Enable Receiver and Transmitter 
    UCSR0B = (1 << RXEN0) | (1 << TXEN0);

    // Sets frame format 
    UCSR0C = (1 << USBS0) | (3 << UCSZ00);

}

Arquivo principal:

#include "avr-uart.h"
#include <stdint.h>
#include <string.h>

#define BUFFER_SIZE 50
#define DDRB        (*(volatile uint8_t *)0x24)         // Address of DDRB Register
#define PORTB       (*(volatile uint8_t *)0x25)         // Address of PORTB Register
#define PB5     5                       // PB5 (Port B, bit 5)

int main(void) {

  // Sets the DDRB Register to Output
  DDRB |= (1 << PB5);

  // Initializes UART on the Micro-controller
  USART_Init(MYUBRR);

  char commandBuffer[BUFFER_SIZE];

  uint8_t buffer = 0;

  while (1) {

    // Save the received character in a single char variable
    char received = USART_Recieve();

    // Echo the character
    USART_Transmit(received);

    if (received == '\n' || received == '\r') {

      commandBuffer[buffer] = '\0';

      if (strcmp(commandBuffer, "ledON") == 0) {

        PORTB |= (1 << PB5); // Turns on the LED
        USART_Print("\r\n[NANO] INTERACTED WITH LED\r\n");
      }

      if (strcmp(commandBuffer, "ledOFF") == 0) {

        PORTB &= ~(1 << PB5);   // Turns off the LED
        USART_Print("\r\n[NANO] INTERACTED WITH LED\r\n");
      }

      else {
        USART_Print("\r\n[NANO] INVALID COMMAND\r\n");
      }

      buffer = 0;
    }

    else {
      if (buffer < BUFFER_SIZE - 1) {
        commandBuffer[buffer++] = received;
      }
    }
  }
}

E finalmente o shell simples que escrevi em rust:

use std::io::{self, Write, Read};
use std::time::Duration;
use serialport::SerialPort;

fn main() {


    // Variables for Serial Port name and BAUD rate 
    let port_name = "/dev/ttyUSB1";
    let baud = 115200;

    println!("[!] Initializing Arduino-Nano c0smic Shell! :)\n");


    // Opens a serial port connection to the Arduino
    let mut port = serialport::new(port_name, baud)
        .timeout(Duration::from_millis(1000))
        .open().expect("Failed to open port");

    println!("[!] Successfully connected to serial port /dev/ttyUSB1!\n");
 
    println!("Shell is initialized, you may start sending commands :)\n");

    let mut inputBuffer = String::new();

    loop {

        print!(">> ");
        io::stdout().flush().unwrap();

        inputBuffer.clear();
        // Creates input buffer for commands 

        // Clears reads line 
        io::stdin().read_line(&mut inputBuffer).expect("Failed to read line!");

        // Trims command buffer 
        let inputBuffer: String = inputBuffer.trim().parse().expect("Failed to clean buffer");


        if inputBuffer == "ledON" || inputBuffer == "ledOFF" {
           

            // Sends data as bytes 
            port.write_all(format!("{}\n", inputBuffer).as_bytes()).unwrap();

            // Makes the CPU wait (sleep) for 500 ms 
            std::thread::sleep(Duration::from_millis(500));


            // Creates buffer for receiving data from Nano 
            let mut buffer = [0u8; 128];

            match port.read(&mut buffer) {
                Ok(n) if n > 0 => {
                    let response = String::from_utf8_lossy(&buffer[..n]);
                    println!("{}", response);
                }
    
                // Checks if a response is received or if there is an error 
                Ok(_) => println!("No response receieved"),
                Err(e) => println!("Failed to read: {}", e),
            }

        } else {
            println!("[!] Error ::: Invalid Command!\n");
        }
    }

}

O Makefile para compilação:

default: build

build:
    avr-gcc -Os -DF_CPU=16000000UL -mmcu=atmega328p main.c -o main 

burn: build 
    avr-objcopy -O ihex -R .eeprom main main.hex 

    avrdude -F -V -c arduino -pm328p -P /dev/ttyUSB1 -b 115200 -U flash:w:main.hex 

Consegui confirmar que o shell Rust consegue se conectar ao Arduino e realmente enviar dados (já que o LED RX pisca toda vez que envio o comando), mas sempre que o shell aguarda uma resposta, recebo o erro "Timed Out". Pelo que entendi, o Arduino Nano não consegue ler os dados enviados corretamente. Qualquer ajuda é bem-vinda. Obrigada!

c
  • 1 respostas
  • 83 Views
Martin Hope
Cheok Yan Cheng
Asked: 2025-04-14 20:02:05 +0800 CST

Firebase no iOS: avaliando a necessidade de atualização manual de tokens

  • 6

Atualmente, estou usando o seguinte código no meu cliente iOS para determinar se precisamos apresentar uma tela de login:

if Auth.auth().currentUser == nil

Aqui está a lógica da tela de login:

      @objc func handleAppleSignUp() {
          Analytics.logEvent("handleAppleSignUp", parameters: nil)
          
          appleSignUpButton?.stopPulseAnimation()
          
          startSignInWithAppleFlow()
      }

      //
      // https://firebase.google.com/docs/auth/ios/apple
      //
      
      @available(iOS 13, *)
      func startSignInWithAppleFlow() {
        let nonce = randomNonceString()
        currentNonce = nonce
        let appleIDProvider = ASAuthorizationAppleIDProvider()
        let request = appleIDProvider.createRequest()
        request.requestedScopes = [.fullName, .email]
        request.nonce = sha256(nonce)

        let authorizationController = ASAuthorizationController(authorizationRequests: [request])
        authorizationController.delegate = self
        authorizationController.presentationContextProvider = self
        authorizationController.performRequests()
      }
      
      private func randomNonceString(length: Int = 32) -> String {
        precondition(length > 0)
        var randomBytes = [UInt8](repeating: 0, count: length)
        let errorCode = SecRandomCopyBytes(kSecRandomDefault, randomBytes.count, &randomBytes)
        if errorCode != errSecSuccess {
          fatalError(
            "Unable to generate nonce. SecRandomCopyBytes failed with OSStatus \(errorCode)"
          )
        }

        let charset: [Character] =
          Array("0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._")

        let nonce = randomBytes.map { byte in
          // Pick a random character from the set, wrapping around if needed.
          charset[Int(byte) % charset.count]
        }

        return String(nonce)
      }

      @available(iOS 13, *)
      private func sha256(_ input: String) -> String {
        let inputData = Data(input.utf8)
        let hashedData = SHA256.hash(data: inputData)
        let hashString = hashedData.compactMap {
          String(format: "%02x", $0)
        }.joined()

        return hashString
      }
  }

  // https://fluffy.es/sign-in-with-apple-tutorial-ios/
  extension LoginViewController:  ASAuthorizationControllerPresentationContextProviding {
      func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
          // Return the window of the current view controller
          return self.view.window!
      }
  }

  extension LoginViewController: ASAuthorizationControllerDelegate {
      func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
        if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential {
          guard let nonce = currentNonce else {
            fatalError("Invalid state: A login callback was received, but no login request was sent.")
          }
          guard let appleIDToken = appleIDCredential.identityToken else {
            print("Unable to fetch identity token")
            return
          }
          guard let idTokenString = String(data: appleIDToken, encoding: .utf8) else {
            print("Unable to serialize token string from data: \(appleIDToken.debugDescription)")
            return
          }
          // Initialize a Firebase credential, including the user's full name.
          let credential = OAuthProvider.appleCredential(withIDToken: idTokenString,
                                                            rawNonce: nonce,
                                                            fullName: appleIDCredential.fullName)
            
          EmulatorUtils.authUseEmulatorIfPossible()
          
          // Sign in with Firebase.
          Auth.auth().signIn(with: credential) { (authResult, error) in
            if let error = error {
              // Error. If error.code == .MissingOrInvalidNonce, make sure
              // you're sending the SHA256-hashed nonce as a hex string with
              // your request to Apple.
              print(error.localizedDescription)
              return
            }
            // User is signed in to Firebase with Apple.
            // ...
              
              Analytics.logEvent("sign_in_success", parameters: nil)
              
              self.delegate?.updateBasedOnLoginStatus()
          }
        }
      }

      func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
        // Handle error.
        print("Sign in with Apple errored: \(error)")
      }
  }

Eu estava pensando: será que precisamos atualizar o token de login manualmente? Alguns dos meus usuários relataram que as interações com o Firebase Functions e o Firestore às vezes falham. Em todos os casos, esse problema é resolvido saindo e entrando novamente.

Se eu precisar atualizar o token de login manualmente, alguém pode explicar como e quando fazer isso?

  • 1 respostas
  • 57 Views
Martin Hope
sonic
Asked: 2025-04-14 20:01:08 +0800 CST

Ruby Koans. Por que recebo um array vazio? [duplicado]

  • 6
Esta pergunta já tem respostas aqui :
Fatiamento de array em Ruby: explicação para comportamento ilógico (retirado de Rubykoans.com) (10 respostas)
Fechado há 2 dias .

Revisito Ruby on Rails e brinco com Koans. Não entendo o porquê array[4,0]e array[4,100]retorno []em vez denil

def test_slicing_arrays
    array = [:peanut, :butter, :and, :jelly]

    assert_equal [:peanut], array[0,1]
    assert_equal [:peanut, :butter], array[0,2]
    assert_equal [:and, :jelly], array[2,2]
    assert_equal [:and, :jelly], array[2,20]
    assert_equal [], array[4,0] 
    assert_equal [], array[4,100]
    assert_equal nil, array[5,0]
  end
ruby-on-rails
  • 1 respostas
  • 70 Views
Martin Hope
Billie
Asked: 2025-04-14 19:52:56 +0800 CST

Suporte de validação do ControlsFX: mostre erros de validação no carregamento e mantenha o botão OK desabilitado até que haja uma entrada válida

  • 7

Estou trabalhando em uma aplicação JavaFX + Spring Boot usando o padrão MVVM. Usamos o ControlsFX ValidationSupport para validar campos em um formulário de login. Nosso objetivo é:

  • Mostrar ícones de erro vermelhos ("decorações") imediatamente quando a página carrega, se os campos estiverem vazios ou inválidos

  • Mantenha o botão OK desabilitado até que todas as regras de validação sejam aprovadas

Exemplo:

Temos uma caixa de diálogo para criar um novo usuário com estes campos:

  • Nome de usuário (TextField)
  • Senha (PasswordField)
  • Repita a senha (PasswordField)

Registramos Validadores assim:

@Component
public class ValidationHelper {

    public void registerUserRegistrationValidations(ValidationSupport validationSupport, TextField userName,
                                                    PasswordField password, PasswordField repeatPassword) {
        registerFocusLostValidation(userName, getEnteredUserNameDataLengthValidator(), validationSupport);
        registerFocusLostValidation(password, getEnteredPasswdDataLengthValidator(), validationSupport);
        registerFocusLostValidation(repeatPassword, getEnteredPasswdDataLengthValidator(), validationSupport);
        registerFocusLostValidation(repeatPassword, getEnteredPasswordsEqualValidator(repeatPassword), validationSupport);
    }

    private Validator<Object> getEnteredUserNameDataLengthValidator() {
        return Validator.createPredicateValidator(
                userName -> userName != null && ((String) userName).length() > 2,
                "user name too short");
    }

    private Validator<Object> getEnteredPasswdDataLengthValidator() {
        return Validator.createPredicateValidator(
                pin -> pin != null && ((String) pin).length() > 2,
                "Password too short");
    }

    private Validator<Object> getEnteredPasswordsEqualValidator(PasswordField passwdField) {
        return Validator.createPredicateValidator(
                password -> password != null && password.equals(passwdField.getText()),
                "Passwords do not match");
    }

    private <T> void registerFocusLostValidation(Control control, Validator<T> validator, ValidationSupport validationSupport) {
        validationSupport.registerValidator(control, false, validator);
    }
}

Também fazemos isso para vincular um sinalizador global:

BooleanBinding isInvalid = Bindings.createBooleanBinding(
    () -> !validationSupport.getValidationResult().getErrors().isEmpty(),
    validationSupport.validationResultProperty()
);
validationState.formInvalidProperty().bind(isInvalid);

Então no controlador de rodapé:

okButton.disableProperty().bind(validationState.formInvalidProperty());

O Problema

Isso geralmente funciona, mas somente depois que o usuário começa a digitar.

Inicialmente:

  • A página carrega sem nenhum círculo vermelho de validação
  • O botão OK fica ativo muito cedo (após digitar a primeira senha)
  • A validação para repetição de senha só é acionada após perda de foco

Queremos que a validação apareça assim que o formulário for exibido, sem interação do usuário. Tentativas

  • Tentamos Platform.runLater(validationSupport::revalidate)
  • Tentamos definir required = true em registerValidator
  • Também tentamos chamar validationSupport.getValidationResult().getErrors() manualmente, mas o estado inicial é sempre visto como "válido".

Alguma ideia de como fazer a validação ser acionada imediatamente e garantir que o botão OK se comporte corretamente desde o início?

Testado com o ControlsFX versão 11.1.1 (ou o que você estiver usando) e JavaFX 22.

Exemplo Mínimo Reproduzível

ControlsFxApp.java

package controlsFx;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;

import java.io.IOException;
import java.net.URL;

@SpringBootApplication
public class ControlsFxApp extends Application {
    private static final String RESOURCE = "sample.fxml";
    private ConfigurableApplicationContext springContext;

    @Override
    public void init() {
        springContext = new SpringApplicationBuilder(ControlsFxApp.class).run();
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        Parent root = load(RESOURCE);
        Scene scene = new Scene(root);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public Parent load(String fxmlPath) throws IOException {
        URL location = getClass().getResource(fxmlPath);
        FXMLLoader fxmlLoader = new FXMLLoader(location);
        fxmlLoader.setControllerFactory(springContext::getBean);
        return fxmlLoader.load();
    }
}

FooterController.java

package controlsFx;

import javafx.fxml.FXML;
import javafx.scene.control.Button;
import org.springframework.stereotype.Controller;

@Controller
public class FooterController {
    private final ValidationState validationState;
    public Button register;

    public FooterController(ValidationState validationState) {
        this.validationState = validationState;
    }

    @FXML
    private void initialize() {
        register.setOnAction(event -> {
            System.out.println("Validation requested for the current step...");
        });
        register.disableProperty().bind(validationState.formInvalidProperty());
    }
}

Controlador de Registro.java

package controlsFx;

import javafx.application.Platform;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.BooleanBinding;
import javafx.fxml.FXML;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import org.controlsfx.validation.ValidationSupport;
import org.controlsfx.validation.decoration.GraphicValidationDecoration;
import org.springframework.stereotype.Controller;

@Controller
public class RegistrationController {
    private final ValidationHelper validationHelper;
    private final ValidationSupport validationSupport = new ValidationSupport();
    private final ValidationState validationState;
    public TextField userName;
    public PasswordField password;
    public PasswordField repeatPassword;

    public RegistrationController(ValidationHelper validationHelper, ValidationState validationState) {
        this.validationHelper = validationHelper;
        this.validationState = validationState;
    }

    @FXML
    public void initialize() {
        validationSupport.setValidationDecorator(new GraphicValidationDecoration());
        validationHelper.registerUserRegistrationValidations(validationSupport, userName, password, repeatPassword);
        Platform.runLater(() -> {
            validationSupport.revalidate();

            BooleanBinding isInvalid = Bindings.createBooleanBinding(
                    () -> !validationSupport.getValidationResult().getErrors().isEmpty(),
                    validationSupport.validationResultProperty()
            );
            validationState.formInvalidProperty().bind(isInvalid);
        });
    }
}

ValidationHelper.java

package controlsFx;

import javafx.scene.control.Control;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import org.controlsfx.validation.ValidationSupport;
import org.controlsfx.validation.Validator;
import org.springframework.stereotype.Component;

@Component
public class ValidationHelper {

    public void registerUserRegistrationValidations(ValidationSupport validationSupport, TextField userName,
                                                    PasswordField password, PasswordField repeatPassword) {
        registerFocusLostValidation(userName, getEnteredUserNameDataLengthValidator(), validationSupport);
        registerFocusLostValidation(password, getEnteredPasswdDataLengthValidator(), validationSupport);
        registerFocusLostValidation(repeatPassword, getEnteredPasswdDataLengthValidator(), validationSupport);
        registerFocusLostValidation(repeatPassword, getEnteredPasswordsEqualValidator(repeatPassword), validationSupport);
    }

    private Validator<Object> getEnteredUserNameDataLengthValidator() {
        return Validator.createPredicateValidator(
                userName -> userName != null && ((String) userName).length() > 2,
                "user name too short");
    }

    private Validator<Object> getEnteredPasswdDataLengthValidator() {
        return Validator.createPredicateValidator(
                pin -> pin != null && ((String) pin).length() > 2,
                "Password too short");
    }

    private Validator<Object> getEnteredPasswordsEqualValidator(PasswordField passwdField) {
        return Validator.createPredicateValidator(
                password -> password != null && password.equals(passwdField.getText()),
                "Passwords do not match");
    }

    private <T> void registerFocusLostValidation(Control control, Validator<T> validator, ValidationSupport validationSupport) {
        validationSupport.registerValidator(control, false, validator);
    }
}

Estado de Validação.java

package controlsFx;

import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import org.springframework.stereotype.Component;

@Component
public class ValidationState {
    private final BooleanProperty formInvalid = new SimpleBooleanProperty(true);

    public BooleanProperty formInvalidProperty() {
        return formInvalid;
    }
}

centro.fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane xmlns:fx="http://javafx.com/fxml"
            xmlns="http://javafx.com/javafx"
            fx:controller="controlsFx.RegistrationController"
            prefHeight="400.0" prefWidth="600.0">
    <VBox AnchorPane.bottomAnchor="30" AnchorPane.leftAnchor="30" AnchorPane.rightAnchor="30"
          AnchorPane.topAnchor="30">
        <Label>User Name:</Label>
        <TextField fx:id="userName" id="userName"/>
        <Label>Password:</Label>
        <PasswordField fx:id="password" id="password"/>
        <Label>Repeat Password:</Label>
        <PasswordField fx:id="repeatPassword" id="password"/>
    </VBox>
</AnchorPane>

rodapé.xml

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane xmlns:fx="http://javafx.com/fxml"
            xmlns="http://javafx.com/javafx" prefHeight="400.0" prefWidth="600.0"
            fx:controller="controlsFx.FooterController">
    <Button fx:id="register" layoutX="33.0" layoutY="187.0" prefHeight="25.0" prefWidth="534.0" text="Register"/>
</AnchorPane>

amostra.fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.text.Font?>
<BorderPane xmlns:fx="http://javafx.com/fxml" xmlns="http://javafx.com/javafx" prefWidth="200" prefHeight="200"
            fx:id="borderPaneId">
    <top>
        <AnchorPane BorderPane.alignment="CENTER">
            <Label text="Registration">
                <font>
                    <Font size="24.0"/>
                </font>
            </Label>
            <BorderPane.margin>
                <Insets/>
            </BorderPane.margin>
        </AnchorPane>
    </top>
    <center>
        <fx:include source="center.fxml"/>
    </center>
    <bottom>
        <fx:include source="footer.fxml"/>
    </bottom>
</BorderPane>

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>controlsFx</groupId>
    <artifactId>validationdemo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>17</java.version>
        <javafx.version>22</javafx.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-controls</artifactId>
            <version>${javafx.version}</version>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-fxml</artifactId>
            <version>${javafx.version}</version>
        </dependency>
        <dependency>
            <groupId>org.controlsfx</groupId>
            <artifactId>controlsfx</artifactId>
            <version>11.1.2</version>
        </dependency>
    </dependencies>
</project>
java
  • 1 respostas
  • 98 Views
Martin Hope
Evan Lynch
Asked: 2025-04-14 19:30:33 +0800 CST

Como especificar o local onde o arquivo Pandas para CSV está armazenado no meu diretório [duplicado]

  • 6
Esta pergunta já tem respostas aqui :
Como unir caminhos de forma agradável? (2 respostas)
Como posso criar um caminho completo para um arquivo a partir de partes (por exemplo, caminho para a pasta, nome e extensão)? (7 respostas)
Fechado há 2 dias .

Então, não sei como salvar o arquivo csv que este código cria em uma pasta específica no meu diretório. Qualquer ajuda seria bem-vinda!

#Store rows which do not conform to the relationship in a new dataframe
subset = df[df['check_total_relationship'] == False]`

subset.to_csv('false_relationships.csv', index=False, header=True, encoding='utf-8')`
python
  • 1 respostas
  • 48 Views
Martin Hope
Yosu
Asked: 2025-04-14 19:12:51 +0800 CST

Editar o recurso Calendário completoTimelineMonth para exibir semanas completas

  • 5

No meu projeto, utilizo a visualização resourceTimelineMonth com fullCalendar. A visualização começa no dia 1 e termina no final do mês. Mas preciso exibir a primeira semana completa e a última semana completa. Por exemplo, para abril de 2025, a primeira é uma quinta-feira, então preciso exibir a segunda-feira, 31, e o dia 30 de abril é uma quarta-feira, então preciso exibir a quinta, sexta, sábado e domingo desta semana.

Vi que podemos usar visualizações como esta:

views: {
            resourceTimelineMonthEdited: {
                type: 'resourceTimelineMonth',
                duration: {weeks: 5},
                dateAlignment: '2025-03-31'
            }
        },

Mas o início da visualização é o dia atual e não o 1º. E recebi este erro:

Cannot read properties of undefined (reading 'getUTCFullYear')

Eu também tentei usar visibleRange assim:

calendar.setOption('visibleRange', {
  start: '2025-03-31',
  end: '2025-05-04'
});

Mas nada acontece.

javascript
  • 1 respostas
  • 30 Views
Martin Hope
meez
Asked: 2025-04-14 19:12:08 +0800 CST

Como substituir o estilo quando ambas as condições são verdadeiras com o CSS do Tailwind

  • 5

No meu componente Astro, estou usando class:list para meu estilo tailwind.

Tenho a seguinte situação, em que ambas as condições são true, e quero isRedColorestar na liderança. Como posso resolver isso?

<span
  class:list={[
    'text-large bg-gray text-white font-bold',
    { 'bg-orange': theme === "orange" },
    { 'bg-red': isRedColor },
    classes,
  ]}
>
  {title}
</span>
conditional-statements
  • 1 respostas
  • 31 Views
Martin Hope
Erik Hart
Asked: 2025-04-14 19:09:01 +0800 CST

AzureDevOps: NuGetCommand@2 push para DotNetCoreCLI@2 nuget push personalizado, com feed VSTS?

  • 7
  • Construir máquina Ubuntu 24.04
  • É necessário substituir a tarefa NuGetCommand@2 por DotNetCoreCLI@2 .
  • Enviar para o feed privado do AzureDevOps ("VSTS", nome antigo de antes do AzureDevOps)
  • É necessário executar o comando push com a opção --skip-duplicate(parâmetro allowPackageConflicts: true na tarefa antiga).
  • É necessário substituir publishVstsFeed:<guid1>/<guid2> na tarefa por --source <URL>. Como?

Em um pipeline no Ubuntu 24.04, a antiga tarefa NuGetCommand@2 não funciona mais, porque requer o .NET Mono, que não faz mais parte das máquinas de compilação do Ubuntu 24.04.

  • Comando _DotNetCoreCLI@2: 'push' não suporta allowPackageConflicts: true nem argumentos: '--skip-duplicate' .

Então termino com algo parecido com esta tarefa:

  - task: DotNetCoreCLI@2
    displayName: DotNet NuGet push
    inputs:
      # required, because NuGetCommand@2 allowPackageConflicts missing.
      command: 'custom'
      custom: 'nuget'
      # --skip-duplicate is the direct option 
      # to replace allowPackageConflicts: true. 
      arguments: 'push $(Build.SourcesDirectory)/packagesMyPacksDir/*.nupkg --source https://pkgs.dev.azure.com/my-company/<guid1>/_packaging/<guid2>/nuget/v3/index.json -ApiKey VSTS'

Mas com um comando personalizado, todas as opções para resolver o URL do feed, como acontecia internamente na antiga tarefa NuGetCommand@2 ou com DotNetCoreCLI push , não funcionam.

Minha ideia era simplesmente inserir <guid1> e <guid2> na --sourceURL, mas quando observei compilações mais antigas, com a tarefa NuGetCommand@2 , percebi que o segundo GUID não era o valor /<guid2> do publishVstsFeed:<guid1>/<guid2> anterior , mas outro GUID a cada nova execução de pipeline.

Então, como eu crio a --sourceURL?

Alternativa possível: se houvesse uma chance de listar todos os pacotes NuGet para enviar e usar os comandos push do DotNetCoreCLI em um loop, isso poderia funcionar sem criar uma URL de origem, mas ainda não encontrei nenhuma maneira de fazer um loop em um número variável de arquivos.

  • 3 respostas
  • 71 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