AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / user-1634905

sudoExclamationExclamation's questions

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

如何让iOS移动渐变边框永远向一个方向移动而不重置到原始位置?

  • 5

我的以下代码显示了该问题:

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")
    }
}

这将产生以下动画:

在此处输入图片描述

请注意,我将其设置autoreverses为 false,因为我不想让它在重复到 时反转回来infinity。然而,这样做的结果是,在 之后duration,它会从原来的 重新开始location。这会导致移动渐变边框突然跳动。

我怎样才能让它一直朝一个方向移动而不重置?

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

苹果的 iOS 文档中关于先前注册的具有相同重用标识符的类被新的 cellClass 替换的说法是否不正确?

  • 0

苹果的文档指出:

如果您之前注册了具有相同重用标识符的类或 nib 文件,则您在参数中指定的类将替换旧条目。如果您想从指定的重用标识符中取消注册该类,cellClass请指定nil。cellClass

据我所知,这似乎不正确。

下面简单的示例代码演示了这个问题。基本上,我有一个可以改变填充值的滑块。当填充值发生变化时,它应该用重用标识符重新注册(替换旧条目)该类,并重新加载表格以显示新的填充值:

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")
    }
}

然而,事实似乎并非如此。它继续使用之前的填充,并且旧条目不会被替换。

我是否误解了 Apple 文档的内容?

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

SwiftUI 的 navigationBarItems 前导和尾随按钮未显示在 FamilyActivityPicker 中

  • 5

我在 SwiftUI 中有以下内容View需要显示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)")
        }
    }
}

但是,navigationBarItems 的前导按钮和尾随按钮均未显示:

在此处输入图片描述

我做错了什么?我们应该如何取消或完成 FamilyActivityPicker 视图?

编辑:

当我使用NavigationStackwith时.toolbar,我最终得到了 2 个导航栏,如下面的屏幕截图所示,看起来非常丑陋并且浪费空间:

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()
                    }
                }
            }
        }
    }
}

结果:

在此处输入图片描述

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

为什么 iOS CILightenBlendMode 会改变灯光颜色?

  • 5

我有以下源图像:

在此处输入图片描述

我正在尝试将其转换为:

在此处输入图片描述

我已经建立了这个代码:

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)
        )
    }
}

但是,黄色背景在输出中看起来并不准确:

在此处输入图片描述

CILightenBlendMode我以为滤镜只会将黑色变成紫色,但实际上滤镜似乎也改变了黄色。我做错了什么?

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

iOS 自动布局 - 无法使高度小于或等于

  • 5

我在我的 iOS 应用程序中使用SnapKit进行自动布局。

我需要在屏幕的最顶部显示一个图像视图。它将具有动态高度和宽度的图像。我需要它的顶部边缘与视图的顶部对齐。我需要它水平居中。我需要它与屏幕的左右边距大于或等于 10。我需要它的高度根据内容动态变化,最大高度等于 300。我需要它保持其纵横比并根据需要使用自动布局自动减小其宽度或高度。

我认为下面的代码应该可以完成这个工作:

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)
}

这对于横向图像(宽度大于高度)似乎工作正常,但它在纵向图像中不起作用:




适用于风景图像:

在此处输入图片描述







肖像图像失败。请注意高度不再是lessThanOrEqualTo(300):

在此处输入图片描述

这是因为 Xcode 打印了一条警告,称它无法满足约束,因此必须打破高度约束:

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>

我原本期望它能减小宽度并保持纵横比以满足条件。但它没有这样做。

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

SeleniumBase CDP 模式 execute_script 并使用 javascript 进行评估会出现错误“SyntaxError: 非法返回语句”

  • 6

我在 CDP 模式下使用SeleniumBase 。

我很难弄清楚这是 Python 问题还是 SeleniumBase 问题。

下面的简单示例显示了我的问题:

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!")

这会引发错误:

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

