小编tha*_*ker的帖子

how to convert a date string into a NSDate type swift

我正在尝试采用dd/mm/yyyy格式的字符串并将其转换为 NSDate,以便我可以存储生日。日、月、年经过验证是真实日期(也不是将来的日期),因此我知道它们是正确的。它们由用户作为文本字段输入,我想我可以制作dateString我想要的任何有用的格式。

let day = dayTextField.text
let month = monthTextField.text
let year = yearTextField.text
let dateString = "\(day)/\(month)/\(year)"
let dateFormatter = DateFormatter()

dateFormatter.dateFormat = "dd/MM/yyyy"

let birthdate: NSDate = dateFormatter.date(from: dateString) as NSDate
Run Code Online (Sandbox Code Playgroud)

我的问题是当我尝试将日期字符串转换为 NSDate 时,最后一行出现以下错误:

'Date?' is not convertible to 'NSDate'; did you mean to use 'as!' to force downcast?
Run Code Online (Sandbox Code Playgroud)

我可以在“(from:) dateString”之后强制强制转换,但我认为这不是正确的做法。

您能提供的任何帮助和见解将不胜感激!谢谢

nsdate ios swift

5
推荐指数
1
解决办法
4685
查看次数

Python计时器启动和重置

我正在尝试让 Timer 功能在 Python(当前为 Python 2.7)中工作。

这是我到目前为止所拥有的。我正在努力解决线程问题并重置计时器。

from threading import Timer

def api_call():
    print("Call that there api")

t = Timer(10.0,api_call)


def my_callback(channel):

    if something_true:
        print('reset timer and start again')
        t.cancel()
        t.start()
        print("\n timer started")
    elif something_else_true:
        t.cancel()
        print("timer canceled")
    else:
       t.cancel()
       print('cancel timer for sure')

try:
    if outside_input_that_can_happen_a_lot:
        my_callback()

finally:
    #cleanup objects
Run Code Online (Sandbox Code Playgroud)

基本上,my_callback()可以非常快速地多次调用,并且可以命中“if”、“elif”或“else”语句的任何部分。

我遇到的问题是,当something_true变量为真时,它将启动一个计时器。第一次效果很好。之后每次调用它时,我都会收到一个线程错误,告诉我只能将一个线程用于计时器。

基本上,我希望能够在第一个“if”时重置我的计时器,并在“elif”或“else”被点击时取消。

python multithreading timer python-2.7

5
推荐指数
1
解决办法
3253
查看次数

使用 Serilog .NET Core 记录不输出

PS:我的问题出在我身上,而不是代码。代码没问题。我需要更改.WriteTo.Console().WriteTo.Debug()(并获得正确的 nuget 包)。

我正在尝试使用 .NET Core Web Api 中的 Serilog 从我的日志中输出信息。但是,并没有输出相关信息(即我要记录的信息)。

我已经安装了以下 Serilog nuget 软件包:

  • 串行日志
  • Serilog.AspNetCore
  • Serilog.Sinks.Console
  • Serilog.Sinks.File
  • Serilog.Sinks.RollingFile

我已经考虑在 appSettings.json 中设置我的配置设置,但如果可能的话,我更愿意这样做。

这是我的Program.cs文件。

