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-1634905

sudoExclamationExclamation's questions

Martin Hope
sudoExclamationExclamation
Asked: 2025-04-29 02:53:20 +0800 CST

Como fazer com que a borda de gradiente móvel do iOS continue se movendo em uma direção para sempre sem redefinir para o local original?

  • 5

O código abaixo mostra o problema:

import UIKit
import SnapKit

class ViewController: UIViewController {

    let animatedBorderView = AnimatedGradientBorderView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        animatedBorderView.layer.cornerRadius = 20
        animatedBorderView.clipsToBounds = true
        view.addSubview(animatedBorderView)
        animatedBorderView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.size.equalTo(400)
        }
    }
}

class AnimatedGradientBorderView: UIView {
    
    private let gradientLayer = CAGradientLayer()
    private let shapeLayer = CAShapeLayer()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupLayers()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupLayers()
    }
    
    private func setupLayers() {
        gradientLayer.startPoint = CGPoint(x: 0, y: 0)
        gradientLayer.endPoint = CGPoint(x: 1, y: 1)
        gradientLayer.colors = [
            UIColor.systemRed.cgColor,
            UIColor.systemYellow.cgColor,
            UIColor.systemGreen.cgColor,
        ]
        gradientLayer.locations = [0, 0.3, 0.6, 1]
        layer.addSublayer(gradientLayer)
        
        shapeLayer.lineWidth = 5
        shapeLayer.fillColor = nil
        shapeLayer.strokeColor = UIColor.black.cgColor
        gradientLayer.mask = shapeLayer
        
        startAnimating()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        gradientLayer.frame = bounds
        let path = UIBezierPath(roundedRect: bounds.insetBy(dx: shapeLayer.lineWidth / 2, dy: shapeLayer.lineWidth / 2), cornerRadius: layer.cornerRadius)
        shapeLayer.path = path.cgPath
    }
    
    private func startAnimating() {
        let animation = CABasicAnimation(keyPath: "locations")
        animation.fromValue = [0, 0.2, 0.4, 0.6]
        animation.toValue = [0.4, 0.6, 0.8, 1]
        animation.duration = 2.0
        animation.repeatCount = .infinity
        animation.autoreverses = false
        gradientLayer.add(animation, forKey: "animateLocations")
    }
}

Isso produz a animação abaixo:

insira a descrição da imagem aqui

Observe que defini autoreversescomo falso porque não quero que ele reverta ao repetir para infinity. No entanto, como consequência disso, o problema é que, após o duration, ele reinicia no original location. Isso causa um salto repentino na borda do gradiente móvel.

Como posso fazer com que ele continue se movendo para sempre na mesma direção sem precisar reiniciar?

  • 1 respostas
  • 50 Views
Martin Hope
sudoExclamationExclamation
Asked: 2025-04-16 04:13:43 +0800 CST

A documentação do iOS da Apple está incorreta sobre a substituição de classes registradas anteriormente com o mesmo identificador de reutilização pela nova cellClass?

  • 0

A documentação da Apple diz que:

Se você registrou anteriormente uma classe ou arquivo nib com o mesmo identificador de reutilização, a classe especificada no cellClassparâmetro substituirá a entrada antiga. Você pode especificar nil"for" cellClassse desejar cancelar o registro da classe do identificador de reutilização especificado.

Até onde sei, isso não parece estar correto.

O código de exemplo simples abaixo demonstra o problema. Basicamente, tenho um controle deslizante que altera o valor do preenchimento. Quando o preenchimento muda, ele deve registrar novamente (substituir a entrada antiga) a classe com o identificador de reutilização e recarregar a tabela para mostrar o novo preenchimento:

import UIKit
import SnapKit

extension String {
    static let kPadding = Self("padding")
    static let cellId = Self("cell")
}

class ViewController: UIViewController, UITableViewDataSource {
    
    let tableView = UITableView(frame: .zero, style: .plain)

    override func viewDidLoad() {
        super.viewDidLoad()
        
        registerCell()
        tableView.dataSource = self
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.horizontalEdges.top.equalToSuperview()
        }
        
        let slider = UISlider()
        slider.isContinuous = false
        slider.minimumValue = 0
        slider.maximumValue = 100
        slider.value = UserDefaults.standard.float(forKey: .kPadding)
        slider.addTarget(self, action: #selector(sliderChanged(slider:)), for: .valueChanged)
        
        view.addSubview(slider)
        slider.snp.makeConstraints { make in
            let padding = 15.0
            make.horizontalEdges.bottom.equalTo(view.safeAreaLayoutGuide).inset(padding)
            make.top.equalTo(tableView.snp.bottom).offset(padding)
        }
        
    }
    
    @objc func sliderChanged(slider : UISlider) {
        print("sliderChanged: \(slider.value)")
        UserDefaults.standard.set(slider.value, forKey: .kPadding)
        registerCell()
        tableView.reloadData()
    }
    
    func registerCell(){
        tableView.register(Cell.self, forCellReuseIdentifier: .cellId)
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        100
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: .cellId) as! Cell
        
        cell.label.text = "Hello \(indexPath.row)"
        