请注意,我已经尝试了两者sb.execute_script(script),sb.cdp.evaluate(script)并且都出现了同样的问题。

我如何执行此类脚本?

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

如何在 CDP 模式下在 Selenium Base 中设置窗口大小?

  • 6

我在 CDP 模式下使用SeleniumBase 。

我想知道如何在网站加载后在 CDP 模式下设置窗口大小?

如果我使用非 CDP 功能sb.set_window_size(x,y),那么它会被检测为在https://bot-detector.rebrowser.netruntimeEnableLeak上打开 devtools的机器人:

在此处输入图片描述

我尝试过sb.cdp.set_window_size(x,y),但是该功能似乎不存在,因为它崩溃了:

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

编辑:我能够找到一种解决方法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))

有没有更好的方法?

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

多次回退导致失败并出现 500 内部错误

  • 5

我正在使用 Rusts 的Axum网络框架。

我需要有多个后备方案。

第一个后备方案是用于传送静态文件,例如/script.js位于/style.css我的static文件夹中的文件。

第二个回退应该是如果任何路由不匹配,那么我需要提供主页(/匹配时也会提供主页)。例如,对于渲染客户端渲染页面的虚假路由。

代码:

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();

这不起作用。转到主页时,静态文件不会被发送,但500 Internal Error会被发送。

跟踪日志:

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

如果我注释掉第二个 fallback .fallback(get(home_get)),那么它就开始工作了。

如何实现两种后备方案?

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

有没有办法可以防止 ROW_NUMBER 的 ORDER BY 重复同样的事情?

  • 5

我目前有这个 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;

正如你所看到的,我需要ROW_NUMBER()有

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

这让我重复同样长

order by priority desc nulls last, created_at desc

两次。

如果我需要在排序时包含更多列,那么它将变得更长。

有没有办法防止这种重复?我尝试在后面使用别名,ORDER BY但似乎不受支持。

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

Rust 错误:不能一次多次借用可变类型,不能借用不可变类型,因为它也是借用可变类型

  • 5

我有以下示例代码:

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);

这会产生两个错误:

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

我该如何解决这个问题?我需要两个闭包才能修改errorsvec。

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

在数据库存储时我可以删除 Argon2 中密码哈希的前缀吗?

  • 5

我在 Rust 中使用这个 Argon2 库进行密码哈希处理:

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!");
}

生成的结果password_hash如下:

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

它似乎总是带有前缀$argon2id$v=19$m=19456,t=2,p=1$

  1. 我可以在将其存储到数据库之前删除该前缀以节省空间吗?然后在验证之前对其进行硬编码以添加它?

  2. 这些东西意味着什么?

  3. 它会一直都一样吗?

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

为什么 CustomStringConvertible 对数据不起作用?

  • 5

我有以下内容:

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

这显示一个警告:

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

并且由于此警告,Data无法使用 打印description。

难道这个不支持吗?

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

如何使 SwiftUI Picker 的段实际上与其内容一样宽而不是与最宽的段一样宽?

  • 5

在 SwiftUI 中,我有以下内容:

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()

显示为:

在此处输入图片描述

但是,如果我将改为toReturn.append("T")更长的字符串,例如toReturn.append("Tasks"),那么段的宽度就会变得与最宽的段一样宽,并且实际上并不适合其内容:

在此处输入图片描述

如何使 SwiftUI Picker 的段实际上与其内容一样宽而不是与最宽的段一样宽?

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

如何向 Swift-Markdown 中的 MarkupVisitor 添加自定义标记?

  • 6

我在我的应用程序中使用swift-markdown库。

我正在尝试弄清楚如何将我自己的自定义添加Markup到MarkupVisitor?

我已经能够使用visitInlineAttributes适用于的解决方法^[]()。

有没有办法添加我自己的自定义标记?

例如,如果我想要自己的内联标记,其中的文本@[text]会是灰色?类似于 **bold** 使内容变粗的方式。

