问:
Invalid foreign key column name error ef Core
im trying to create API with related entities in EF Core. I don't understand why It throwing this error:

```<code>Microsoft.Data.SqlClient.SqlException (0x80131904): Invalid column name 'AuthorId'.
   at Microsoft.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__188_0(Task`1 result)
   at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
   at System.Threading.Tasks.Task.<>c.<.cctor>b__272_0(Object obj)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
--- End of stack trace from previous location ---
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.InitializeReaderAsync(AsyncEnumerator enumerator, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
   at System.Text.Json.Serialization.Converters.IAsyncEnumerableOfTConverter`2.OnWriteResume(Utf8JsonWriter writer, TAsyncEnumerable value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonCollectionConverter`2.OnTryWrite(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.Converters.IAsyncEnumerableOfTConverter`2.OnTryWrite(Utf8JsonWriter writer, TAsyncEnumerable value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.WriteCore(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.WriteCoreAsObject(Utf8JsonWriter writer, Object value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonSerializer.WriteCore[TValue](JsonConverter jsonConverter, Utf8JsonWriter writer, TValue& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonSerializer.WriteStreamAsync[TValue](Stream utf8Json, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken)
   at System.Text.Json.JsonSerializer.WriteStreamAsync[TValue](Stream utf8Json, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken)
   at System.Text.Json.JsonSerializer.WriteStreamAsync[TValue](Stream utf8Json, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|30_0[TFilter,TFilterAsync](ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeResultFilters>g__Awaited|28_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
ClientConnectionId:a2b92e1b-ed00-4050-b7ff-23ed1f0fa3a3
Error Number:207,State:1,Class:16

HEADERS
=======
Accept: */*
Connection: keep-alive
Host: localhost:7079
User-Agent: PostmanRuntime/7.30.0
Accept-Encoding: gzip, deflate, br
Postman-Token: 3d4c8593-da6e-4682-95c5-5aa54dd7b7df

</code>```

Models:

```<code>using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace LibraryAPI.Resources
{
    // Book model
    public class Book
    {

        [Key]
        public int Id { get; set; }
        [Column(TypeName = "nvarchar(100)")]
        public string Title { get; set; }
        [Column(TypeName = "nvarchar(MAX)")]
        public string Description { get; set; }
        [ForeignKey("AuthorId")]
        public Author Author { get; set; }
        [Column(TypeName = "decimal")]
        public float Rating { get; set; }
        [Column(TypeName = "nvarchar(13)")]
        public int ISBN { get; set; }
        [Column(TypeName = "Datetime2")]
        public DateTime PublicationDate { get; set; }

    }
    public class BookDto
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public string AuthorName { get; set; }
        public float Rating { get; set; }
        public int ISBN { get; set; }
        public DateTime PublicationDate { get; set; }
    }
}

</code>```
```<code>using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.EntityFrameworkCore;

namespace LibraryAPI.Resources
{
    // Author model
    public class Author
    {
        [Key]
        public int Id { get; set; }
        [Column(TypeName = "nvarchar(50)")]
        public string FirstName { get; set; } = null!;
        [Column(TypeName = "nvarchar(50)")]
        public string LastName { get; set; } = null!;
        [Column(TypeName = "Datetime2")]
        public string FullName
        {
            get { return FirstName + " " + LastName; }
        }
        [Column(TypeName = "Datetime2")]
        public DateTime BirthDate { get; set; }
        [Column(TypeName = "bit")]
        public string Gender { get; set; }
        public List<Book> Books { get; set; }

    }
}

</code>```

Context:

```<code>namespace LibraryAPI.Resources;
using Microsoft.EntityFrameworkCore;

public class LibraryContext : DbContext
{
    public LibraryContext(DbContextOptions<LibraryContext> options) : base(options)
    {
    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder
             .Entity<Author>()
             .Property(e => e.Gender)
             .HasConversion<GenderToNumericCoverter>();
        modelBuilder.Entity<Book>()
            .HasOne(p => p.Author)
            .WithMany(b => b.Books);

    }
    protected override void ConfigureConventions(ModelConfigurationBuilder builder)
    {
        builder.Properties<DateOnly>()
            .HaveConversion<DateOnlyConverter>()
            .HaveColumnType("Datetime2");
    }

    public DbSet<Author> Author { get; set; } = null!;
    public DbSet<Book> Book { get; set; } = null!;
    //public DbSet<BookAuthor> BookAuthor { get; set; }
}

</code>```

Controllers:

```<code>using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using LibraryAPI.Resources;
using System.Web.Http.Description;

namespace LibraryAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class BooksController : ControllerBase
    {
        private readonly LibraryContext _context;

        public BooksController(LibraryContext context)
        {
            _context = context;
        }

        // GET: api/Books
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Book>>> GetBooks()
        {
            var books = from b in _context.Book.Include(b => b.Author)
                        select new BookDto()
                        {
                            Id = b.Id,
                            Title = b.Title,
                            Description = b.Description,
                            AuthorName = b.Author.FullName,
                            Rating = b.Rating,
                            ISBN = b.ISBN,
                            PublicationDate = b.PublicationDate
                        };

            return Ok(books);
        }

        //GET: api/BooksByAuthor/[Authorname]
        [ResponseType(typeof(BookDto))]
        [HttpGet("{AuthorName}")]
        public async Task<IActionResult> GetBooksByAuthor(string AuthorName)
        {
            var books = from b in _context.Book.Include(b => b.Author)
                        where b.Author.FullName == AuthorName
                        select new BookDto()
                        {
                            Id = b.Id,
                            Title = b.Title,
                            Description = b.Description,
                            AuthorName = b.Author.FullName,
                            Rating = b.Rating,
                            ISBN = b.ISBN,
                            PublicationDate = b.PublicationDate
                        };
            if (books == null)
            {
                return NotFound();
            }

            return Ok(books);
        }

        // GET: api/Books/[Title]
        [ResponseType(typeof(BookDto))]
        [HttpGet("{Title}")]
        public async Task<ActionResult<Book>> GetBookByTitle(string title)
        {
            var books = from b in _context.Book.Include(b => b.Author)
                        where b.Title == title
                        select new BookDto()
                        {
                            Id = b.Id,
                            Title = b.Title,
                            Description = b.Description,
                            AuthorName = b.Author.FullName,
                            Rating = b.Rating,
                            ISBN = b.ISBN,
                            PublicationDate = b.PublicationDate
                        };
            if (books == null)
            {
                return NotFound();
            }

            return Ok(books);
        }

        // PUT: api/Books/5
        [HttpPut("{id}")]
        public async Task<IActionResult> PutBook(int id, Book book)
        {
            if (id != book.Id)
            {
                return BadRequest();
            }

            _context.Entry(book).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!BookExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return Ok(book);
        }

        // POST: api/Books
        [HttpPost]
        public async Task<ActionResult<Book>> PostBook(Book book)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            _context.Book.Add(book);
            await _context.SaveChangesAsync();

            _context.Entry(book).Reference(b => b.Author).Load();

            var dto = new BookDto()
            {
                Id = book.Id,
                Title = book.Title,
                Description = book.Description,
                AuthorName = book.Author.FullName,
                Rating = book.Rating,
                ISBN = book.ISBN,
                PublicationDate = book.PublicationDate
            };
            return CreatedAtAction("GetBook", new { id = book.Id }, book);
        }

        // DELETE: api/Books/5
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteBook(int id)
        {
            var book = await _context.Book.FindAsync(id);
            if (book == null)
            {
                return NotFound();
            }

            _context.Book.Remove(book);
            await _context.SaveChangesAsync();

            return Ok();
        }

        private bool BookExists(int id)
        {
            return _context.Book.Any(e => e.Id == id);
        }
    }
}

</code>```
```<code>using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using LibraryAPI.Resources;

namespace LibraryAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AuthorsController : ControllerBase
    {
        private readonly LibraryContext _context;

        public AuthorsController(LibraryContext context)
        {
            _context = context;
        }

        // GET: api/Authors
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Author>>> GetAuthors()
        {

            return await _context.Author.Include("Book").ToListAsync();
        }

        // GET: api/Author/[FullName]
        [HttpGet("{FullName}")]
        public async Task<ActionResult<IEnumerable<Author>>> GetAuthorByName(string FullName)
        {
            var author = await _context.Author.FindAsync(FullName);

            if (author == null)
            {
                return NotFound();
            }

            return Ok(author);
        }

        // GET: api/Authors/[id]
        [HttpGet("{id}")]
        public async Task<ActionResult<Author>> GetAuthor(int id)
        {
            var author = await _context.Author.FindAsync(id);

            if (author == null)
            {
                return NotFound();
            }

            return author;
        }

        // PUT: api/Authors/5
        [HttpPut("{id}")]
        public async Task<IActionResult> PutAuthor(int id, Author author)
        {
            if (id != author.Id)
            {
                return BadRequest();
            }

            _context.Entry(author).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!AuthorExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }

        // POST: api/Authors
        [HttpPost]
        public async Task<ActionResult<Author>> PostAuthor(Author author)
        {
            _context.Author.Add(author);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetAuthor", new { id = author.Id }, author);
        }

        // DELETE: api/Authors/5
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteAuthor(int id)
        {
            var author = await _context.Author.FindAsync(id);
            if (author == null)
            {
                return NotFound();
            }

            _context.Author.Remove(author);
            await _context.SaveChangesAsync();

            return NoContent();
        }

        private bool AuthorExists(int id)
        {
            return _context.Author.Any(e => e.Id == id);
        }
    }
}

</code>```

Program.cs

```<code>using LibraryAPI;
using LibraryAPI.Resources;
using Microsoft.EntityFrameworkCore;
using System.Text.Json.Serialization;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers().AddJsonOptions(options =>
{
    options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
}); ;
builder.Services.AddMvc().AddJsonOptions(options =>
    options.JsonSerializerOptions.Converters.Add(new DateOnlyConverterJSON()));
builder.Services.AddDbContext<LibraryContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("LibraryDB")));
builder.Services.AddEndpointsApiExplorer();

var app = builder.Build();

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();
</code>```

I tried adding Foreign key attribute but it didn't change anything. I checked relationship configuration but it seems fine. Tried inverse property and still nothing.

I will glady take any other tips how to improve this code :)

Body:
im trying to create API with related entities in EF Core. I don't understand why It throwing this error:

Microsoft.Data.SqlClient.SqlException (0x80131904): Invalid column name 'AuthorId'.
   at Microsoft.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__188_0(Task`1 result)
   at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
   at System.Threading.Tasks.Task.<>c.<.cctor>b__272_0(Object obj)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
--- End of stack trace from previous location ---
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.InitializeReaderAsync(AsyncEnumerator enumerator, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
   at System.Text.Json.Serialization.Converters.IAsyncEnumerableOfTConverter`2.OnWriteResume(Utf8JsonWriter writer, TAsyncEnumerable value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonCollectionConverter`2.OnTryWrite(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.Converters.IAsyncEnumerableOfTConverter`2.OnTryWrite(Utf8JsonWriter writer, TAsyncEnumerable value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.WriteCore(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.WriteCoreAsObject(Utf8JsonWriter writer, Object value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonSerializer.WriteCore[TValue](JsonConverter jsonConverter, Utf8JsonWriter writer, TValue& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonSerializer.WriteStreamAsync[TValue](Stream utf8Json, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken)
   at System.Text.Json.JsonSerializer.WriteStreamAsync[TValue](Stream utf8Json, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken)
   at System.Text.Json.JsonSerializer.WriteStreamAsync[TValue](Stream utf8Json, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|30_0[TFilter,TFilterAsync](ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeResultFilters>g__Awaited|28_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
ClientConnectionId:a2b92e1b-ed00-4050-b7ff-23ed1f0fa3a3
Error Number:207,State:1,Class:16

HEADERS
=======
Accept: */*
Connection: keep-alive
Host: localhost:7079
User-Agent: PostmanRuntime/7.30.0
Accept-Encoding: gzip, deflate, br
Postman-Token: 3d4c8593-da6e-4682-95c5-5aa54dd7b7df

Models:

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace LibraryAPI.Resources
{
    // Book model
    public class Book
    {

        [Key]
        public int Id { get; set; }
        [Column(TypeName = "nvarchar(100)")]
        public string Title { get; set; }
        [Column(TypeName = "nvarchar(MAX)")]
        public string Description { get; set; }
        [ForeignKey("AuthorId")]
        public Author Author { get; set; }
        [Column(TypeName = "decimal")]
        public float Rating { get; set; }
        [Column(TypeName = "nvarchar(13)")]
        public int ISBN { get; set; }
        [Column(TypeName = "Datetime2")]
        public DateTime PublicationDate { get; set; }

    }
    public class BookDto
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public string AuthorName { get; set; }
        public float Rating { get; set; }
        public int ISBN { get; set; }
        public DateTime PublicationDate { get; set; }
    }
}

using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.EntityFrameworkCore;

namespace LibraryAPI.Resources
{
    // Author model
    public class Author
    {
        [Key]
        public int Id { get; set; }
        [Column(TypeName = "nvarchar(50)")]
        public string FirstName { get; set; } = null!;
        [Column(TypeName = "nvarchar(50)")]
        public string LastName { get; set; } = null!;
        [Column(TypeName = "Datetime2")]
        public string FullName
        {
            get { return FirstName + " " + LastName; }
        }
        [Column(TypeName = "Datetime2")]
        public DateTime BirthDate { get; set; }
        [Column(TypeName = "bit")]
        public string Gender { get; set; }
        public List<Book> Books { get; set; }

    }
}

Context:

namespace LibraryAPI.Resources;
using Microsoft.EntityFrameworkCore;

public class LibraryContext : DbContext
{
    public LibraryContext(DbContextOptions<LibraryContext> options) : base(options)
    {
    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder
             .Entity<Author>()
             .Property(e => e.Gender)
             .HasConversion<GenderToNumericCoverter>();
        modelBuilder.Entity<Book>()
            .HasOne(p => p.Author)
            .WithMany(b => b.Books);

    }
    protected override void ConfigureConventions(ModelConfigurationBuilder builder)
    {
        builder.Properties<DateOnly>()
            .HaveConversion<DateOnlyConverter>()
            .HaveColumnType("Datetime2");
    }

    public DbSet<Author> Author { get; set; } = null!;
    public DbSet<Book> Book { get; set; } = null!;
    //public DbSet<BookAuthor> BookAuthor { get; set; }
}

Controllers:

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using LibraryAPI.Resources;
using System.Web.Http.Description;

namespace LibraryAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class BooksController : ControllerBase
    {
        private readonly LibraryContext _context;

        public BooksController(LibraryContext context)
        {
            _context = context;
        }

        // GET: api/Books
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Book>>> GetBooks()
        {
            var books = from b in _context.Book.Include(b => b.Author)
                        select new BookDto()
                        {
                            Id = b.Id,
                            Title = b.Title,
                            Description = b.Description,
                            AuthorName = b.Author.FullName,
                            Rating = b.Rating,
                            ISBN = b.ISBN,
                            PublicationDate = b.PublicationDate
                        };

            return Ok(books);
        }

        //GET: api/BooksByAuthor/[Authorname]
        [ResponseType(typeof(BookDto))]
        [HttpGet("{AuthorName}")]
        public async Task<IActionResult> GetBooksByAuthor(string AuthorName)
        {
            var books = from b in _context.Book.Include(b => b.Author)
                        where b.Author.FullName == AuthorName
                        select new BookDto()
                        {
                            Id = b.Id,
                            Title = b.Title,
                            Description = b.Description,
                            AuthorName = b.Author.FullName,
                            Rating = b.Rating,
                            ISBN = b.ISBN,
                            PublicationDate = b.PublicationDate
                        };
            if (books == null)
            {
                return NotFound();
            }

            return Ok(books);
        }

        // GET: api/Books/[Title]
        [ResponseType(typeof(BookDto))]
        [HttpGet("{Title}")]
        public async Task<ActionResult<Book>> GetBookByTitle(string title)
        {
            var books = from b in _context.Book.Include(b => b.Author)
                        where b.Title == title
                        select new BookDto()
                        {
                            Id = b.Id,
                            Title = b.Title,
                            Description = b.Description,
                            AuthorName = b.Author.FullName,
                            Rating = b.Rating,
                            ISBN = b.ISBN,
                            PublicationDate = b.PublicationDate
                        };
            if (books == null)
            {
                return NotFound();
            }

            return Ok(books);
        }

        // PUT: api/Books/5
        [HttpPut("{id}")]
        public async Task<IActionResult> PutBook(int id, Book book)
        {
            if (id != book.Id)
            {
                return BadRequest();
            }

            _context.Entry(book).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!BookExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return Ok(book);
        }

        // POST: api/Books
        [HttpPost]
        public async Task<ActionResult<Book>> PostBook(Book book)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            _context.Book.Add(book);
            await _context.SaveChangesAsync();

            _context.Entry(book).Reference(b => b.Author).Load();

            var dto = new BookDto()
            {
                Id = book.Id,
                Title = book.Title,
                Description = book.Description,
                AuthorName = book.Author.FullName,
                Rating = book.Rating,
                ISBN = book.ISBN,
                PublicationDate = book.PublicationDate
            };
            return CreatedAtAction("GetBook", new { id = book.Id }, book);
        }

        // DELETE: api/Books/5
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteBook(int id)
        {
            var book = await _context.Book.FindAsync(id);
            if (book == null)
            {
                return NotFound();
            }

            _context.Book.Remove(book);
            await _context.SaveChangesAsync();

            return Ok();
        }

        private bool BookExists(int id)
        {
            return _context.Book.Any(e => e.Id == id);
        }
    }
}

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using LibraryAPI.Resources;

namespace LibraryAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AuthorsController : ControllerBase
    {
        private readonly LibraryContext _context;

        public AuthorsController(LibraryContext context)
        {
            _context = context;
        }

        // GET: api/Authors
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Author>>> GetAuthors()
        {

            return await _context.Author.Include("Book").ToListAsync();
        }

        // GET: api/Author/[FullName]
        [HttpGet("{FullName}")]
        public async Task<ActionResult<IEnumerable<Author>>> GetAuthorByName(string FullName)
        {
            var author = await _context.Author.FindAsync(FullName);

            if (author == null)
            {
                return NotFound();
            }

            return Ok(author);
        }

        // GET: api/Authors/[id]
        [HttpGet("{id}")]
        public async Task<ActionResult<Author>> GetAuthor(int id)
        {
            var author = await _context.Author.FindAsync(id);

            if (author == null)
            {
                return NotFound();
            }

            return author;
        }

        // PUT: api/Authors/5
        [HttpPut("{id}")]
        public async Task<IActionResult> PutAuthor(int id, Author author)
        {
            if (id != author.Id)
            {
                return BadRequest();
            }

            _context.Entry(author).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!AuthorExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }

        // POST: api/Authors
        [HttpPost]
        public async Task<ActionResult<Author>> PostAuthor(Author author)
        {
            _context.Author.Add(author);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetAuthor", new { id = author.Id }, author);
        }

        // DELETE: api/Authors/5
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteAuthor(int id)
        {
            var author = await _context.Author.FindAsync(id);
            if (author == null)
            {
                return NotFound();
            }

            _context.Author.Remove(author);
            await _context.SaveChangesAsync();

            return NoContent();
        }

        private bool AuthorExists(int id)
        {
            return _context.Author.Any(e => e.Id == id);
        }
    }
}

Program.cs

using LibraryAPI;
using LibraryAPI.Resources;
using Microsoft.EntityFrameworkCore;
using System.Text.Json.Serialization;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers().AddJsonOptions(options =>
{
    options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
}); ;
builder.Services.AddMvc().AddJsonOptions(options =>
    options.JsonSerializerOptions.Converters.Add(new DateOnlyConverterJSON()));
builder.Services.AddDbContext<LibraryContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("LibraryDB")));
builder.Services.AddEndpointsApiExplorer();

var app = builder.Build();

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

I tried adding Foreign key attribute but it didn't change anything. I checked relationship configuration but it seems fine. Tried inverse property and still nothing.

I will glady take any other tips how to improve this code :)


来源: stackexchange

问:
How to add schedulerLicenseKey on fullcalendar react-typescript
need help please,
I tried to add "schedulerLicenseKey" on Fullcalendar, but I always get an error

Here is my code:

```<code>...
 return (
  <FullCalendar
        schedulerLicenseKey="my-key"
        plugins={[timeGridPlugin]}
        initialView="timeGridDay"
        locale="fr"
        headerToolbar={false}
        ref={calendarRef}
        titleFormat={{ year: "numeric", month: "long", day: "numeric" }}
        dayHeaderFormat={{ weekday: "long" }}
        firstDay={1}
        allDaySlot={false}
        contentHeight={935}
        displayEventTime={false}
/>
)
</code>```

and this is the error I get:

```<code> No overload matches this call.
  Overload 1 of 2, '(props: CalendarOptions | Readonly<CalendarOptions>): FullCalendar', gave the following error.
    Type '{ schedulerLicenseKey: string; plugins: PluginDef[]; initialView: string; locale: string; headerToolbar: false; ref: any; titleFormat: { year: "numeric"; month: "long"; day: "numeric"; }; ... 7 more ...; scrollTime: string; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<FullCalendar> & Readonly<CalendarOptions> & Readonly<...>'.
      Property 'schedulerLicenseKey' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<FullCalendar> & Readonly<CalendarOptions> & Readonly<...>'.
  Overload 2 of 2, '(props: CalendarOptions, context: any): FullCalendar', gave the following error.
    Type '{ schedulerLicenseKey: string; plugins: PluginDef[]; initialView: string; locale: string; headerToolbar: false; ref: any; titleFormat: { year: "numeric"; month: "long"; day: "numeric"; }; ... 7 more ...; scrollTime: string; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<FullCalendar> & Readonly<CalendarOptions> & Readonly<...>'.
      Property 'schedulerLicenseKey' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<FullCalendar> & Readonly<CalendarOptions> & Readonly<...>'.
</code>```

I already tried this version, and its working! but I prefer using  the first code, than this one

```<code>  useEffect(() => {
    var calendarEl = document.getElementById("calendar")!;
    var calendar = new Calendar(calendarEl, {
      schedulerLicenseKey: "my-key",
      plugins: [resourceTimeGridPlugin],
      initialView: "resourceTimeGridDay",
      resources: resourcesList,
      locale: "fr",
      allDaySlot: false,
      now: new Date(),
    } as CalendarOptions);
    calendar.render();
  }, []);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
need help please,
I tried to add "schedulerLicenseKey" on Fullcalendar, but I always get an error

Here is my code:

...
 return (
  <FullCalendar
        schedulerLicenseKey="my-key"
        plugins={[timeGridPlugin]}
        initialView="timeGridDay"
        locale="fr"
        headerToolbar={false}
        ref={calendarRef}
        titleFormat={{ year: "numeric", month: "long", day: "numeric" }}
        dayHeaderFormat={{ weekday: "long" }}
        firstDay={1}
        allDaySlot={false}
        contentHeight={935}
        displayEventTime={false}
/>
)

and this is the error I get:

 No overload matches this call.
  Overload 1 of 2, '(props: CalendarOptions | Readonly<CalendarOptions>): FullCalendar', gave the following error.
    Type '{ schedulerLicenseKey: string; plugins: PluginDef[]; initialView: string; locale: string; headerToolbar: false; ref: any; titleFormat: { year: "numeric"; month: "long"; day: "numeric"; }; ... 7 more ...; scrollTime: string; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<FullCalendar> & Readonly<CalendarOptions> & Readonly<...>'.
      Property 'schedulerLicenseKey' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<FullCalendar> & Readonly<CalendarOptions> & Readonly<...>'.
  Overload 2 of 2, '(props: CalendarOptions, context: any): FullCalendar', gave the following error.
    Type '{ schedulerLicenseKey: string; plugins: PluginDef[]; initialView: string; locale: string; headerToolbar: false; ref: any; titleFormat: { year: "numeric"; month: "long"; day: "numeric"; }; ... 7 more ...; scrollTime: string; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<FullCalendar> & Readonly<CalendarOptions> & Readonly<...>'.
      Property 'schedulerLicenseKey' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<FullCalendar> & Readonly<CalendarOptions> & Readonly<...>'.

I already tried this version, and its working! but I prefer using  the first code, than this one

  useEffect(() => {
    var calendarEl = document.getElementById("calendar")!;
    var calendar = new Calendar(calendarEl, {
      schedulerLicenseKey: "my-key",
      plugins: [resourceTimeGridPlugin],
      initialView: "resourceTimeGridDay",
      resources: resourcesList,
      locale: "fr",
      allDaySlot: false,
      now: new Date(),
    } as CalendarOptions);
    calendar.render();
  }, []);


问:
Defining different values to an enum according to a condition in python
I'm dealing with an "apparently" simple problem with enums in Python that i cannot figure out how to solve. I just need to load different values for an enum in different environments (dev and prod). Ex:

in dev environment I`d like to define:

```<code>from enum import Enum

class PortsDev(Enum):
    service_1 = 5000
    service_2 = 5001

</code>```

in prod environment I`d like to define:

```<code>from enum import Enum

class Ports(Enum):
    service_1 = 3000
    service_2 = 3001

</code>```

I'm using conditional import, as:

```<code>if os.getenv("APPLICATION_CONFIG") == "production":
    from .services_ports import Ports
else:
    from .services_ports import PortsDev as Ports
</code>```

It works, but, the pre-commit fails on mypy with error.

Does anyone have a suggestion for a better way to do this?

Thanks in advance

Body:
I'm dealing with an "apparently" simple problem with enums in Python that i cannot figure out how to solve. I just need to load different values for an enum in different environments (dev and prod). Ex:

in dev environment I`d like to define:

from enum import Enum

class PortsDev(Enum):
    service_1 = 5000
    service_2 = 5001

in prod environment I`d like to define:

from enum import Enum

class Ports(Enum):
    service_1 = 3000
    service_2 = 3001

I'm using conditional import, as:

if os.getenv("APPLICATION_CONFIG") == "production":
    from .services_ports import Ports
else:
    from .services_ports import PortsDev as Ports

It works, but, the pre-commit fails on mypy with error.

Does anyone have a suggestion for a better way to do this?

Thanks in advance


问:
how to get attendances Track from the Google API?
We are using the API of google calendar to create events and we have some invites to that, the problem is that we want to get the Attendance, we know that calendar has the feature Attendance Tracking, and that works perfectly, but we need to get that information from the google API. for now it sends me a email at the end of the meet with an excel with that information. but I need to get it from the API cos, we have a lot of meeting and need to update this information automaticly.

thanks a lot if you give some route or some idea to reach it!!!

I am triging to get this information from the caelndar API V3 following this doc but I just get the event info and attendees, but I need to get the Attendance.


问:
Android OnActivityResult gave me a NULL value with getStringExtra()
I'm trying to get a response inside the onActivityResult from an uri intent. However, it is always -1 as resultCode and null as Intent data.

```<code>  private fun startMyFunction(call: MethodCall) {
    val app: String? = call.argument("app")
    val url: String? = call.argument("url")

    try {
      val uri = Uri.parse(url)

      val intent = Intent(Intent.ACTION_VIEW, uri)
      intent.setPackage(app)

      if (activity?.let { intent.resolveActivity(it.packageManager) } == null) {
        this.success("activity_unavailable")
        return
      }

      activity?.startActivityForResult(intent, requestCodeNumber)
    } catch (ex: Exception) {
      Log.e("my_app", ex.toString())
      this.success("failed_to_open_app")
    }
  }
</code>```
```<code>  private fun success(o: String) {
    if (!hasResponded) {
      hasResponded = true
      result?.success(o)
    }
  }
</code>```
```<code>  override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?): Boolean {
    if (requestCodeNumber == requestCode && result != null) {
      Log.d("onActivityResult - response - ", data.toString())
      if (data != null) {
        try {
          val response = data.getStringExtra("response")!!
          this.success(response)
        } catch (ex: Exception) {
          this.success("invalid_response - Exception")
        }
      } else {
        this.success("user_cancelled - Null data")
      }
    }
    return true
  }
</code>```

I have read many of the similar situations here on StackOverflow, as well as on Google, but none of them have helped me in my case

For ref -
https://github.com/GJJ2019/upi_pay/blob/master/android/src/main/kotlin/com/drenther/upi_pay/UpiPayPlugin.kt

Body:
I'm trying to get a response inside the onActivityResult from an uri intent. However, it is always -1 as resultCode and null as Intent data.

  private fun startMyFunction(call: MethodCall) {
    val app: String? = call.argument("app")
    val url: String? = call.argument("url")

    try {
      val uri = Uri.parse(url)

      val intent = Intent(Intent.ACTION_VIEW, uri)
      intent.setPackage(app)

      if (activity?.let { intent.resolveActivity(it.packageManager) } == null) {
        this.success("activity_unavailable")
        return
      }

      activity?.startActivityForResult(intent, requestCodeNumber)
    } catch (ex: Exception) {
      Log.e("my_app", ex.toString())
      this.success("failed_to_open_app")
    }
  }

  private fun success(o: String) {
    if (!hasResponded) {
      hasResponded = true
      result?.success(o)
    }
  }

  override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?): Boolean {
    if (requestCodeNumber == requestCode && result != null) {
      Log.d("onActivityResult - response - ", data.toString())
      if (data != null) {
        try {
          val response = data.getStringExtra("response")!!
          this.success(response)
        } catch (ex: Exception) {
          this.success("invalid_response - Exception")
        }
      } else {
        this.success("user_cancelled - Null data")
      }
    }
    return true
  }

I have read many of the similar situations here on StackOverflow, as well as on Google, but none of them have helped me in my case

For ref -
https://github.com/GJJ2019/upi_pay/blob/master/android/src/main/kotlin/com/drenther/upi_pay/UpiPayPlugin.kt


问:
How to uninitialize a variable In Flutter / Dart?
I define a variable ui.Image? previewImage; (ui refers to dart:ui).

I then start an image stream from the camera that performs YOLOX classifications and pairs them with an image, and updates the variable previewImage with the classification results with a function onDetected():

```<code>  onDetected(
    List<YoloxResults> results,
    ui.Image image,
  ) {
    setState(() {
      yoloxResults = results;
      previewImage = image;
    });
  }
</code>```

The yoloxResults and previewImage are then displayed with a widget:

```<code>  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        if (previewImage == null) {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }

        final cameraWidget = FittedBox(
          child: SizedBox(
            width: previewImage!.width.toDouble(),
            height: previewImage!.height.toDouble(),
            child: CustomPaint(
              painter: YoloxResultsPainter(
                image: previewImage!,
                results: results,
                labels: labels,
              ),
            ),
          ),
        );

        return cameraWidget;
      },
    );
  }
</code>```

I have a page where I switch between the above widget and another body widget via a Ternary Operator...

The first time I load the cameraWidget, previewImage is null and displays the CircularProgressIndicator() before the previewImage is set via the onDetected() function (which is what I want).

The second time I open the cameraWidget previewImage is already defined and an old image is displayed before the onDetected() function updates...  I have tried setState previewImage = null, which calls the CircleProgressIndicator() but then displays an old previewImage first, and before updating...

My Question: How can I reset the previewImage variable to being uninitialized?

How can I remove the data assigned to previewImage?

Body:
I define a variable ui.Image? previewImage; (ui refers to dart:ui).

I then start an image stream from the camera that performs YOLOX classifications and pairs them with an image, and updates the variable previewImage with the classification results with a function onDetected():

  onDetected(
    List<YoloxResults> results,
    ui.Image image,
  ) {
    setState(() {
      yoloxResults = results;
      previewImage = image;
    });
  }

The yoloxResults and previewImage are then displayed with a widget:

  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        if (previewImage == null) {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }

        final cameraWidget = FittedBox(
          child: SizedBox(
            width: previewImage!.width.toDouble(),
            height: previewImage!.height.toDouble(),
            child: CustomPaint(
              painter: YoloxResultsPainter(
                image: previewImage!,
                results: results,
                labels: labels,
              ),
            ),
          ),
        );

        return cameraWidget;
      },
    );
  }

I have a page where I switch between the above widget and another body widget via a Ternary Operator...

The first time I load the cameraWidget, previewImage is null and displays the CircularProgressIndicator() before the previewImage is set via the onDetected() function (which is what I want).

The second time I open the cameraWidget previewImage is already defined and an old image is displayed before the onDetected() function updates...  I have tried setState previewImage = null, which calls the CircleProgressIndicator() but then displays an old previewImage first, and before updating...

My Question: How can I reset the previewImage variable to being uninitialized?

How can I remove the data assigned to previewImage?


问:
Is it possible to add http headers to a Soap request from the SoapExtension method ProcessMessage()
I am trying to add Digital Security headers to some api calls that leverage a third-party sdk. One of the required security headers is a hash of the entire POST body being sent. The sdk we are leveraging calls a SOAP endpoint and the construction of the soap envelope is very far along in the request process. The sdk offered some obvious BeforeRequest extension points but they are executed before the SoapEnvelope is constructed.

There are a couple ways I have attempted to solve this:

I was trying to take a serializable object and recreate the request with the soap envelope but doing so did not yield a matching string as there were namespaces that were applied when they shouldnt, encoding on innner objects serialization etc (I am sure I am doing things wrong but these struggles got me looking elsewhere)

Next I found the SoapExtension class and thought this would work for me. In my testing I am seeing that I get the full request body (with the SOAP envelope) exactly as it would be sent. But I do not think or cannot find a way to modify the http headers of this request from within the hooks in SoapExtension.

So the question I am asking here is focused on my second approach and wondering if this is possible. If not I will go back to my first attempt and see if I can figure out how to correctly generate an identical request body.


问:
Can't query datetime column in SQLAlchemy with postgreSQL
I want to delete rows based on a datetime filter.

I created a table with DateTime column without timezone using similar script.

class VolumeInfo(Base):
    ...
    date: datetime.datetime = Column(DateTime, nullable=False)
```
<p>Then I try to delete rows using such filter</p>
<pre class="lang-py prettyprint-override"><code>days_interval = 10
to_date = datetime.datetime.combine(
            datetime.datetime.utcnow().date(),
            datetime.time(0, 0, 0, 0),
        ).replace(tzinfo=None)
from_date = to_date - datetime.timedelta(days=days_interval)

query = delete(VolumeInfo).where(Volume.date < from_date)
</code>```

Unexpectedly, sometimes there is no error, but sometimes there is the error:

```<code>Traceback (most recent call last):
  ...
  File "script.py", line 381, in delete_volumes
    db.execute(query)
  File "/usr/local/lib/python3.10/site-packages/sqlalchemy/orm/session.py", line 1660, in execute
    ) = compile_state_cls.orm_pre_session_exec(
  File "/usr/local/lib/python3.10/site-packages/sqlalchemy/orm/persistence.py", line 1843, in orm_pre_session_exec
    update_options = cls._do_pre_synchronize_evaluate(
  File "/usr/local/lib/python3.10/site-packages/sqlalchemy/orm/persistence.py", line 2007, in _do_pre_synchronize_evaluate
    matched_objects = [
  File "/usr/local/lib/python3.10/site-packages/sqlalchemy/orm/persistence.py", line 2012, in <listcomp>
    and eval_condition(state.obj())
  File "/usr/local/lib/python3.10/site-packages/sqlalchemy/orm/evaluator.py", line 211, in evaluate
    return operator(eval_left(obj), eval_right(obj))
TypeError: can't compare offset-naive and offset-aware datetimes
</code>```

Using python3.10 in docker (image python:3.10-slim) and postgreSQL database with psycopg2 driver.
I have already tried all possible options, but this error appears every once in a while

How can i solve this? or where I made a mistake?

UPD1:

Body:
I want to delete rows based on a datetime filter.

I created a table with DateTime column without timezone using similar script.

class VolumeInfo(Base):
    ...
    date: datetime.datetime = Column(DateTime, nullable=False)

Then I try to delete rows using such filter

days_interval = 10
to_date = datetime.datetime.combine(
            datetime.datetime.utcnow().date(),
            datetime.time(0, 0, 0, 0),
        ).replace(tzinfo=None)
from_date = to_date - datetime.timedelta(days=days_interval)

query = delete(VolumeInfo).where(Volume.date < from_date)

Unexpectedly, sometimes there is no error, but sometimes there is the error:

Traceback (most recent call last):
  ...
  File "script.py", line 381, in delete_volumes
    db.execute(query)
  File "/usr/local/lib/python3.10/site-packages/sqlalchemy/orm/session.py", line 1660, in execute
    ) = compile_state_cls.orm_pre_session_exec(
  File "/usr/local/lib/python3.10/site-packages/sqlalchemy/orm/persistence.py", line 1843, in orm_pre_session_exec
    update_options = cls._do_pre_synchronize_evaluate(
  File "/usr/local/lib/python3.10/site-packages/sqlalchemy/orm/persistence.py", line 2007, in _do_pre_synchronize_evaluate
    matched_objects = [
  File "/usr/local/lib/python3.10/site-packages/sqlalchemy/orm/persistence.py", line 2012, in <listcomp>
    and eval_condition(state.obj())
  File "/usr/local/lib/python3.10/site-packages/sqlalchemy/orm/evaluator.py", line 211, in evaluate
    return operator(eval_left(obj), eval_right(obj))
TypeError: can't compare offset-naive and offset-aware datetimes

Using python3.10 in docker (image python:3.10-slim) and postgreSQL database with psycopg2 driver.
I have already tried all possible options, but this error appears every once in a while

How can i solve this? or where I made a mistake?

UPD1:


问:
Sending Email with Ruby on Rails and OAuth2 (Office 365)
Our application is built on

ruby 2.2.1p85

Rails 4.2.5

We use ActionMailer to send notification emails. My old code that rely on ActionMailer and SMTP is:

```<code>  ActionMailer::Base.smtp_settings = {
    :address => "smtp.office365.com",
    :port => 587,
    :domain => "smtp.office365.com",
    :authentication => :login,
    :user_name => "MY_EMAIL_ADDRESS",
    :password => "MY_PASSWORD",
    :enable_starttls_auto => true
  }

  ......

  def general_mail (to, subject, content, attachmts = [] )
    attachmts.each do |attachment|
        attachments[File.basename(attachment)] = File.read(attachment, mode: 'rb')
    end

    mail(to: to, subject: subject) do |format|
        format.text { render :text => content }
    end
  end
</code>```

The code now is not working because the old authentication method will be deprecated and switch to OAuth2.

Can someone help me to make the notification email code work again under Oauth2?

Thank you so much!

Body:
Our application is built on

ruby 2.2.1p85

Rails 4.2.5

We use ActionMailer to send notification emails. My old code that rely on ActionMailer and SMTP is:

  ActionMailer::Base.smtp_settings = {
    :address => "smtp.office365.com",
    :port => 587,
    :domain => "smtp.office365.com",
    :authentication => :login,
    :user_name => "MY_EMAIL_ADDRESS",
    :password => "MY_PASSWORD",
    :enable_starttls_auto => true
  }

  ......

  def general_mail (to, subject, content, attachmts = [] )
    attachmts.each do |attachment|
        attachments[File.basename(attachment)] = File.read(attachment, mode: 'rb')
    end

    mail(to: to, subject: subject) do |format|
        format.text { render :text => content }
    end
  end

The code now is not working because the old authentication method will be deprecated and switch to OAuth2.

Can someone help me to make the notification email code work again under Oauth2?

Thank you so much!


问:
ValueError: X has 1 features, but KNeighborsClassifier is expecting 112 features as input. Explored the existing solution
When I am running the following Code, I get this error. How could I solve this?

```<code>model = KNeighborsClassifier(n_neighbors=19)
#model.fit(X_train, Y_train.values.ravel())
model.fit(X_train, Y_train)
prediction = model.predict(X_test)
print("KNN")
print("Accuracy = ",accuracy_score(Y_test, prediction))
print("Confusion Matrix =")
print(confusion_matrix(Y_test, prediction))
print(classification_report(Y_test, prediction))
</code>```

Body:
When I am running the following Code, I get this error. How could I solve this?

model = KNeighborsClassifier(n_neighbors=19)
#model.fit(X_train, Y_train.values.ravel())
model.fit(X_train, Y_train)
prediction = model.predict(X_test)
print("KNN")
print("Accuracy = ",accuracy_score(Y_test, prediction))
print("Confusion Matrix =")
print(confusion_matrix(Y_test, prediction))
print(classification_report(Y_test, prediction))


问:
@getyoti/react-native-yoti-face-capture - prompts FaceCaptureAnalysisErrorFaceAnalysisFailed on inialization of Face Analysis
I'm using @getyoti/react-native-yoti-face-capture to capture a user's face. However, the only response I received once I triggered YotiFaceCaptureRef.current.startAnalyzing(); is FaceCaptureAnalysisErrorFaceAnalysisFailed.

Below is my full code.

```<code>import * as React from 'react';
import AutoHeightImage from 'react-native-auto-height-image';
import { check, PERMISSIONS, request, RESULTS } from 'react-native-permissions';
import { Platform, StyleSheet, ScrollView, View, TouchableOpacity, Text, Dimensions } from 'react-native';
import YotiFaceCapture, { IMAGE_QUALITY_MEDIUM } from '@getyoti/react-native-yoti-face-capture';
import { AuthContext } from '../../navigation/AuthProvider';
import { validateObject } from '../../functions';
import { FormButton, FormButtonLoading, FormButtonTitle, CameraButton, FormClicks } from './styled';
import Entypo from 'react-native-vector-icons/Entypo';
import EvilIcons from 'react-native-vector-icons/EvilIcons';
import Ionicons from 'react-native-vector-icons/Ionicons';
import { projectName } from '../../config';

const {height, width} = Dimensions.get('window');

export default function FaceCapture({ navigation }) {

  const { faceCapture, logout } = React.useContext(AuthContext);

  const YotiFaceCaptureRef = React.useRef(null);

  const [base64, setBase64] = React.useState(null);
  const [cameraIsRunning, setCameraIsRunning] = React.useState(false);
  const [isAnalyzing, setIsAnalyzing] = React.useState(false);
  const [permission, setPermission] = React.useState({status:false, type:'normal'});
  const [shot, setShot] = React.useState({status:false, capture:false});
  const [submit, setSubmit] = React.useState({show:false,process:false});
  const [error, setError] = React.useState(null);

  React.useEffect(
    () =>
      navigation.addListener('beforeRemove', (e) => {
        e.preventDefault();
      }),
    [navigation]
  );

  const checkStatus = async (result, group, comment) => {

    var status = false
    try {

      setPermission({status:status ? false : true, type:'normal'})

      switch (result) {

          case RESULTS.GRANTED: status = true; break;

          case RESULTS.DENIED: {

             if(group == 'location')
             {
                var res = await request(Platform.OS === 'ios' ? PERMISSIONS.IOS.LOCATION_WHEN_IN_USE : PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION);
             }
             else if(group == 'camera')
             {
                var res = await request(Platform.OS === 'ios' ? PERMISSIONS.IOS.CAMERA : PERMISSIONS.ANDROID.CAMERA);
             }
             else if(group == 'contact')
             {
                var res = await request(Platform.OS === 'ios' ? PERMISSIONS.IOS.CONTACTS : PERMISSIONS.ANDROID.READ_CONTACTS);
             }
             else if(group == 'phone')
             {
                var res = await request(Platform.OS === 'ios' ? PERMISSIONS.IOS.CALL_PHONE : PERMISSIONS.ANDROID.CALL_PHONE);
             }

             if(res === RESULTS.GRANTED) status = true;

             else
             {
                setPermission({status:true, type:'normal'})

                setError(comment);
             }

          } break;

          case RESULTS.BLOCKED: {

            setPermission({status:true, type:'setting'})

            setError(comment + ' Go to setting now to enable it?');

          } break;

          case RESULTS.UNAVAILABLE: case RESULTS.LIMITED: {

            setError('Your device does not support some functionalities required to swiftly run ' + projectName + ' app. Try with a more advance device');

            setPermission({status:false})

          } break;

          default : {

            setError('Unknown error was encountered. Kindly try again; but if issue persist, you may have to reboot ' + projectName + ' app before trying again.');

            setPermission({status:true, type:'normal'})

          } break;
       }

       if(status)
       {
          setPermission({status:false})

          setShot({status:true, capture:false})

          YotiFaceCaptureRef.current.startCamera();
       }

       return status;
    }
    finally{}

  }

  const requestPermission = () => {
    {
      let status = Platform.OS === 'ios' ? PERMISSIONS.IOS.CAMERA : PERMISSIONS.ANDROID.CAMERA;

      check(status)
        .then((result) => {
          checkStatus(result, 'camera', 'Unfortunately, ' + projectName + ' need access to your camera in order to complete your registration.')
        })
        .catch(() => {
          setError('Camera permission request failed.');
        });
    }
  }

  React.useEffect(() => requestPermission(), []);

  const proceed = async (e) => {

    setSubmit({show:true,process:true})

    if(!validateObject(base64))
    {
      return setError('Picture not found')
    }

    const res = await faceCapture(JSON.stringify({height:'', width:'', fileSize:'', type:'image/jpeg', base64:base64}) )

    if(res.status == 'success')
    {
      setBase64(null)
    }
    else
    {
      setError(res.message)

      setSubmit({show:true,process:false})

      setShot({status:false, capture:false})
    }

    return
  }

  return (
    <ScrollView style={{flex:1}} contentContainerStyle={styles.container}>
      <Text style={styles.header}>Face capture</Text>
      {validateObject(base64) ?
        <CameraFrame>
          <AutoHeightImage
            width={200}
            source={{
              uri: `data:image/jpeg;base64,${base64}`,
            }}
            style={styles.preview}
          />

          <CameraUndo onPress={() => {
            setBase64(null)

            setShot({status:true, capture:false})

            setSubmit({show:false, process:false})

            setError(null)

            YotiFaceCaptureRef.current.startCamera();
        }}><EvilIcons name="undo" size={30} color="#fff" /></CameraUndo>
        </CameraFrame>
      :
        <YotiFaceCapture
          imageQuality={IMAGE_QUALITY_MEDIUM}
          requireEyesOpen={true}
          requiredStableFrames={3}
          requireValidAngle={false}
          requireBrightEnvironment
          faceCenter={[0.5, 0.5]}
          onFaceCaptureAnalyzedImage={(result) => {
            const { croppedImage } = result;
console.log(result)
            if(uri !== croppedImage) setBase64(croppedImage);

            setError(null);

            setSubmit({show:true, process:false})

            setShot({status:false, capture:false})
          }}
          onFaceCaptureImageAnalysisFailed={({ cause }) => {

            var message = '';

            switch(cause)
            {
              case 'FaceCaptureAnalysisErrorFaceTooBig' : { message = 'Face is too big. Move camera a little distance away.'; } break

              case 'FaceCaptureAnalysisErrorEyesNotOpen' : { message = 'Your eyes seem to be closed. Open eyes for enhanced gratification.'; } break

              case 'FaceCaptureAnalysisErrorFaceTooSmall' : { message = 'Face is too small. Move camera a little closer.'; } break

              case 'FaceCaptureAnalysisErrorFaceNotStable' : { message = 'Face is not stable.'; } break

              case 'FaceCaptureAnalysisErrorNoFaceDetected' : { message = 'Your face could not be detected.'; } break

              case 'FaceCaptureAnalysisErrorFaceNotCentered' : { message = 'Center your face to the screen.'; } break

              case 'FaceCaptureAnalysisErrorFaceNotStraight' : { message = 'Your face should be positioned straight.'; } break

              case 'FaceCaptureAnalysisErrorMultipleFaces' : { message = 'Multiple faces detected. Only registrant\'s face should be captured.'; } break

              case 'FaceCaptureAnalysisErrorEnvironmentTooDark' : { message = 'Your environment is too dark. Kindly move to a bright environment.'; } break

              case 'FaceCaptureAnalysisErrorFaceAnalysisFailed' : { message = 'Face detection failed. Try again.'; } break

              default : setShot({status:true, capture:true}); break
            }

            if(message != '')
            {
              YotiFaceCaptureRef.current.startCamera();

              setShot({status:true, capture:false})

              setError(() => message)
            }
          }}
          onFaceCaptureStateChanged={(state) => {
            console.log('State Changed => ', state)
          }}
          onFaceCaptureStateFailed={(reason) => {

            var message = '';  setPermission(false)

            switch(reason)
            {
              case 'FaceCaptureStateErrorCameraInitializingError' : { message = 'Error initializing camera.'; setShot({status:false, capture:false}) } break

              case 'FaceCaptureStateErrorCameraNotAccessible' : { message = 'Error connecting to camera. Permission to camera is required.'; setShot(false); setPermission({status:true, type:'normal'}) } break

              case 'FaceCaptureStateErrorInvalidState' : { message = 'Unknown error occured.'; setShot({status:false, capture:false}) } break

              default : setShot({status:true, capture:false}); break
            }

            setError(() => message)
          }}
          style={styles.aperture}
          ref={YotiFaceCaptureRef}
        />}
      <View style={styles.buttonContainer}>
        {validateObject(error) ? <Text style={styles.log}>{error}</Text> : null}

        {permission.status ?

          <Button
            activeOpacity={0.8}
            onPress={() => permission.type == 'setting' ? Linking.openSettings() : requestPermission()}
          >Grant access</Button>

        : submit.show ?

          <FormButton activeOpacity={submit.process ? 1 : 0.8} onPress={() => submit.process ? {} : proceed()} disabled={submit.process ? true : false}>

            <FormButtonTitle>{submit.process ? 'Processing...' : 'Submit'}</FormButtonTitle>

            {submit.process ? <FormButtonLoading source={require('../../assets/icons/dummy/load.gif')} /> : null}

          </FormButton>

        : shot.status ?

          <FormClicks>

            <CameraButton activeOpacity={0.7} onPress={() => {
              if (shot.capture == 1)
              {
                YotiFaceCaptureRef.current.stopAnalyzing();

                YotiFaceCaptureRef.current.stopCamera();

                setShot({status:false, capture:false})

                return;
              }

              YotiFaceCaptureRef.current.startAnalyzing();

              setShot({status:true, capture:true})
            }}>

                {shot.capture ? <Entypo name="camera" size={16} color="#555" /> : <Ionicons name="md-analytics" size={18} color="#555" />}

            </CameraButton>

          </FormClicks>

        : null}

        <TouchableOpacity
          activeOpacity={0.8}
          style={{marginTop:15}}
          onPress={async() => {await logout(true)}}
        >
          <Text style={{}}>Sign out</Text>
        </TouchableOpacity>
      </View>
    </ScrollView>
  );
}

function Button({ children, onPress }) {
  return (
    <TouchableOpacity onPress={onPress} style={styles.button}>
      <Text style={styles.buttonText}>{children}</Text>
    </TouchableOpacity>
  );
}

const styles = StyleSheet.create({
  container: {
    minHeight:'100%',
    width:'100%',
    alignContent:'center',
    alignItems:'center',
    backgroundColor:'#fff'
  },
  header: {
    width:'100%',
    marginTop:20,
    fontSize:17,
    textAlign:'center',
  },
  aperture: {
    width: '85%',
    height: undefined,
    aspectRatio: width / (height - 150),
    marginLeft:'auto',
    marginRight:'auto',
    marginTop:20,
    marginBottom:20,
    backgroundColor:'#333'
  },
  buttonContainer: {
    width: '100%',
    marginTop: 0,
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal:'7.5%',
    paddingBottom:30,
    flex:1,
  },
  log: {
    fontSize:14,
    color:'#E80000',
    backgroundColor:'rgba(244, 148, 143, 0.12)',
    textAlign:'center',
    lineHeight:26,
    padding:20,
    borderRadius:7,
    marginVertical: 5
  },
  previewContainer: {
    width: '85%',
    height: undefined,
    aspectRatio: width / (height - 150),
    marginLeft:'auto',
    marginRight:'auto',
    marginTop:20,
    marginBottom:20,
    borderColor: '#eeee',
    borderWidth: 3,
    padding: 5,
    alignItems: 'center',
    justifyContent: 'center',
  },
  preview: {
    width: 200,
  },
  button: {
    backgroundColor: '#2d9fff',
    margin: 5,
    marginHorizontal: 20,
    borderRadius: 5,
    padding: 10,
    zIndex: 1000,
    alignItems: 'center',
  },
  buttonText: { color: 'white', fontSize: 20 },
});
</code>```

How do I resolve this issue; as this happen on all app I installed the apk?

Body:
I'm using @getyoti/react-native-yoti-face-capture to capture a user's face. However, the only response I received once I triggered YotiFaceCaptureRef.current.startAnalyzing(); is FaceCaptureAnalysisErrorFaceAnalysisFailed.

Below is my full code.

import * as React from 'react';
import AutoHeightImage from 'react-native-auto-height-image';
import { check, PERMISSIONS, request, RESULTS } from 'react-native-permissions';
import { Platform, StyleSheet, ScrollView, View, TouchableOpacity, Text, Dimensions } from 'react-native';
import YotiFaceCapture, { IMAGE_QUALITY_MEDIUM } from '@getyoti/react-native-yoti-face-capture';
import { AuthContext } from '../../navigation/AuthProvider';
import { validateObject } from '../../functions';
import { FormButton, FormButtonLoading, FormButtonTitle, CameraButton, FormClicks } from './styled';
import Entypo from 'react-native-vector-icons/Entypo';
import EvilIcons from 'react-native-vector-icons/EvilIcons';
import Ionicons from 'react-native-vector-icons/Ionicons';
import { projectName } from '../../config';

const {height, width} = Dimensions.get('window');

export default function FaceCapture({ navigation }) {

  const { faceCapture, logout } = React.useContext(AuthContext);

  const YotiFaceCaptureRef = React.useRef(null);

  const [base64, setBase64] = React.useState(null);
  const [cameraIsRunning, setCameraIsRunning] = React.useState(false);
  const [isAnalyzing, setIsAnalyzing] = React.useState(false);
  const [permission, setPermission] = React.useState({status:false, type:'normal'});
  const [shot, setShot] = React.useState({status:false, capture:false});
  const [submit, setSubmit] = React.useState({show:false,process:false});
  const [error, setError] = React.useState(null);

  React.useEffect(
    () =>
      navigation.addListener('beforeRemove', (e) => {
        e.preventDefault();
      }),
    [navigation]
  );

  const checkStatus = async (result, group, comment) => {

    var status = false
    try {

      setPermission({status:status ? false : true, type:'normal'})

      switch (result) {

          case RESULTS.GRANTED: status = true; break;

          case RESULTS.DENIED: {

             if(group == 'location')
             {
                var res = await request(Platform.OS === 'ios' ? PERMISSIONS.IOS.LOCATION_WHEN_IN_USE : PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION);
             }
             else if(group == 'camera')
             {
                var res = await request(Platform.OS === 'ios' ? PERMISSIONS.IOS.CAMERA : PERMISSIONS.ANDROID.CAMERA);
             }
             else if(group == 'contact')
             {
                var res = await request(Platform.OS === 'ios' ? PERMISSIONS.IOS.CONTACTS : PERMISSIONS.ANDROID.READ_CONTACTS);
             }
             else if(group == 'phone')
             {
                var res = await request(Platform.OS === 'ios' ? PERMISSIONS.IOS.CALL_PHONE : PERMISSIONS.ANDROID.CALL_PHONE);
             }

             if(res === RESULTS.GRANTED) status = true;

             else
             {
                setPermission({status:true, type:'normal'})

                setError(comment);
             }

          } break;

          case RESULTS.BLOCKED: {

            setPermission({status:true, type:'setting'})

            setError(comment + ' Go to setting now to enable it?');

          } break;

          case RESULTS.UNAVAILABLE: case RESULTS.LIMITED: {

            setError('Your device does not support some functionalities required to swiftly run ' + projectName + ' app. Try with a more advance device');

            setPermission({status:false})

          } break;

          default : {

            setError('Unknown error was encountered. Kindly try again; but if issue persist, you may have to reboot ' + projectName + ' app before trying again.');

            setPermission({status:true, type:'normal'})

          } break;
       }

       if(status)
       {
          setPermission({status:false})

          setShot({status:true, capture:false})

          YotiFaceCaptureRef.current.startCamera();
       }

       return status;
    }
    finally{}

  }

  const requestPermission = () => {
    {
      let status = Platform.OS === 'ios' ? PERMISSIONS.IOS.CAMERA : PERMISSIONS.ANDROID.CAMERA;

      check(status)
        .then((result) => {
          checkStatus(result, 'camera', 'Unfortunately, ' + projectName + ' need access to your camera in order to complete your registration.')
        })
        .catch(() => {
          setError('Camera permission request failed.');
        });
    }
  }

  React.useEffect(() => requestPermission(), []);

  const proceed = async (e) => {

    setSubmit({show:true,process:true})

    if(!validateObject(base64))
    {
      return setError('Picture not found')
    }

    const res = await faceCapture(JSON.stringify({height:'', width:'', fileSize:'', type:'image/jpeg', base64:base64}) )

    if(res.status == 'success')
    {
      setBase64(null)
    }
    else
    {
      setError(res.message)

      setSubmit({show:true,process:false})

      setShot({status:false, capture:false})
    }

    return
  }

  return (
    <ScrollView style={{flex:1}} contentContainerStyle={styles.container}>
      <Text style={styles.header}>Face capture</Text>
      {validateObject(base64) ?
        <CameraFrame>
          <AutoHeightImage
            width={200}
            source={{
              uri: `data:image/jpeg;base64,${base64}`,
            }}
            style={styles.preview}
          />

          <CameraUndo onPress={() => {
            setBase64(null)

            setShot({status:true, capture:false})

            setSubmit({show:false, process:false})

            setError(null)

            YotiFaceCaptureRef.current.startCamera();
        }}><EvilIcons name="undo" size={30} color="#fff" /></CameraUndo>
        </CameraFrame>
      :
        <YotiFaceCapture
          imageQuality={IMAGE_QUALITY_MEDIUM}
          requireEyesOpen={true}
          requiredStableFrames={3}
          requireValidAngle={false}
          requireBrightEnvironment
          faceCenter={[0.5, 0.5]}
          onFaceCaptureAnalyzedImage={(result) => {
            const { croppedImage } = result;
console.log(result)
            if(uri !== croppedImage) setBase64(croppedImage);

            setError(null);

            setSubmit({show:true, process:false})

            setShot({status:false, capture:false})
          }}
          onFaceCaptureImageAnalysisFailed={({ cause }) => {

            var message = '';

            switch(cause)
            {
              case 'FaceCaptureAnalysisErrorFaceTooBig' : { message = 'Face is too big. Move camera a little distance away.'; } break

              case 'FaceCaptureAnalysisErrorEyesNotOpen' : { message = 'Your eyes seem to be closed. Open eyes for enhanced gratification.'; } break

              case 'FaceCaptureAnalysisErrorFaceTooSmall' : { message = 'Face is too small. Move camera a little closer.'; } break

              case 'FaceCaptureAnalysisErrorFaceNotStable' : { message = 'Face is not stable.'; } break

              case 'FaceCaptureAnalysisErrorNoFaceDetected' : { message = 'Your face could not be detected.'; } break

              case 'FaceCaptureAnalysisErrorFaceNotCentered' : { message = 'Center your face to the screen.'; } break

              case 'FaceCaptureAnalysisErrorFaceNotStraight' : { message = 'Your face should be positioned straight.'; } break

              case 'FaceCaptureAnalysisErrorMultipleFaces' : { message = 'Multiple faces detected. Only registrant\'s face should be captured.'; } break

              case 'FaceCaptureAnalysisErrorEnvironmentTooDark' : { message = 'Your environment is too dark. Kindly move to a bright environment.'; } break

              case 'FaceCaptureAnalysisErrorFaceAnalysisFailed' : { message = 'Face detection failed. Try again.'; } break

              default : setShot({status:true, capture:true}); break
            }

            if(message != '')
            {
              YotiFaceCaptureRef.current.startCamera();

              setShot({status:true, capture:false})

              setError(() => message)
            }
          }}
          onFaceCaptureStateChanged={(state) => {
            console.log('State Changed => ', state)
          }}
          onFaceCaptureStateFailed={(reason) => {

            var message = '';  setPermission(false)

            switch(reason)
            {
              case 'FaceCaptureStateErrorCameraInitializingError' : { message = 'Error initializing camera.'; setShot({status:false, capture:false}) } break

              case 'FaceCaptureStateErrorCameraNotAccessible' : { message = 'Error connecting to camera. Permission to camera is required.'; setShot(false); setPermission({status:true, type:'normal'}) } break

              case 'FaceCaptureStateErrorInvalidState' : { message = 'Unknown error occured.'; setShot({status:false, capture:false}) } break

              default : setShot({status:true, capture:false}); break
            }

            setError(() => message)
          }}
          style={styles.aperture}
          ref={YotiFaceCaptureRef}
        />}
      <View style={styles.buttonContainer}>
        {validateObject(error) ? <Text style={styles.log}>{error}</Text> : null}

        {permission.status ?

          <Button
            activeOpacity={0.8}
            onPress={() => permission.type == 'setting' ? Linking.openSettings() : requestPermission()}
          >Grant access</Button>

        : submit.show ?

          <FormButton activeOpacity={submit.process ? 1 : 0.8} onPress={() => submit.process ? {} : proceed()} disabled={submit.process ? true : false}>

            <FormButtonTitle>{submit.process ? 'Processing...' : 'Submit'}</FormButtonTitle>

            {submit.process ? <FormButtonLoading source={require('../../assets/icons/dummy/load.gif')} /> : null}

          </FormButton>

        : shot.status ?

          <FormClicks>

            <CameraButton activeOpacity={0.7} onPress={() => {
              if (shot.capture == 1)
              {
                YotiFaceCaptureRef.current.stopAnalyzing();

                YotiFaceCaptureRef.current.stopCamera();

                setShot({status:false, capture:false})

                return;
              }

              YotiFaceCaptureRef.current.startAnalyzing();

              setShot({status:true, capture:true})
            }}>

                {shot.capture ? <Entypo name="camera" size={16} color="#555" /> : <Ionicons name="md-analytics" size={18} color="#555" />}

            </CameraButton>

          </FormClicks>

        : null}

        <TouchableOpacity
          activeOpacity={0.8}
          style={{marginTop:15}}
          onPress={async() => {await logout(true)}}
        >
          <Text style={{}}>Sign out</Text>
        </TouchableOpacity>
      </View>
    </ScrollView>
  );
}

function Button({ children, onPress }) {
  return (
    <TouchableOpacity onPress={onPress} style={styles.button}>
      <Text style={styles.buttonText}>{children}</Text>
    </TouchableOpacity>
  );
}

const styles = StyleSheet.create({
  container: {
    minHeight:'100%',
    width:'100%',
    alignContent:'center',
    alignItems:'center',
    backgroundColor:'#fff'
  },
  header: {
    width:'100%',
    marginTop:20,
    fontSize:17,
    textAlign:'center',
  },
  aperture: {
    width: '85%',
    height: undefined,
    aspectRatio: width / (height - 150),
    marginLeft:'auto',
    marginRight:'auto',
    marginTop:20,
    marginBottom:20,
    backgroundColor:'#333'
  },
  buttonContainer: {
    width: '100%',
    marginTop: 0,
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal:'7.5%',
    paddingBottom:30,
    flex:1,
  },
  log: {
    fontSize:14,
    color:'#E80000',
    backgroundColor:'rgba(244, 148, 143, 0.12)',
    textAlign:'center',
    lineHeight:26,
    padding:20,
    borderRadius:7,
    marginVertical: 5
  },
  previewContainer: {
    width: '85%',
    height: undefined,
    aspectRatio: width / (height - 150),
    marginLeft:'auto',
    marginRight:'auto',
    marginTop:20,
    marginBottom:20,
    borderColor: '#eeee',
    borderWidth: 3,
    padding: 5,
    alignItems: 'center',
    justifyContent: 'center',
  },
  preview: {
    width: 200,
  },
  button: {
    backgroundColor: '#2d9fff',
    margin: 5,
    marginHorizontal: 20,
    borderRadius: 5,
    padding: 10,
    zIndex: 1000,
    alignItems: 'center',
  },
  buttonText: { color: 'white', fontSize: 20 },
});

How do I resolve this issue; as this happen on all app I installed the apk?


问:
Trying to Display Pandas DataFrame in Django HTML Output
I am currently trying to display a dataframe in HTML output with Django. Currently I have designed a view that takes in a couple csv files, runs some functions on them and then outputs a results dataframe. I am now trying to get this results dataframe to be on my html output.

views.py:

results_html = results.to_html(index=False)
return render(request, 'home.html', {'results_html': results_html})
```
<p><strong>home.html:</strong></p>
<pre class="lang-html prettyprint-override"><code><html>
  <body>
      <table>{{results_html|safe}}</table>
   </body>
</html>
</code>```

My home.html is in the templates folder within my overall app folder. I am trying to get this table to be displayed after clicking a button and also allow the ability to add design to the table to make it more visually appealing.

I have been researching on this site and other and tried their solutions and the table still doesn't output.

Body:
I am currently trying to display a dataframe in HTML output with Django. Currently I have designed a view that takes in a couple csv files, runs some functions on them and then outputs a results dataframe. I am now trying to get this results dataframe to be on my html output.

views.py:

results_html = results.to_html(index=False)
return render(request, 'home.html', {'results_html': results_html})

home.html:

{{results_html|safe}}

My home.html is in the templates folder within my overall app folder. I am trying to get this table to be displayed after clicking a button and also allow the ability to add design to the table to make it more visually appealing.

I have been researching on this site and other and tried their solutions and the table still doesn't output.


问:
Renaming a file that has a URL type encoding in it in Python
I created a program that deletes a part of a file's name to a certain string, and it works for many files but when it runs to a file named "%D0%A0%D1%87%2057%2F23-preview-.pdf-preview.pdf" it stops working due to an error.
The error is:
Traceback (most recent call last): File "C:\Users\Bratislav\Desktop\rename.py", line 34, in <module> fi.rename(f"{path}{untilTheString((requests.utils.unquote(entry.name)), theestring)}.{getExtension(entry.name)}") File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2544.0_x64__qbz5n2kfra8p0\lib\pathlib.py", line 1234, in rename self._accessor.rename(self, target) FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:\\Users\\SomeUser\\Desktop\\Folder\\%D0%A0%D1%87%2057%2F23-preview-.pdf-preview.pdf' -> 'C:/Users/SomeUser/Desktop/Folder/Рч 57/23.pdf'

My code is:

import requests, os, time, pathlib

directories = input("directories: ").split()
theestring = input("the string: ")

def getExtension(x):
        x = x[::-1]
        extension = ""
        for c in x:
                if c == ".":
                        return extension[::-1]
                extension += c

def untilTheString(x, theString):
        until = ""
        if len(theString) > len(x):
                return x
        for c in range((len(x) - len(theString) + 1)):
                if x[c:(c+len(theString))] != theString:
                        until = until + x[c]
                        continue
                return until
        return until

for e in directories:
        path = os.getcwd().replace("\\", "/") + "/" + e
        with os.scandir(e) as entries:
                for entry in entries:
                        if entry.is_file():
                                print(f"{entry.name}\n{untilTheString((requests.utils.unquote(entry.name)), theestring)}.{getExtension(entry.name)}")
                                fi = pathlib.Path(path + entry.name)
                                fi.rename(f"{path}{untilTheString((requests.utils.unquote(entry.name)), theestring)}.{getExtension(entry.name)}")
                                time.sleep(0.5)
```

Can someone help?

I tried running it on both CMD and Powershell, nothing changed.
I tried to do the renaming with os.rename function, nothing changed.

Body:
I created a program that deletes a part of a file's name to a certain string, and it works for many files but when it runs to a file named "%D0%A0%D1%87%2057%2F23-preview-.pdf-preview.pdf" it stops working due to an error.
The error is:
Traceback (most recent call last): File "C:\Users\Bratislav\Desktop\rename.py", line 34, in <module> fi.rename(f"{path}{untilTheString((requests.utils.unquote(entry.name)), theestring)}.{getExtension(entry.name)}") File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2544.0_x64__qbz5n2kfra8p0\lib\pathlib.py", line 1234, in rename self._accessor.rename(self, target) FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:\\Users\\SomeUser\\Desktop\\Folder\\%D0%A0%D1%87%2057%2F23-preview-.pdf-preview.pdf' -> 'C:/Users/SomeUser/Desktop/Folder/Рч 57/23.pdf'

My code is:

import requests, os, time, pathlib

directories = input("directories: ").split()
theestring = input("the string: ")

def getExtension(x):
        x = x[::-1]
        extension = ""
        for c in x:
                if c == ".":
                        return extension[::-1]
                extension += c

def untilTheString(x, theString):
        until = ""
        if len(theString) > len(x):
                return x
        for c in range((len(x) - len(theString) + 1)):
                if x[c:(c+len(theString))] != theString:
                        until = until + x[c]
                        continue
                return until
        return until

for e in directories:
        path = os.getcwd().replace("\\", "/") + "/" + e
        with os.scandir(e) as entries:
                for entry in entries:
                        if entry.is_file():
                                print(f"{entry.name}\n{untilTheString((requests.utils.unquote(entry.name)), theestring)}.{getExtension(entry.name)}")
                                fi = pathlib.Path(path + entry.name)
                                fi.rename(f"{path}{untilTheString((requests.utils.unquote(entry.name)), theestring)}.{getExtension(entry.name)}")
                                time.sleep(0.5)

Can someone help?

I tried running it on both CMD and Powershell, nothing changed.
I tried to do the renaming with os.rename function, nothing changed.


问:
Keycloak doesnt validate token on user_info endpoint in docker settings
My application based on microservices were working fine working on just localhost untill trying to set it up on docker-compose.
I've got issue on API Gateway side.  I've figured that authorization-uri has to be on localhost since it goes from outside of docker network.

token-uri and  user-info-uri are going from gateway to keycloak and need to call keycloak by its dns name. clientId and userId null in the error.

```<code>19:09:20,616 WARN  [org.keycloak.events] (default task-2) type=USER_INFO_REQUEST_ERROR, realmId=cinema, clientId=null, userId=null, ipAddress=172.21.0.9, error=invalid_token, auth_method=validate_access_token
</code>```
```<code>spring:
  application:
    name: Gateway
  config:
    import: optional:configserver:http://${ConfigService:configserver}:8888
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
      default-filters:
        - TokenRelay
  security:
    oauth2:
      client:
        provider:
          keycloak-spring-gateway-client:
            token-uri: http://${KEYCLOAK:localhost}:8080/auth/realms/${app.config.keycloak.realm}/protocol/openid-connect/token
            authorization-uri: http://localhost:28080/auth/realms/${app.config.keycloak.realm}/protocol/openid-connect/auth
            user-name-attribute: preferred_username
            user-info-uri: http://${KEYCLOAK:localhost}:8080/auth/realms/${app.config.keycloak.realm}/protocol/openid-connect/userinfo
            jwk-set-uri: http://${KEYCLOAK:localhost}:8080/auth/realms/${app.config.keycloak.realm}/protocol/openid-connect/certs
            user-info-authentication-method: header
        registration:

          keycloak-spring-gateway-client:
            provider: keycloak-spring-gateway-client
            client-id: gateway
            client-secret: ${GATEWAY_SECRET:PxY64IIOcSCUgZDWRdt2rHf8SL41xdX5}
            authorization-grant-type: authorization_code
            redirect-uri: http://localhost:8890/login/oauth2/code/keycloak
            scope: openid
      resourceserver:
        jwt:
          jwk-set-uri: ${app.config.keycloak.url}/realms/${app.config.keycloak.realm}/protocol/openid-connect/certs
</code>```

I've tried to change user-id to user_Id, but doesnt change anything.
Any ideas what could be wrong? Any help would be appreciated.

Body:
My application based on microservices were working fine working on just localhost untill trying to set it up on docker-compose.
I've got issue on API Gateway side.  I've figured that authorization-uri has to be on localhost since it goes from outside of docker network.

token-uri and  user-info-uri are going from gateway to keycloak and need to call keycloak by its dns name. clientId and userId null in the error.

19:09:20,616 WARN  [org.keycloak.events] (default task-2) type=USER_INFO_REQUEST_ERROR, realmId=cinema, clientId=null, userId=null, ipAddress=172.21.0.9, error=invalid_token, auth_method=validate_access_token

spring:
  application:
    name: Gateway
  config:
    import: optional:configserver:http://${ConfigService:configserver}:8888
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
      default-filters:
        - TokenRelay
  security:
    oauth2:
      client:
        provider:
          keycloak-spring-gateway-client:
            token-uri: http://${KEYCLOAK:localhost}:8080/auth/realms/${app.config.keycloak.realm}/protocol/openid-connect/token
            authorization-uri: http://localhost:28080/auth/realms/${app.config.keycloak.realm}/protocol/openid-connect/auth
            user-name-attribute: preferred_username
            user-info-uri: http://${KEYCLOAK:localhost}:8080/auth/realms/${app.config.keycloak.realm}/protocol/openid-connect/userinfo
            jwk-set-uri: http://${KEYCLOAK:localhost}:8080/auth/realms/${app.config.keycloak.realm}/protocol/openid-connect/certs
            user-info-authentication-method: header
        registration:

          keycloak-spring-gateway-client:
            provider: keycloak-spring-gateway-client
            client-id: gateway
            client-secret: ${GATEWAY_SECRET:PxY64IIOcSCUgZDWRdt2rHf8SL41xdX5}
            authorization-grant-type: authorization_code
            redirect-uri: http://localhost:8890/login/oauth2/code/keycloak
            scope: openid
      resourceserver:
        jwt:
          jwk-set-uri: ${app.config.keycloak.url}/realms/${app.config.keycloak.realm}/protocol/openid-connect/certs

I've tried to change user-id to user_Id, but doesnt change anything.
Any ideas what could be wrong? Any help would be appreciated.


问:
WebSocket using Springboot
I have cloned the following webSocket project https://github.com/thegeekyasian/WebSocket-SpringBoot and the server is up and running.  And postman client was able to connect to the server successfully. But when I rename the packages of this project and I try to connect to the server using postman client I have the following error. Could you please help?
Could not connect to ws://localhost:8080/webSocket
09:38:35
Error: Unexpected server response: 404
Handshake Details
Request URL: http://localhost:8080/webSocket
Request Method: GET
Status Code: 404
Request Headers
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: GmRXEBdLLrcJuIQH59nkuA==
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
Host: localhost:8080
Response Headers
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Wed, 11 Jan 2023 17:38:35 GMT

I tried to connect using ws://localhost:8080/webSocket

Title: WebSocket using Springboot


问:
error message [localhost:27017: [WinError 10061] No connection could be made because the target machine actively refused it, Timeout: 30s,
MongoDb atlas connetion issue.

Can anyone know how to resolve it?

error message [localhost:27017: [WinError 10061] No connection could
be made because the target machine actively refused it, Timeout: 30s,
Topology Description:

I checked MongoDB atlas connection, connection working fine, cluster running.


问:
Site page title on Categories pages and Product Page
I'm working with SAP Spartacus lib, version 3.6 and I need to implement a custom page title to Category Page and Product Page.

Actually, on Category Page the title is blank and on Pdp is returning PRODUCT NAME - Website name (I believe it is the default behavior).

I have looked back on Backoffice and my category already has a Description and I need to format my Product Page title to remove the Product name.

On SAP Spartacus Docs I've found this documentation, but for me do not explain how to implement this object on module.

```<code>{
 provide: PageMetaResolver,
 useExisting: YourCustomPageMetaResolver,
 multi: true,
}
</code>```

https://sap.github.io/spartacus-docs/html-tags/#customizing-meta-tags

Anyone can help me?
Thanks for your time.

Body:
I'm working with SAP Spartacus lib, version 3.6 and I need to implement a custom page title to Category Page and Product Page.

Actually, on Category Page the title is blank and on Pdp is returning PRODUCT NAME - Website name (I believe it is the default behavior).

I have looked back on Backoffice and my category already has a Description and I need to format my Product Page title to remove the Product name.

On SAP Spartacus Docs I've found this documentation, but for me do not explain how to implement this object on module.

{
 provide: PageMetaResolver,
 useExisting: YourCustomPageMetaResolver,
 multi: true,
}

https://sap.github.io/spartacus-docs/html-tags/#customizing-meta-tags

Anyone can help me?
Thanks for your time.


问:
Message from debugger: Terminated due to signal 6, Xcode, macbook m1, SFML
When I start my SFML app in Xcode on macbook m1 I have error "Message from debugger: Terminated due to signal 6" and this image enter image description here
Maybe someone knows how to fix this.
Help please

I searched the internet for a solution, but couldn't find a solution.