        return cell
    }

}

class Cell: UITableViewCell {
    
    let label = UILabel()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        label.font = UIFont.systemFont(ofSize: 34, weight: .bold)
        
        contentView.addSubview(label)
        label.snp.makeConstraints { make in
            make.edges.equalToSuperview().inset(UserDefaults.standard.float(forKey: .kPadding))
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

No entanto, esse não parece ser o caso. Ele continua usando o preenchimento anterior e a entrada antiga não é substituída.

Estou entendendo errado o que a documentação da Apple diz?

  • 1 respostas
  • 80 Views
Martin Hope
sudoExclamationExclamation
Asked: 2025-03-09 05:30:45 +0800 CST

Os botões iniciais e finais do navigationBarItems do SwiftUI não aparecem no FamilyActivityPicker

  • 5

Tenho o seguinte Viewno SwiftUI para exibir FamilyActivityPicker:

import SwiftUI
import FamilyControls

struct FamilyActivityPickerView: View {
    @State private var selectionToDiscourage = FamilyActivitySelection()
    @Environment(\.dismiss) private var dismiss
    
    var body: some View {
        FamilyActivityPicker(headerText: "Select Apps to Restrict", selection: $selectionToDiscourage).navigationBarItems(leading: Button("Cancel") {
            print("Cancel!")
            dismiss()
        }, trailing: Button("Done") {
            print("Done!")
            dismiss()
        }).ignoresSafeArea().onChange(of: selectionToDiscourage) { newSelection in
            let applications = selectionToDiscourage.applications
            let categories = selectionToDiscourage.categories
            let webDomains = selectionToDiscourage.webDomains
            print("applications: \(applications), categories: \(categories), webDomains: \(webDomains)")
        }
    }
}

Entretanto, nenhum dos botões iniciais e finais do navigationBarItems está sendo exibido:

insira a descrição da imagem aqui

O que estou fazendo errado? Como devemos Cancelar ou Concluído a visualização FamilyActivityPicker?

EDITAR:

Quando uso NavigationStacko .toolbar, acabo com 2 barras de navegação, como mostrado na captura de tela abaixo, o que fica muito feio e desperdiça espaço:

import SwiftUI
import FamilyControls

struct FamilyActivityPickerView: View {
    @State private var selectionToDiscourage = FamilyActivitySelection()
    @Environment(\.dismiss) private var dismiss
    
    var body: some View {
        NavigationStack {
            FamilyActivityPicker(selection: $selectionToDiscourage).ignoresSafeArea().onChange(of: selectionToDiscourage) { newSelection in
                let applications = selectionToDiscourage.applications
                let categories = selectionToDiscourage.categories
                let webDomains = selectionToDiscourage.webDomains
                print("applications: \(applications), categories: \(categories), webDomains: \(webDomains)")
            }.toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    Button("Cancel") {
                        print("Cancel!")
                        dismiss()
                    }
                }
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button("Done") {
                        print("Done!")
                        dismiss()
                    }
                }
            }
        }
    }
}

Resultado:

insira a descrição da imagem aqui

  • 2 respostas
  • 68 Views
Martin Hope
sudoExclamationExclamation
Asked: 2025-03-08 03:56:46 +0800 CST

Por que o iOS CILightenBlendMode está alterando a cor da luz?

  • 5

Tenho a seguinte imagem de origem:

insira a descrição da imagem aqui

Estou tentando convertê-lo para:

insira a descrição da imagem aqui

Eu construí este código:

import CoreImage

if let image = UIImage(named: "demo9"), let editted = applyDuotoneEffect(to: image) {
    imageView.image = editted
}

func applyDuotoneEffect(to image: UIImage) -> UIImage? {
    guard let ciImage = CIImage(image: image) else { return nil }
    
    let context = CIContext(options: nil)
    
    let grayscaleFilter = CIFilter(name: "CIPhotoEffectMono", parameters: [kCIInputImageKey: ciImage])
    
    let solidLightColorImage = CIImage(color: CIColor(cgColor: ("efa403".toUIColor() ?? .red).cgColor)).cropped(to: ciImage.extent)
    let multiplyFilter = CIFilter(name: "CIMultiplyBlendMode", parameters: [kCIInputImageKey: grayscaleFilter?.outputImage as Any, kCIInputBackgroundImageKey: solidLightColorImage as Any])
       
    
    let solidDarkColorImage = CIImage(color: "290a59".toCIColor() ?? .black).cropped(to: ciImage.extent)
    let lightenFilter = CIFilter(name: "CILightenBlendMode", parameters: [kCIInputImageKey: multiplyFilter?.outputImage as Any, kCIInputBackgroundImageKey: solidDarkColorImage as Any])
    
    guard let outputImage = lightenFilter?.outputImage,
          let cgImage = context.createCGImage(outputImage, from: outputImage.extent) else { return nil }
    
    return UIImage(cgImage: cgImage)
}

extension String {
    func toUIColor() -> UIColor? {
        var cString = trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
        
        if (cString.hasPrefix("#")) {
            cString.remove(at: cString.startIndex)
        }
        
        if ((cString.count) != 6) {
            return nil
        }
        
        var rgbValue: UInt64 = 0
        Scanner(string: cString).scanHexInt64(&rgbValue)
        
        return UIColor(
            red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
            green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
            blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
            alpha: CGFloat(1.0)
        )
    }
}

Entretanto, o fundo amarelo não parece preciso na saída:

insira a descrição da imagem aqui

Parece que o CILightenBlendModefiltro muda a cor amarela também, embora eu esperasse que ele mudasse apenas os pretos para roxo. O que estou fazendo errado?

  • 1 respostas
  • 37 Views
Martin Hope
sudoExclamationExclamation
Asked: 2025-02-19 02:30:40 +0800 CST

Layout automático do iOS - não é possível ter altura menor que ou igual a

  • 5

Estou usando o SnapKit para layout automático no meu aplicativo iOS.

Preciso mostrar uma visualização de imagem no topo da tela. Ela terá uma imagem de altura e largura dinâmicas. Preciso que sua borda superior esteja alinhada com o topo da visualização. Preciso que ela esteja centralizada horizontalmente. Preciso que ela tenha uma margem esquerda e direita da tela maior ou igual a 10. Preciso que sua altura seja dinâmica com base no conteúdo com altura máxima igual a 300. Preciso que ela mantenha sua proporção e reduza sua largura ou altura conforme necessário automaticamente usando o layout automático.

Achei que o código abaixo deveria fazer o trabalho:

let padding = 10.0
let preview = UIImageView()

preview.setContentHuggingPriority(.required, for: .vertical)
preview.setContentHuggingPriority(.required, for: .horizontal)

preview.backgroundColor = .red
preview.contentMode = .scaleAspectFit
let image = UIImage(named: "demo3")!
preview.image = image

preview.clipsToBounds = true
view.addSubview(preview)
preview.snp.makeConstraints { make in
    make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
    make.centerX.equalToSuperview()
    make.left.right.greaterThanOrEqualToSuperview().inset(padding).priority(.required)
    make.height.lessThanOrEqualTo(300).priority(.required)
    make.width.equalTo(preview.snp.height).multipliedBy(image.size.width / image.size.height).priority(.required)
}

Isso parece funcionar bem para imagens de paisagem (largura maior que altura), mas não funciona em imagens de retrato:




Trabalhos em imagens de paisagens:

insira a descrição da imagem aqui







Falha em imagens de retrato. Observe como a altura não é mais lessThanOrEqualTo(300):

insira a descrição da imagem aqui

Isso ocorre porque o Xcode imprime um aviso de que não foi possível satisfazer as restrições e foi necessário quebrar a restrição de altura:

Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. 
    Try this: 
        (1) look at each constraint and try to figure out which you don't expect; 
        (2) find the code that added the unwanted constraint or constraints and fix it. 
(
    "<SnapKit.LayoutConstraint:[email protected]#54 UIImageView:0x7f81b19101e0.centerX == UIView:0x7f81b183dc30.centerX>",
    "<SnapKit.LayoutConstraint:[email protected]#55 UIImageView:0x7f81b19101e0.right >= UIView:0x7f81b183dc30.right - 12.0>",
    "<SnapKit.LayoutConstraint:[email protected]#56 UIImageView:0x7f81b19101e0.height <= 300.0>",
    "<SnapKit.LayoutConstraint:[email protected]#57 UIImageView:0x7f81b19101e0.width == UIImageView:0x7f81b19101e0.height * 0.666748046875>",
    "<NSLayoutConstraint:0x600003e37a20 'UIView-Encapsulated-Layout-Width' UIView:0x7f81b183dc30.width == 430   (active)>"
)

Will attempt to recover by breaking constraint 
<SnapKit.LayoutConstraint:[email protected]#56 UIImageView:0x7f81b19101e0.height <= 300.0>

Eu esperava que ele reduzisse sua largura, mantendo a proporção de aspecto para satisfazer as condições. Mas não faz isso.

  • 1 respostas
  • 22 Views
Martin Hope
sudoExclamationExclamation
Asked: 2025-02-05 16:22:10 +0800 CST

O modo CDP do SeleniumBase execute_script e avalie com javascript dá erro "SyntaxError: Declaração de retorno ilegal"

  • 6

Estou usando o SeleniumBase no modo CDP.

Estou tendo dificuldade para descobrir se isso é um problema do Python ou do SeleniumBase.

O exemplo simples abaixo mostra meu problema:

from seleniumbase import SB

with SB(uc=True, locale_code="en", headless=True) as sb:

    link = "https://news.ycombinator.com"
    
    print(f"\nOpening {link}")

    sb.wait_for_ready_state_complete(timeout=120)

    sb.activate_cdp_mode(link)

    script = f"""
function getSomeValue() {{
    return '42';
}}

return getSomeValue();
"""
    
    # data = sb.execute_script(script)
    data = sb.cdp.evaluate(script)

    print(data)

    print("Finished!")

Isso gera o erro:

seleniumbase.undetected.cdp_driver.connection.ProtocolException: 
exceptionId: 1
text: Uncaught
lineNumber: 5
columnNumber: 4
scriptId: 6
exception: 
        type: object
        subtype: error
        className: SyntaxError
        description: SyntaxError: Illegal return statement
        objectId: 3089353218542582072.1.2

Observe acima que tentei ambos sb.execute_script(script)e sb.cdp.evaluate(script)e ambos dão o mesmo problema.

Como posso executar esses scripts?

python
  • 1 respostas
  • 20 Views
Martin Hope
sudoExclamationExclamation
Asked: 2025-02-04 01:26:14 +0800 CST

Como definir o tamanho da janela no Selenium Base no modo CDP?

  • 6

Estou usando o SeleniumBase no modo CDP.

Estou tentando descobrir como definir o tamanho da janela no Modo CDP DEPOIS que o site for carregado?

Se eu usar a função não CDP sb.set_window_size(x,y), ele será detectado como bot runtimeEnableLeakpara abrir devtools em https://bot-detector.rebrowser.net :

insira a descrição da imagem aqui

Eu tentei sb.cdp.set_window_size(x,y), mas essa função parece não existir, pois trava com:

sb.cdp.set_window_size(x,y)
AttributeError: 'types.SimpleNamespace' object has no attribute 'set_window_size'

EDIT: Consegui encontrar uma solução alternativa usando sb.cdp.set_window_rect:

[screenwidth,screenheight,innerwidth,innerheight,scrollwidth,scrollheight] = sb.cdp.evaluate("return [window.screen.width, window.screen.height, window.innerWidth, window.innerHeight, document.documentElement.scrollWidth, document.documentElement.scrollHeight];")

print(f"Size: {screenwidth}, {screenheight}, {innerwidth}, {innerheight}, {scrollwidth}, {scrollheight}")

sb.cdp.set_window_rect(0,0,scrollwidth + screenwidth - innerwidth, scrollheight + screenheight - innerheight + 100)

print(f"Sleeping for some time...")
sb.sleep(random.randint(5, 8))

Existe uma maneira melhor?

selenium-webdriver
  • 1 respostas
  • 27 Views
Martin Hope
sudoExclamationExclamation
Asked: 2025-01-19 12:36:03 +0800 CST

vários fallbacks fazem com que falhem com erro interno 500

  • 5

Estou usando o framework web Axum do Rusts .

Preciso ter vários fallbacks.

O primeiro fallback é para entregar arquivos estáticos, como /script.jse /style.csslocalizados na minha staticpasta.

O segundo fallback deve ser para se alguma rota não corresponder, então preciso entregar a home page (que também é entregue quando /é correspondida). Por exemplo, para rotas falsas que renderizam uma página renderizada do lado do cliente.

CÓDIGO:

dotenv::dotenv().expect("Failed to load environment variables from .env file!");

let state = AppState {
    pool: PgPoolOptions::new().max_connections(70).connect(&std::env::var("DATABASE_URL").expect("DATABASE_URL must be set.")).await.unwrap(),
};

let api_path = "/api";

tracing_subscriber::fmt()
.with_max_level(tracing::Level::DEBUG)
.init();

let app = axum::Router::new()
    .route("/", get(home_get))
    .route_with_tsr(format!("{api_path}/submit").as_str(), post(submit_post))
    .route_with_tsr(format!("{api_path}/search").as_str(), post(search_post))
    .fallback_service(ServeDir::new(Path::new(&std::env::var("STATIC_FILES").expect("STATIC_FILES must be set."))))
    .fallback(get(home_get))
    .route_layer(axum::middleware::from_fn_with_state(state.clone(),info_middleware))
    .layer(RequestBodyLimitLayer::new(4096))
    .layer(TraceLayer::new_for_http())
    .with_state(state);

let listener = tokio::net::TcpListener::bind(":::8080").await.unwrap();
axum::serve(listener, app.into_make_service_with_connect_info::<SocketAddr>()).await.unwrap();

Isso não está funcionando. Ao ir para a página inicial, os arquivos estáticos não são enviados e 500 Internal Errorsão enviados.

Registros de rastreamento:

2025-01-19T04:32:37.437061Z DEBUG request{method=GET uri=/ version=HTTP/1.1}: tower_http::trace::on_request: started processing request
2025-01-19T04:32:37.437244Z DEBUG request{method=GET uri=/ version=HTTP/1.1}: tower_http::trace::on_response: finished processing request latency=0 ms status=200
2025-01-19T04:32:37.478539Z DEBUG request{method=GET uri=/style.css?v=1737261157 version=HTTP/1.1}: tower_http::trace::on_request: started processing request
2025-01-19T04:32:37.480165Z DEBUG request{method=GET uri=/style.css?v=1737261157 version=HTTP/1.1}: tower_http::trace::on_response: finished processing request latency=1 ms status=500
2025-01-19T04:32:37.480295Z ERROR request{method=GET uri=/style.css?v=1737261157 version=HTTP/1.1}: tower_http::trace::on_failure: response failed classification=Status code: 500 Internal Server Error latency=1 ms
2025-01-19T04:32:37.482660Z DEBUG request{method=GET uri=/script.js?v=1737261157 version=HTTP/1.1}: tower_http::trace::on_request: started processing request
2025-01-19T04:32:37.487678Z DEBUG request{method=GET uri=/script.js?v=1737261157 version=HTTP/1.1}: tower_http::trace::on_response: finished processing request latency=5 ms status=500
2025-01-19T04:32:37.487877Z ERROR request{method=GET uri=/script.js?v=1737261157 version=HTTP/1.1}: tower_http::trace::on_failure: response failed classification=Status code: 500 Internal Server Error latency=5 ms

Se eu comentar o segundo fallback .fallback(get(home_get)), ele começa a funcionar.

Como ter ambos os fallbacks?

rust
  • 1 respostas
  • 54 Views
Martin Hope
sudoExclamationExclamation
Asked: 2025-01-01 05:16:12 +0800 CST

Existe uma maneira de evitar que o ORDER BY do ROW_NUMBER tenha que repetir a mesma coisa?

  • 5

Atualmente tenho este SQL:

select ROW_NUMBER() OVER (order by priority DESC NULLS LAST,
                                   created_at DESC) as index
     , id
     , title
     , ago(created_at)
     , priority
     , user_id 
from post 
order by priority DESC NULLS LAST
       , created_at DESC;

Como você pode ver, eu preciso ter ROW_NUMBER()e isso precisa do

(order by priority desc nulls last, created_at desc) as index, 
id, title, ago(created_at)

Isso está me fazendo repetir a mesma coisa por muito tempo

order by priority desc nulls last, created_at desc

duas vezes.

Se eu precisar ter ainda mais colunas na ordem, ela ficará ainda mais longa.

Existe uma maneira de evitar essa repetição? Tentei usar um alias depois do ORDER BYmas isso não parece ser suportado.

sql
  • 4 respostas
  • 97 Views
Martin Hope
sudoExclamationExclamation
Asked: 2024-12-30 00:44:17 +0800 CST

Erros de Rust: Não é possível tomar emprestado como mutável mais de uma vez por vez, não é possível tomar emprestado como imutável porque também é tomado emprestado como mutável

  • 5

Tenho o seguinte código de exemplo:

let mut errors: Vec<String> = Vec::new();

let msg1 = "message 1".to_string();
let msg2 = "message 2".to_string();
let msg3 = "message 3".to_string();

let mut push_auth_requirements = || {
    errors.push(msg1.clone());
    errors.push(msg2.clone());
};

let mut push_auth_error = || {
    errors.push(msg3.clone());
    push_auth_requirements();
};

// do some stuff

if errors.is_empty() {
    // do more stuff
    if "bob" == "dsadasd" {
        push_auth_requirements();
    } else {
        push_auth_error();
    }
}

println!("Errors: {:?}",errors);

Isso gera dois erros:

error[E0499]: cannot borrow `errors` as mutable more than once at a time
  --> src/main.rs:89:31
   |
84 |     let mut push_auth_requirements = || {
   |                                      -- first mutable borrow occurs here
85 |         errors.push(msg1.clone());
   |         ------ first borrow occurs due to use of `errors` in closure
...
89 |     let mut push_auth_error = || {
   |                               ^^ second mutable borrow occurs here
90 |         errors.push(msg3.clone());
   |         ------ second borrow occurs due to use of `errors` in closure
91 |         push_auth_requirements();
   |         ---------------------- first borrow later captured here by closure

error[E0502]: cannot borrow `errors` as immutable because it is also borrowed as mutable
  --> src/main.rs:96:8
   |
84 |     let mut push_auth_requirements = || {
   |                                      -- mutable borrow occurs here
85 |         errors.push(msg1.clone());
   |         ------ first borrow occurs due to use of `errors` in closure
...
96 |     if errors.is_empty() {
   |        ^^^^^^ immutable borrow occurs here
...
99 |             push_auth_requirements();
   |             ---------------------- mutable borrow later used here

Como posso resolver isso? Preciso de ambos os closures para poder modificar o errorsvec.

rust
  • 1 respostas
  • 35 Views
Martin Hope
sudoExclamationExclamation
Asked: 2024-12-20 01:34:35 +0800 CST

Posso remover o prefixo do hash da senha no Argon2 ao armazenar no banco de dados?

  • 5

Estou usando esta biblioteca Argon2 em Rust para hash de senha:

https://docs.rs/argon2/latest/argon2/

let salt = SaltString::generate(&mut OsRng);
let argon2 = Argon2::default();
let password_bytes = form.password.as_bytes();
let password_hash = argon2.hash_password(&password_bytes, &salt).unwrap().to_string();

println!("password_hash: {}",password_hash);

let parsed_hash = PasswordHash::new(&password_hash).unwrap();
if Argon2::default().verify_password(&password_bytes, &parsed_hash).is_ok() {
    println!("Valid!");
}

O password_hashgerado se parece com isso:

$argon2id$v=19$m=19456,t=2,p=1$UWyFFxDMETxLo1q7BFjIEQ$i3MwCW0H7fZjFG7hMwKAPZgWs4hjo/foEUCwLsqp9uY

Parece sempre ter o prefixo$argon2id$v=19$m=19456,t=2,p=1$

  1. Posso remover esse prefixo antes de armazená-lo no banco de dados para economizar espaço? E então apenas codificá-lo para adicioná-lo antes de verificar?

  2. O que essas coisas significam?

  3. Será sempre a mesma coisa?

rust
  • 1 respostas
  • 37 Views
Martin Hope
sudoExclamationExclamation
Asked: 2024-10-08 03:33:09 +0800 CST

Por que CustomStringConvertible não funciona para Dados?

  • 5

Eu tenho o seguinte:

extension Data : CustomStringConvertible {
    var description : String {
        return base64EncodedString()
    }
}

Isto mostra um aviso:

Conformance of 'Data' to protocol 'CustomStringConvertible' was already stated in the type's module 'Foundation'

E por causa desse aviso, Datanão é impresso usando o description.

Isso não é suportado?

  • 2 respostas
  • 30 Views
Martin Hope
sudoExclamationExclamation
Asked: 2024-10-07 00:15:53 +0800 CST

Como fazer com que os segmentos do SwiftUI Picker sejam tão largos quanto seu conteúdo e não tão largos quanto o segmento mais largo?

  • 5

No SwiftUI, tenho o seguinte:

func segments() -> [String] {
    var toReturn = Calendar.current.veryShortWeekdaySymbols
    toReturn.append("T")
    return toReturn
}

Picker("Day of week?", selection: $selectedDay) {
    ForEach(segments(), id: \.self) {
        Text($0)
            .scaledToFit()
    }
}
.pickerStyle(.segmented)
.fixedSize()

Isso é mostrado como:

insira a descrição da imagem aqui

Entretanto, se eu alterar o toReturn.append("T")para uma string mais longa, como toReturn.append("Tasks"), os segmentos se tornarão tão largos quanto o segmento mais largo e não se ajustarão ao seu conteúdo:

insira a descrição da imagem aqui

Como fazer com que os segmentos do SwiftUI Picker sejam tão largos quanto seu conteúdo e não tão largos quanto o segmento mais largo?

  • 1 respostas
  • 33 Views
Martin Hope
sudoExclamationExclamation
Asked: 2024-09-17 02:08:26 +0800 CST

Como adicionar marcação personalizada ao MarkupVisitor no Swift-Markdown?

  • 6

Estou usando a biblioteca swift-markdown no meu aplicativo.

Estou tentando descobrir como adicionar meu próprio costume Markupao MarkupVisitor?

Consegui usar uma solução alternativa visitInlineAttributesque se aplica a ^[]().

Existe uma maneira de adicionar minha própria marcação personalizada?

Por exemplo, se eu quisesse minha própria marcação inline onde o texto dentro @[text]teria cor cinza? Semelhante a como **bold** deixa as coisas em negrito.

Alguém fez essa pergunta na biblioteca, mas não entendi como implementar a única resposta lá.

https://github.com/swiftlang/swift-markdown/issues/122

Aqui está um exemplo que eu tenho:

import UIKit
import Markdown
import SnapKit

class ViewController: UIViewController, UITextViewDelegate {
    
    let label = UITextView()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        label.isEditable = false
        label.delegate = self
        label.linkTextAttributes = [:]
        view.addSubview(label)
        label.snp.makeConstraints { make in
            make.edges.equalTo(view.safeAreaLayoutGuide).inset(10)
        }
        
        var md = MarkdownParser()
        let attr = md.attributedString(from: "Hello World! Here's some text which is **bold** and here's some which is *italics*. Here's some ^[[metadata containing link](https://old.reddit.com/r/SaaS/comments/1fgv248/fuck_founder_mode_work_in_fuck_off_mode/)]() which is gray and not underlined. And here's some normal [link](https://hckrnews.com) which is underlined and red. You are welcome!")
        print("ATTR:\n\n\(attr)")
        label.attributedText = attr
        
    }
    
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        print("shouldInteractWith: \(URL)")
        return true
    }

}

struct MarkdownParser: MarkupVisitor {

    typealias Result = NSMutableAttributedString
    
    mutating func attributedString(from : String) -> NSMutableAttributedString {
        let document = Document(parsing: from)
        print(document.debugDescription())
        return NSMutableAttributedString(attributedString: visit(document))
    }
    
    mutating func visit(_ markup: Markup) -> NSAttributedString {
        return markup.accept(&self)
    }
    
    mutating func defaultVisit(_ markup: any Markdown.Markup) -> NSMutableAttributedString {
        let result = NSMutableAttributedString()

        for child in markup.children {
            result.append(visit(child))
        }

        return result
    }
    
    mutating func visitText(_ text: Text) -> NSMutableAttributedString {
        return NSMutableAttributedString(string: text.plainText, attributes: [.font:UIFont.systemFont(ofSize: 18, weight: .regular),.foregroundColor:UIColor.label])
    }
    
    mutating func visitEmphasis(_ emphasis: Emphasis) -> NSMutableAttributedString {
        return doVisit(emphasis)
    }
    
    mutating func visitStrong(_ strong: Strong) -> NSMutableAttributedString {
        return doVisit(strong)
    }
    
    mutating func visitInlineAttributes(_ attributes: InlineAttributes) -> NSMutableAttributedString {
        return doVisit(attributes)
    }
    
    mutating func visitLink(_ link: Link) -> NSMutableAttributedString {
        return doVisit(link)
    }
    
    mutating func doVisit(_ markup: any Markup) -> NSMutableAttributedString {
        let result = NSMutableAttributedString()
        
        for child in markup.children {
            result.append(visit(child))
        }
        
        switch markup {
        case is Strong:
            fallthrough
        case is Emphasis:
            result.enumerateAttribute(.font, in: result.fullRange, options: []) { value, range, stop in
                if let newFont = (value as? UIFont)?.addTrait(trait: markup is Strong ? .traitBold : .traitItalic) {
                    result.addAttribute(.font, value: newFont, range: range)
                }
            }
        case is InlineAttributes:
            result.removeAttributes([.underlineStyle,.underlineColor])
            result.addAttribute(.foregroundColor, value: UIColor.tertiaryLabel)
        case is Link:
            if let destination = (markup as? Link)?.destination, let url = URL(string: destination) {
                let color = UIColor.systemRed
                result.addAttributes([.underlineStyle : NSUnderlineStyle.single.rawValue, .underlineColor : color,.foregroundColor : color, .link : url])
            }
        default:
            break
        }
        
        return result
    }
}

extension NSAttributedString {
    var fullRange : NSRange {
        NSRange(location: 0, length: length)
    }
}

extension NSMutableAttributedString {
    func addAttribute(_ name: NSAttributedString.Key, value: Any) {
        addAttribute(name, value: value, range: fullRange)
    }

    func addAttributes(_ attrs: [NSAttributedString.Key : Any]) {
        addAttributes(attrs, range: fullRange)
    }
    
    func removeAttribute(_ name: NSAttributedString.Key) {
        removeAttribute(name, range: fullRange)
    }
    
    func removeAttributes(_ names: [NSAttributedString.Key]) {
        for attribute in names {
            removeAttribute(attribute)
        }
    }
}

extension UIFont {
    func addTrait(trait : UIFontDescriptor.SymbolicTraits) -> UIFont {
        var traits = fontDescriptor.symbolicTraits
        if traits.contains(trait) {
            return self
        } else {
            traits.insert([trait])
            return UIFont(descriptor: fontDescriptor.withSymbolicTraits(traits)!, size: pointSize)
        }
    }
}

Isso mostra o seguinte:

insira a descrição da imagem aqui

  • 1 respostas
  • 29 Views
Martin Hope
sudoExclamationExclamation
Asked: 2024-09-12 01:31:49 +0800 CST

É legal alterar a posição do quadro do contentView em uma UITableViewCell ou devo usar outra visualização de contêiner?

  • 5

Estou criando minhas próprias células deslizantes personalizadas, onde o usuário pode deslizar uma célula para mostrar opções. Atualmente, todas as minhas subvisualizações são adicionadas ao da contentViewcélula. E adicionei minhas opções ao backgroundViewda célula.

insira a descrição da imagem aqui

  1. Posso adicionar meu conteúdo personalizado ao backgroundView?

  2. É aceitável que eu altere manualmente a posição do quadro contentViewao deslizar na célula? E então eu o redefinirei de volta para sua posição original após a conclusão. Ou devo usar outra visualização como um contêiner?

  • 1 respostas
  • 26 Views
Martin Hope
sudoExclamationExclamation
Asked: 2024-02-24 16:44:47 +0800 CST

Em Javascript, como posso querySelector para obter o innerHTML excluindo um dos divs irmãos internos

  • 5

Eu tenho o seguinte html:

<body>
    <span class="comment">
        EXAMPLES:
        <p><i>Example 1</i> - <a href="https://example.com/1">https://example.com/1</a> - Jan 2020 (2 comments)</p>
        <p><i>Example 2</i> - <a href="https://example.com/2">https://example.com/2</a> - Jun 2022 (13 comments)</p>
        <div class="reply"><p><u><a href="reply?id=12323" rel="nofollow">reply</a></u></p></div>
        <p><i>Example 3</i> - <a href="https://example.com/3">https://example.com/3</a> - Apr 2023 (33 comments)</p>
    </span>
</body>

Estou tentando obter o innerHTMLda .commentclasse, exceto o .replydiv.

Observe que não é garantido que a .replyaula seja a última.

Basicamente, quero obter apenas:

EXAMPLES:
<p><i>Example 1</i> - <a href="https://example.com/1">https://example.com/1</a> - Jan 2020 (2 comments)</p>
<p><i>Example 2</i> - <a href="https://example.com/2">https://example.com/2</a> - Jun 2022 (13 comments)</p>
<p><i>Example 3</i> - <a href="https://example.com/3">https://example.com/3</a> - Apr 2023 (33 comments)</p>

Não consigo descobrir como posso excluir um dos filhos irmãos.

Eu sei que posso pegar as crianças, exceto a .replyturma, usando o seguinte:

document.querySelectorAll(`.comment > :not(.reply)`)

Mas este não é o innerHTML. É um NodeList:

insira a descrição da imagem aqui

Existe uma maneira de obter um novo elemento combinado NodeListque eu possa invocar innerHTML?

Encontrei uma pequena pergunta semelhante aqui:

Javascript .innerHTML, mas excluindo div interno

mas essa questão é sobre como extrair uma string específica e as soluções parecem feias. Existe uma maneira melhor?

javascript
  • 1 respostas
  • 27 Views
Martin Hope
sudoExclamationExclamation
Asked: 2024-02-04 06:26:19 +0800 CST

Por que esse HTML com IDs duplicados é permitido quando as regras dizem "Você não pode ter mais de um elemento com o mesmo ID em um documento HTML."? [duplicado]

  • 0
Esta pergunta já tem respostas aqui :
Por que os navegadores não são rígidos em relação ao HTML? [fechado] (3 respostas)
Fechado há 2 horas .

Estou visualizando o HTML do Hacker News. Por exemplo esta postagem:

https://news.ycombinator.com/item?id=39241448

No HTML, a classe trwith athingtem o mesmo elemento iddo botão expandir/recolher a:

insira a descrição da imagem aqui

As regras estabelecem que:

https://www.w3schools.com/html/html_id.asp

Você não pode ter mais de um elemento com o mesmo id em um documento HTML.

Estou entendendo mal as regras ou isso não é HTML válido?

html
  • 1 respostas
  • 41 Views
Martin Hope
sudoExclamationExclamation
Asked: 2024-01-30 10:10:00 +0800 CST

Rust "o valor emprestado não dura o suficiente" desaparece quando eu removo um trecho de código

  • 5

Estou usando a solução nesta questão:

https://stackoverflow.com/a/56925633/1634905

Meu código se parece com:

fn get_room_header<'a>(socket: &'a SocketRef) -> Option<&'a str> {
    socket.req_parts().headers.get("room")?.to_str().ok()
}

async fn on_connect(socket: SocketRef) {

    println!("on_connect");

    let Some(room) = get_room_header(&socket) else {
        println!("No room sent: {:?}",socket.req_parts());
        _ = socket.disconnect();
        return;
    };

    // println!("Room: {:?}",room);

    let _ = socket.leave_all();
    let _ = socket.join(room);//if I comment out this line, it no longer throws error

}

Isso não compila e dá um erro:

`socket` does not live long enough
borrowed value does not live long enough
main.rs(61, 1): `socket` dropped here while still borrowed
main.rs(46, 21): binding `socket` declared here
main.rs(50, 22): argument requires that `socket` is borrowed for `'static`

Captura de tela do erro:

insira a descrição da imagem aqui

Se eu comentar a linha let _ = socket.join(room);, o erro não será mais gerado. Por que isso?

A join()função é da rust_socketiocaixa:

https://github.com/1c3t3a/rust-socketio/tree/main

Se parece com isso:

pub fn join(&self, rooms: impl RoomParam) -> Result<(), A::Error> {
    self.ns.adapter.add_all(self.id, rooms)
}

pub trait RoomParam: 'static {
    /// The type of the iterator returned by `into_room_iter`.
    type IntoIter: Iterator<Item = Room>;

    /// Convert `self` into an iterator of rooms.
    fn into_room_iter(self) -> Self::IntoIter;
}
rust
  • 1 respostas
  • 32 Views
Martin Hope
sudoExclamationExclamation
Asked: 2024-01-30 10:04:34 +0800 CST

Como ter vários `let Some()` em uma única linha onde o segundo `let` depende do primeiro?

  • 6

É possível algo assim onde ambos let Some(...)estão na mesma linha e o segundo letdepende do primeiro let?

let Some(h) = socket.req_parts().headers.get("room"), let Some(room) = h.to_str() else {
    return;
};

Esta solução:

Como escrever múltiplas condições na instrução if let?

propõe o uso de tuplas, mas não tenho certeza de como fazer isso quando o segundo letdepende do primeiro.

rust
  • 1 respostas
  • 41 Views
Martin Hope
sudoExclamationExclamation
Asked: 2024-01-30 07:04:01 +0800 CST

Android Studio: como manter o logcat fixado ao executar o aplicativo?

  • 5

Fazia muito tempo que não usava o Android Studio. Recentemente comecei a usá-lo e estou enfrentando um problema de UX.

Como você pode ver abaixo, quero que o Logcat sempre fique na parte inferior, assim:

insira a descrição da imagem aqui

No entanto, sempre que executo o aplicativo, o Android Studio o substitui pela Runjanela:

insira a descrição da imagem aqui

Ao tentar descobrir como manter o Logcat sempre presente, usei o "Dividir à direita" e agora tenho esse Logcat de 2 painéis que não é o que eu quero:

insira a descrição da imagem aqui

Eu tenho 2 perguntas:

  1. Como posso manter o logcat sempre fixado mesmo quando executo o aplicativo? Não quero clicar constantemente em "Logcat" para abri-lo.

  2. Como posso me livrar dessa janela de painel dividido?

  • 1 respostas
  • 21 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