public class Program
{
    public static void Main(string[] args)
    {

        // Create the logger
        Log.Logger = new LoggerConfiguration()
            .Enrich.FromLogContext()
            .MinimumLevel.Debug()
            .WriteTo.Console()
            .CreateLogger();

        Log.Information("ah there you are");
        Log.Debug("super");
        Log.Error("super1");
        Log.Warning("super2");

        try
        {
            Log.Information("Starting web host");

            // Program.Main logic
            Directory.SetCurrentDirectory(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
            CreateWebHostBuilder(args).Build().Run();
        }
        catch (Exception ex)
        {
            Log.Fatal(ex, "Host terminated unexpectedly");
            Console.WriteLine(ex.Message);
        } …
Run Code Online (Sandbox Code Playgroud)

c# serilog asp.net-core asp.net-core-webapi

4
推荐指数
1
解决办法
6029
查看次数

筛选 Blazor 输入字段

我有 Blazor 的基本输入

<div class="file-explorer-input">
    <div class="search"><i class='fas fa-search search-icon' /><input type="text" name="subPath" placeholder="Select or search for your directory..." @bind="Search" @oninput="OnType" /></div>
</div>
Run Code Online (Sandbox Code Playgroud)

当我输入我认为无效的字符(例如“/”或“<”)时,我想立即从搜索中过滤掉这些字符。

我试着这样做

using System.Text.RegularExpressions;

private string Search;

private void OnType(ChangeEventArgs args)
{
    var pattern = @"[<>:/\\""|?* ]";
    Search = Regex.Replace(args.Value.ToString(), pattern, "");
}
Run Code Online (Sandbox Code Playgroud)

现在我的过滤效果很好。该Search立即滤出我想要的东西,被设置为该值。问题在于状态管理。

如果我在有效字符(即“s/”)之后输入无效字符,它不会将其识别为对Search.

原因是,因为在输入之前,Search = "s"然后args = "s/"但是由于结果被过滤,Search仍然等于"s"并且因此无法识别更改。但是,输入仍然说s/

我什至尝试过

private void OnType(ChangeEventArgs args)
    {
        var pattern = @"[<>:/\\""|?* ]";
        Search = …
Run Code Online (Sandbox Code Playgroud)

regex state filter state-management blazor

3
推荐指数
1
解决办法
1615
查看次数

使用 Tailwind 在悬停时填充 SVG 颜色

我一直试图让我的 svg 在悬停时用黑色填充,但似乎无法做到。

我希望它有这样的黑色轮廓 我的人 svg.
然后像这样填充填入svg.

这是我希望在悬停时填充它的代码。但是,它并不完全有效。如果我hover:脱掉hover:fill-current它,它就会一直填充黑色。

<svg class="h-6 w-6 text-black hover:fill-current" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
    stroke="currentColor" aria-hidden="true">
    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
        d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
</svg>
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

html css svg tailwind-css

3
推荐指数
2
解决办法
2179
查看次数

每 2 秒获取一次调用,但不希望请求堆积起来

我正在尝试进行 API 调用,并且希望它每 2 秒重复一次。但是我担心如果系统在 2 秒内没有收到请求,它会建立请求并继续尝试发送它们。我怎样才能防止这种情况?

这是我正在尝试的操作fetch

const getMachineAction = async () => {
    try {
        const response = await fetch( 'https://localhost:55620/api/machine/');
        if (response.status === 200) {
            console.log("Machine successfully found.");
            const myJson = await response.json(); //extract JSON from the http response
            console.log(myJson);               
        } else {
            console.log("not a 200");
        }
    } catch (err) {
        // catches errors both in fetch and response.json
        console.log(err);
    }
};
Run Code Online (Sandbox Code Playgroud)

然后我用setInterval.

function ping() {
    setInterval(
        getMachineAction(),
        2000
    );        
}
Run Code Online (Sandbox Code Playgroud)

我曾想过在 setInterval …

javascript asynchronous fetch promise

2
推荐指数
2
解决办法
6588
查看次数

返回响应头 OnAuthenticationFailed

如果用户发送的令牌已过期,我将尝试返回更改的标头,以便我可以在它过期时重新发送我的刷新令牌。

我将 .NET Core 2.2 与“In-Process”托管一起使用,这很重要。

这是我ConfigureServices从我的Startup.cs.

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = "bearer";
    options.DefaultChallengeScheme = "bearer";
}).AddJwtBearer("bearer", options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateAudience = false,
        ValidateIssuer = false,
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(Configuration["serverSigningPassword"])),
        ValidateLifetime = true,
        ClockSkew = System.TimeSpan.Zero //the default for this setting is 5 minutes
    };
    options.Events = new Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerEvents
    {
        OnAuthenticationFailed = context =>
        {
            if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
            {
                context.Response.Headers.Add("Token-Expired", "true");
            }
            return System.Threading.Tasks.Task.CompletedTask;
        }
    };
}); …
Run Code Online (Sandbox Code Playgroud)

javascript c# api http-headers asp.net-core

2
推荐指数
1
解决办法
2031
查看次数

Flutter Flexible 不在列内换行文本

我正在尝试制作一个可能有一些长文本的小部件,我想用几行换行。

我正在尝试使用“灵活”小部件来包装我的文本,但它仍然溢出,我不知道出了什么问题。

这是正在发生的事情: 在此处输入图片说明

这是我的与文本相关的列的代码:

Container(
  child: Column(
    crossAxisAlignment: CrossAxisAlignment.start,
    children: [
      Text(
        'My Title text',
        style: TextStyle(
            fontWeight: FontWeight.bold,
            fontSize: 18.0,
            color: Colors.black),
      ),
      Text(
        'This is lower text',
        style: TextStyle(
            fontWeight: FontWeight.w200,
            fontSize: 16.0,
            color: Colors.black),
      ),
      Flexible(
        child: Text(
          'Here is some long text that I am expecting will go off of the screen.',
          style: TextStyle(
              fontWeight: FontWeight.normal,
              fontSize: 16.0,
              color: Colors.black),
        ),
      )
    ],
  ),
),

Run Code Online (Sandbox Code Playgroud)

并且这里是相关的,这是整个小部件

Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar( …
Run Code Online (Sandbox Code Playgroud)

word-wrap flutter

1
推荐指数
1
解决办法
3283
查看次数

按钮/标签等的 iOS 命名约定

我对应用程序开发比较陌生,我很好奇 iOS 应用程序开发是否有任何命名约定。我找到了这个指南 https://developer.apple.com/design/human-interface-guidelines/ios/controls/buttons/但实际上没有任何命名约定。如果没有“普遍接受”的,你有什么推荐的吗?

我真正挣扎的是按钮名称(IBOutlet)与动作(IBAction)的不同命名按钮。(例如,对于注册按钮:signUpButton 与 signUpButtonTapped)。

对于标签或文本字段等其他内容,我只需输入名称,然后在其后键入(例如 usernameTextField 或 infoLabel)。

任何建议表示赞赏。谢谢!

naming-conventions ios

0
推荐指数
1
解决办法
2050
查看次数