有人在图书馆问了这个问题,但我不明白如何在那里实现唯一的答案。

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

下面是我的一个例子:

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)
        }
    }
}

这表明:

在此处输入图片描述

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

更改 UITableViewCell 中 contentView 框架的位置是否合法,或者我应该使用其他容器视图?

  • 5

我正在制作自己的自定义可滑动单元格,用户可以滑动单元格来显示选项。目前,我的所有子视图都已添加到单元格的contentView。并且我已将我的选项添加到backgroundView单元格的。

在此处输入图片描述

  1. 我可以将我的自定义内容添加到其中backgroundView吗?

  2. contentView我可以在滑动单元格时手动更改框架的位置吗?然后在完成后将其重置回原始位置。还是我应该使用另一个视图作为容器?

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

在 Javascript 中,我如何 querySelector 来获取不包括内部兄弟 div 之一的innerHTML

  • 5

我有以下 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>

我正在尝试获取除 div之外innerHTML的班级。.comment.reply

请注意,该.reply课程并不保证是最后一堂课。

基本上,我只想得到:

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>

我不知道如何才能排除其中一个兄弟姐妹。

.reply我知道我可以使用以下方法让除班级之外的孩子们:

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

但这不是innerHTML. 它是NodeList:

在此输入图像描述

有没有办法从中获取一个新的组合元素,NodeList然后我可以调用innerHTML它?

我在这里发现了一个稍微类似的问题:

Javascript .innerHTML 但不包括内部 div

但这个问题是关于提取特定的字符串,解决方案看起来很丑陋。有没有更好的办法?

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

当规则规定“在 HTML 文档中不能有多个具有相同 id 的元素”时,为什么允许这种具有重复 id 的 HTML?[复制]

  • 0
这个问题在这里已经有了答案:
为什么浏览器对 HTML 不严格?[已关闭] (3 个回答)
2 小时前关闭。

我正在查看 Hacker News 的 HTML。例如这篇文章:

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

在 HTML 中,trwith类与展开/折叠按钮元素athing相同:ida

在此输入图像描述

规则规定:

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

在 HTML 文档中不能有多个具有相同 id 的元素。

我是否误解了规则或者这不是有效的 HTML?

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

当我删除一段代码时,Rust“借用的价值活得不够长”就会消失

  • 5

我正在使用这个问题中的解决方案:

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

我的代码如下所示:

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

}

这不会编译并给出错误:

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

错误截图:

在此输入图像描述

如果我注释掉该行let _ = socket.join(room);,那么它就不再抛出错误。这是为什么?

该join()函数来自rust_socketio板条箱:

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

它看起来像这样:

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 个回答
  • 32 Views
Martin Hope
sudoExclamationExclamation
Asked: 2024-01-30 10:04:34 +0800 CST

如何在一行中包含多个“let Some()”,其中第二个“let”依赖于第一个?

  • 6

let Some(...)当两者都在同一行并且第二个let依赖于第一个的情况下,是否可能出现这样的情况let?

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

这个解决方案:

if let 语句中如何编写多个条件?

建议使用元组,但我不确定当第二个let依赖于第一个时该怎么做。

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

Android Studio:运行应用程序时如何保持 logcat 固定?

  • 5

我已经很久没有使用Android Studio了。我最近开始使用它并面临用户体验问题。

如下所示,我希望 Logcat 始终位于底部,如下所示:

在此输入图像描述

但是,每次我运行该应用程序时,Android Studio 都会将其替换为Run窗口:

在此输入图像描述

在试图弄清楚如何保持 Logcat 始终保留时,我使用了“右分割”,现在我有了这个 2 窗格 Logcat,这不是我想要的:

在此输入图像描述

我有两个问题:

  1. 即使我运行应用程序,如何保持 logcat 始终固定?我不想不断地点击“Logcat”来打开它。

  2. 我怎样才能摆脱这个分割窗格窗口?

  • 1 个回答
  • 21 Views

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

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

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve