问:
discord.py Trying to store time in a db and check if 12 hours passed
I'm trying to check when 12 hours has passed since a user has voted and when I try to run the function through a while True loop, It doesn't run my bot.

def check_votes():
    now = datetime.datetime.now()
    voted_users = votedb.votes.find({"voted": "true"})
    for user in voted_users:
        vote_time = user.get("vote_time")
        elapsed_time = now - vote_time
        if elapsed_time > datetime.timedelta(hours=12):
            votedb.votes.update_one({"user_id": user.get("user_id")}, {"$set": {"voted": "false"}})

while not client.is_closed():
    while True:
        check_votes()
        time.sleep(3600)
```

This is making my bot not run and I'm trying to make it check when if it's been 12 hours since the vote_time which is set as "vote_time": datetime.datetime.now()

Body:
I'm trying to check when 12 hours has passed since a user has voted and when I try to run the function through a while True loop, It doesn't run my bot.

def check_votes():
    now = datetime.datetime.now()
    voted_users = votedb.votes.find({"voted": "true"})
    for user in voted_users:
        vote_time = user.get("vote_time")
        elapsed_time = now - vote_time
        if elapsed_time > datetime.timedelta(hours=12):
            votedb.votes.update_one({"user_id": user.get("user_id")}, {"$set": {"voted": "false"}})

while not client.is_closed():
    while True:
        check_votes()
        time.sleep(3600)

This is making my bot not run and I'm trying to make it check when if it's been 12 hours since the vote_time which is set as "vote_time": datetime.datetime.now()


来源: stackexchange

问:
Mock Ktor's http client with MockK
I want to mock requests with ktor's http client using MockK. The problem is all the methods related to making requests with the client are inline, so I cannot use coEvery on those methods. The next thing I tried was to go through the called methods until I found a method that wasn't inline and then mock that. After stepping through some functions, the HttpClient.request() function instantiates an HttpStatement and then calls execute() on it.

public suspend inline fun HttpClient.request(
    builder: HttpRequestBuilder = HttpRequestBuilder()
): HttpResponse = HttpStatement(builder, this).execute()
```
<p>If I can mock the constructor and <code>.execute()</code> functions, I can intercept the call and return my canned response. I can then check that the builder's params are correct inside of a <code>verify</code> function.</p>
<pre class="lang-kotlin prettyprint-override"><code>mockkConstructor(HttpStatement::class)
coEvery { anyConstructed<HttpStatement>().execute() } returns mockk {
    coEvery { status } returns HttpStatusCode.OK
    coEvery { body<RefreshToken>() } returns RefreshToken()
}
</code>```

This code takes care of intercepting the execute call. The next step would be to verify the constructor params of HttpStatement. This code to verify execute was called works:

coVerify { anyConstructed<HttpStatement>().execute() }
```
<p>Next thing is to verify the constructor params. This pull request in the MockK repo describes how to verify constructors:</p>
<pre class="lang-kotlin prettyprint-override"><code>coVerify { constructedWith<HttpStatement>(/* Matchers here */).execute() }
</code>```

Note that I have to add the .execute() or else MockK tells me I'm not verifying anything.

```<code>Missing calls inside verify { ... } block.
io.mockk.MockKException: Missing calls inside verify { ... } block.
    at app//io.mockk.impl.recording.states.VerifyingState.checkMissingCalls(VerifyingState.kt:52)
    at app//io.mockk.impl.recording.states.VerifyingState.recordingDone(VerifyingState.kt:21)
    ...
</code>```

Ok, so just add in the matchers. However, no combination of matchers I try works. I've tried doing a bunch of constant matchers for type Any (which should match anything right?)

coVerify { constructedWith<HttpStatement>(ConstantMatcher<Any>(true))}
```
<p>I've tried a matcher for <code>HttpRequestBuilder</code> and <code>HttpClient</code></p>
<pre class="lang-kotlin prettyprint-override"><code>coVerify {
    constructedWith<HttpStatement>(
        ConstantMatcher<HttpRequestBuilder>(true),
        ConstantMatcher<HttpClient>(true)
    ).execute()
}
</code>```

And a whole slew of others. Each time, I get this error:

```<code>Verification failed: call 1 of 1: HttpStatement(mockkConstructor<HttpStatement>(any(), any())).execute(any())) was not called
java.lang.AssertionError: Verification failed: call 1 of 1: HttpStatement(mockkConstructor<HttpStatement>(any(), any())).execute(any())) was not called
    at io.mockk.impl.recording.states.VerifyingState.failIfNotPassed(VerifyingState.kt:63)
    at io.mockk.impl.recording.states.VerifyingState.recordingDone(VerifyingState.kt:42)
    ...
</code>```

Next thing I figured I could try would be to use an answers block earlier on in order to print out the types of the parameters being passed in case I was wrong, but that also runs into the "nothing being done in every block" error.

coEvery { anyConstructed<HttpStatement>() } answers {
    args.filterNotNull().map { it::class.qualifiedName }.forEach(::println)
    mockk {
        coEvery { execute().status } returns HttpStatusCode.OK
        coEvery { execute().body<RefreshToken>() } returns RefreshToken(
            accessToken = accessToken,
            expiresIn = expiresIn,
        )
    }
}
```

Is there a solution to mocking the http client? Do I have to mock something even more internal? Or do I just have to stick to using the ktor MockEngine?

ContentLicense: CC BY-SA 4.0

Title: Mock Ktor's http client with MockK

Body:
I want to mock requests with ktor's http client using MockK. The problem is all the methods related to making requests with the client are inline, so I cannot use coEvery on those methods. The next thing I tried was to go through the called methods until I found a method that wasn't inline and then mock that. After stepping through some functions, the HttpClient.request() function instantiates an HttpStatement and then calls execute() on it.

public suspend inline fun HttpClient.request(
    builder: HttpRequestBuilder = HttpRequestBuilder()
): HttpResponse = HttpStatement(builder, this).execute()

If I can mock the constructor and .execute() functions, I can intercept the call and return my canned response. I can then check that the builder's params are correct inside of a verify function.

mockkConstructor(HttpStatement::class)
coEvery { anyConstructed<HttpStatement>().execute() } returns mockk {
    coEvery { status } returns HttpStatusCode.OK
    coEvery { body<RefreshToken>() } returns RefreshToken()
}

This code takes care of intercepting the execute call. The next step would be to verify the constructor params of HttpStatement. This code to verify execute was called works:

coVerify { anyConstructed<HttpStatement>().execute() }

Next thing is to verify the constructor params. This pull request in the MockK repo describes how to verify constructors:

coVerify { constructedWith<HttpStatement>(/* Matchers here */).execute() }

Note that I have to add the .execute() or else MockK tells me I'm not verifying anything.

Missing calls inside verify { ... } block.
io.mockk.MockKException: Missing calls inside verify { ... } block.
    at app//io.mockk.impl.recording.states.VerifyingState.checkMissingCalls(VerifyingState.kt:52)
    at app//io.mockk.impl.recording.states.VerifyingState.recordingDone(VerifyingState.kt:21)
    ...

Ok, so just add in the matchers. However, no combination of matchers I try works. I've tried doing a bunch of constant matchers for type Any (which should match anything right?)

coVerify { constructedWith<HttpStatement>(ConstantMatcher<Any>(true))}

I've tried a matcher for HttpRequestBuilder and HttpClient

coVerify {
    constructedWith<HttpStatement>(
        ConstantMatcher<HttpRequestBuilder>(true),
        ConstantMatcher<HttpClient>(true)
    ).execute()
}

And a whole slew of others. Each time, I get this error:

Verification failed: call 1 of 1: HttpStatement(mockkConstructor<HttpStatement>(any(), any())).execute(any())) was not called
java.lang.AssertionError: Verification failed: call 1 of 1: HttpStatement(mockkConstructor<HttpStatement>(any(), any())).execute(any())) was not called
    at io.mockk.impl.recording.states.VerifyingState.failIfNotPassed(VerifyingState.kt:63)
    at io.mockk.impl.recording.states.VerifyingState.recordingDone(VerifyingState.kt:42)
    ...

Next thing I figured I could try would be to use an answers block earlier on in order to print out the types of the parameters being passed in case I was wrong, but that also runs into the "nothing being done in every block" error.

coEvery { anyConstructed<HttpStatement>() } answers {
    args.filterNotNull().map { it::class.qualifiedName }.forEach(::println)
    mockk {
        coEvery { execute().status } returns HttpStatusCode.OK
        coEvery { execute().body<RefreshToken>() } returns RefreshToken(
            accessToken = accessToken,
            expiresIn = expiresIn,
        )
    }
}

Is there a solution to mocking the http client? Do I have to mock something even more internal? Or do I just have to stick to using the ktor MockEngine?


问:
Compiling lua for arm: dlfcn.h missing
I am trying to compile lua for an arm processor. I adapted the lua makefile to make it use arm-none-eabi-gcc. I dont think the details of lua are relevant, but my flags are visible in the following error message. When I try to compile it I get the following error:

```<code>arm-none-eabi-gcc -O2 -Wall -Wextra -DLUA_COMPAT_5_2 -DLUA_USE_LINUX -mcpu=cortex-m4 -mfloat-abi=softfp -mfpu=fpv4-sp-d16 -gdwarf-2 -mthumb -g3   -c -o loadlib.o loadlib.c
loadlib.c:107:19: fatal error: dlfcn.h: No such file or directory
#include <dlfcn.h>
</code>```

Can someone help me how I fix this? I went through many different sites and installed lots of random packages, but I have no idea where I should get the file dlfcn.h from.
I installed gcc-arm-none-eabi using apt and also tried installing the latest version as stated in this question from askubuntu below. Nothing seems to work. I dont even have an idea where to look for a solution.

Title: Compiling lua for arm: dlfcn.h missing

Body:
I am trying to compile lua for an arm processor. I adapted the lua makefile to make it use arm-none-eabi-gcc. I dont think the details of lua are relevant, but my flags are visible in the following error message. When I try to compile it I get the following error:

arm-none-eabi-gcc -O2 -Wall -Wextra -DLUA_COMPAT_5_2 -DLUA_USE_LINUX -mcpu=cortex-m4 -mfloat-abi=softfp -mfpu=fpv4-sp-d16 -gdwarf-2 -mthumb -g3   -c -o loadlib.o loadlib.c
loadlib.c:107:19: fatal error: dlfcn.h: No such file or directory
#include <dlfcn.h>

Can someone help me how I fix this? I went through many different sites and installed lots of random packages, but I have no idea where I should get the file dlfcn.h from.
I installed gcc-arm-none-eabi using apt and also tried installing the latest version as stated in this question from askubuntu below. Nothing seems to work. I dont even have an idea where to look for a solution.


问:
How do I position an image / recording in cv2?
I am making a program that records the screen, but it will display the same recording in 4 different spots around one window. How do I set the position of the recording to a certain coordinate in the window?

The code:

```<code>import pyautogui
import cv2
import numpy as np

from win32api import GetSystemMetrics

width = GetSystemMetrics(0)
height = GetSystemMetrics(1)

resolution = (width, height)

fps = 60.0

cv2.namedWindow("Hologram", cv2.WINDOW_NORMAL)

cv2.resizeWindow("Hologram", 480, 270)

while True:
    img1 = pyautogui.screenshot()
    img2 = pyautogui.screenshot()
    img3 = pyautogui.screenshot()
    img4 = pyautogui.screenshot()

    frame1 = np.array(img1)
    frame2 = np.array(img2)
    frame3 = np.array(img3)
    frame4 = np.array(img4)

    frame1 = cv2.cvtColor(frame1, cv2.COLOR_BGR2RGB)
    frame2 = cv2.cvtColor(frame2, cv2.COLOR_BGR2RGB)
    frame3 = cv2.cvtColor(frame3, cv2.COLOR_BGR2RGB)
    frame4 = cv2.cvtColor(frame4, cv2.COLOR_BGR2RGB)

    cv2.imshow('Hologram', frame1)
    cv2.imshow('Hologram', frame2)

    cv2.imshow('Hologram', frame3)

    cv2.imshow('Hologram', frame4)

    cv2.waitKey(1)
</code>```

Right now, it just displays all 4 recordings in the same spot, stacked on top of each other. I want all the live recordings to be in different spots around the window.

Body:
I am making a program that records the screen, but it will display the same recording in 4 different spots around one window. How do I set the position of the recording to a certain coordinate in the window?

The code:

import pyautogui
import cv2
import numpy as np

from win32api import GetSystemMetrics

width = GetSystemMetrics(0)
height = GetSystemMetrics(1)

resolution = (width, height)

fps = 60.0

cv2.namedWindow("Hologram", cv2.WINDOW_NORMAL)

cv2.resizeWindow("Hologram", 480, 270)

while True:
    img1 = pyautogui.screenshot()
    img2 = pyautogui.screenshot()
    img3 = pyautogui.screenshot()
    img4 = pyautogui.screenshot()

    frame1 = np.array(img1)
    frame2 = np.array(img2)
    frame3 = np.array(img3)
    frame4 = np.array(img4)

    frame1 = cv2.cvtColor(frame1, cv2.COLOR_BGR2RGB)
    frame2 = cv2.cvtColor(frame2, cv2.COLOR_BGR2RGB)
    frame3 = cv2.cvtColor(frame3, cv2.COLOR_BGR2RGB)
    frame4 = cv2.cvtColor(frame4, cv2.COLOR_BGR2RGB)

    cv2.imshow('Hologram', frame1)
    cv2.imshow('Hologram', frame2)

    cv2.imshow('Hologram', frame3)

    cv2.imshow('Hologram', frame4)

    cv2.waitKey(1)

Right now, it just displays all 4 recordings in the same spot, stacked on top of each other. I want all the live recordings to be in different spots around the window.


问:
Conda environment.yml - automatically add environment and extensions to Jupyter
Whenever I install a sample environment.yml, say:

name: my_env
dependencies:
  - python
  - numpy
  - pip:
    - scipy
    - ipykernel
    - ipywidgets
```
<p>that I install by <code>conda env create -f environment.yml</code> I then always have to add it to the Jupyter "kernelspec":</p>
```python -m ipykernel install --user --name my_env --display-name "my_env"
```
<p>and enable extensions:</p>
```jupyter nbextension enable --py widgetsnbextension
```

It would be simpler to have these two steps part of the environment.yml to start off with. Is this possible?

Body:
Whenever I install a sample environment.yml, say:

name: my_env
dependencies:
  - python
  - numpy
  - pip:
    - scipy
    - ipykernel
    - ipywidgets

that I install by conda env create -f environment.yml I then always have to add it to the Jupyter "kernelspec":

python -m ipykernel install --user --name my_env --display-name "my_env"

and enable extensions:

jupyter nbextension enable --py widgetsnbextension

It would be simpler to have these two steps part of the environment.yml to start off with. Is this possible?


问:
After password reset, I can't log in with the new password in laravel breeze

```<code>MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
MAIL_USERNAME=myemail@gmail.com
MAIL_PASSWORD=myapppasword
MAIL_ENCRYPTION=TLS
MAIL_FROM_ADDRESS="myemail@gmail.com"
MAIL_FROM_NAME="${APP_NAME}"
</code>```

In Laravel breeze after the reset, I can't log in with the new password

Body:
MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
MAIL_USERNAME=myemail@gmail.com
MAIL_PASSWORD=myapppasword
MAIL_ENCRYPTION=TLS
MAIL_FROM_ADDRESS="myemail@gmail.com"
MAIL_FROM_NAME="${APP_NAME}"

In Laravel breeze after the reset, I can't log in with the new password


问:
How to Git the latest tag of a submodule & excluding tags that contain certain words on it
I have cloned recursively a repo from GitLab and then got the tags of the submodules by using the following command:

```<code>git submodule foreach git tag -l
</code>```

So as an example. I have the following two submodules (components), AccltrInterLckDet and AccltrInterLckSwt, listed along with all of its tags:

```<code>Entering 'components/AccltrInterLckDet'
01.01.20210702.001
01.02.202203.001
beagledaimler.02.202211.001
legendgold.02.202210.001
octanegold.02.202210.001
titanium.02.202210.001
titanium.02.202211.001
Entering 'components/AccltrInterLckSwt'
01.01.20210706.001
01.01.20210727.002
01.02.202203.001
beagledaimler.02.202211.001
legendgold.02.202210.001
legendgold.02.202210.002
legendsilver.02.202211.001
octaneblue.02.202211.001
octanegold.02.202210.001
octanegold.02.202210.002
octanegold.02.202210.003
titanium.02.202210.001
titanium.02.202211.001
</code>```

Here's my question, How can I:

Exclude all tags that contain the words "titanium" "legend" "beagle"

Get only the newest tag

Not sure if there's a way to add these two conditions in the original command.

Thanks a lot!

Body:
I have cloned recursively a repo from GitLab and then got the tags of the submodules by using the following command:

git submodule foreach git tag -l

So as an example. I have the following two submodules (components), AccltrInterLckDet and AccltrInterLckSwt, listed along with all of its tags:

Entering 'components/AccltrInterLckDet'
01.01.20210702.001
01.02.202203.001
beagledaimler.02.202211.001
legendgold.02.202210.001
octanegold.02.202210.001
titanium.02.202210.001
titanium.02.202211.001
Entering 'components/AccltrInterLckSwt'
01.01.20210706.001
01.01.20210727.002
01.02.202203.001
beagledaimler.02.202211.001
legendgold.02.202210.001
legendgold.02.202210.002
legendsilver.02.202211.001
octaneblue.02.202211.001
octanegold.02.202210.001
octanegold.02.202210.002
octanegold.02.202210.003
titanium.02.202210.001
titanium.02.202211.001

Here's my question, How can I:

Exclude all tags that contain the words "titanium" "legend" "beagle"

Get only the newest tag

Not sure if there's a way to add these two conditions in the original command.

Thanks a lot!


问:
phase plane analysis of lorenz equations
Im trying to plot the phase plane analysis of lorenz equations. For example the saddle,spiral,nodes.
This is my code

```<code>x = np.linspace(-40,40,100)
y = np.linspace(-60,50,100)
z = np.linspace(-100,100,100)

rho=28
beta=8/3
sigma=10

xx,yy = np.meshgrid(x,y)
yy,zz = np.meshgrid(y,z)
yy,zz = np.meshgrid(y,z)

uu = sigma*(yy - xx)
vv= rho*xx - yy - xx*zz
ww= xx*yy - beta*zz

fig = plt.figure(figsize=(15,5))

ax1 = fig.add_subplot(131)
ax1.streamplot(xx,yy,uu,vv)
ax1.set_xlabel('$x$')
ax1.set_ylabel('$y$')
ax1.set_title('phaseportrait using streamplot')
plt.show()

fig = plt.figure(figsize=(15,5))
ax3 = fig.add_subplot(133)
ax3.streamplot(yy,zz,uu,ww)
ax3.set_xlabel('$x$')
ax3.set_ylabel('$z$')
ax3.set_title('phaseportrait using streamplot')
plt.show()

fig = plt.figure(figsize=(15,5))
ax2 = fig.add_subplot(132)
ax2.streamplot(yy,zz,vv,ww)
ax2.set_xlabel('$z$')
ax2.set_ylabel('$y$')
ax2.set_title('phaseportrait using streamplot')
plt.show()

</code>```

I just keep getting errors

I tried quiverplot and streamplot, tried moving the variables around. im expecting a diagram with a saddle node and spiral but its not working

Body:
Im trying to plot the phase plane analysis of lorenz equations. For example the saddle,spiral,nodes.
This is my code

x = np.linspace(-40,40,100)
y = np.linspace(-60,50,100)
z = np.linspace(-100,100,100)

rho=28
beta=8/3
sigma=10

xx,yy = np.meshgrid(x,y)
yy,zz = np.meshgrid(y,z)
yy,zz = np.meshgrid(y,z)

uu = sigma*(yy - xx)
vv= rho*xx - yy - xx*zz
ww= xx*yy - beta*zz

fig = plt.figure(figsize=(15,5))

ax1 = fig.add_subplot(131)
ax1.streamplot(xx,yy,uu,vv)
ax1.set_xlabel('$x$')
ax1.set_ylabel('$y$')
ax1.set_title('phaseportrait using streamplot')
plt.show()

fig = plt.figure(figsize=(15,5))
ax3 = fig.add_subplot(133)
ax3.streamplot(yy,zz,uu,ww)
ax3.set_xlabel('$x$')
ax3.set_ylabel('$z$')
ax3.set_title('phaseportrait using streamplot')
plt.show()

fig = plt.figure(figsize=(15,5))
ax2 = fig.add_subplot(132)
ax2.streamplot(yy,zz,vv,ww)
ax2.set_xlabel('$z$')
ax2.set_ylabel('$y$')
ax2.set_title('phaseportrait using streamplot')
plt.show()

I just keep getting errors

I tried quiverplot and streamplot, tried moving the variables around. im expecting a diagram with a saddle node and spiral but its not working


问:
Access denied when trying to run django-admin startproject
I am new to django and I tried to create a project with django-admin startproject command. The tutorial I was referring to had no errors while going through this command but I get the following error. The tutorial and I are not doing it in any virtual environment. Though this error comes, the files and folder are created in the directory I am working in, how should I solve this error?

Traceback (most recent call last):
File "C:\\Users\\username\\AppData\\Local\\Programs\\Python\\Python39\\lib\\runpy.py", line 197, in _run_module_as_main
return run_code(code, main_globals, None,
File "C:\\Users\\username\\AppData\\Local\\Programs\\Python\\Python39\\lib\\runpy.py", line 87, in run_code
exec(code, run_globals)
File "C:\\Users\\username\\AppData\\Local\\Programs\\Python\\Python39\\Scripts\\django-admin.exe_main_.py", line 7, in \<module\>
File "C:\\Users\\username\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\django\\core\\management\__init_.py", line 446, in execute_from_command_line
utility.execute()
File "C:\\Users\\username\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\django\\core\\management\__init_.py", line 440, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\\Users\\username\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\django\\core\\management\\base.py", line 402, in run_from_argv
self.execute(\*args, \*\*cmd_options)
File "C:\\Users\\username\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\django\\core\\management\\base.py", line 448, in execute
output = self.handle(\*args, \*\*options)
File "C:\\Users\\username\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\django\\core\\management\\commands\\startproject.py", line 21, in handle    super().handle("project", project_name, target, \*\*options)
File "C:\\Users\\username\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\django\\core\\management\\templates.py", line 225, in handle
run_formatters(\[top_dir\])
File "C:\\Users\\username\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\django\\core\\management\\utils.py", line 165, in run_formatters
subprocess.run(
File "C:\\Users\\username\\AppData\\Local\\Programs\\Python\\Python39\\lib\\subprocess.py", line 501, in run
with Popen(\*popenargs, \*\*kwargs) as process:
File "C:\\Users\\username\\AppData\\Local\\Programs\\Python\\Python39\\lib\\subprocess.py", line 947, in __init__
self.\_execute_child(args, executable, preexec_fn, close_fds,
File "C:\\Users\\username\\AppData\\Local\\Programs\\Python\\Python39\\lib\\subprocess.py", line 1416, in \_execute_child
hp, ht, pid, tid = \_winapi.CreateProcess(executable, args,
PermissionError: \[WinError 5\] Access is denied
```


问:
How to send commands to visual studio from other apps?
Visual Studio used to use a communication method. Is this still available?

I tried to search internet.


问:
Can I use DTO as POST input parameter for OData entity creation with navigation property?
I am trying to build an ASP.NET Core OData (v4) web API, but I'm not so clear on some of the best practices. Specifically I am unsure about what kind of payload input to expect for the POST endpoint for an entity that requires a reference to another entity on creation. To clarify, let's say we have the following data models:

```<code>public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Company Company { get; set; }
}

public class Company
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<Employee> Employees { get; set; }
}
</code>```

Then we have a controller:

```<code>public class EmployeeController : ODataController
{
    // EF DbContext provided via DI
    private readonly ApplicationDbContext _context;

    // Constructor omitted

    // GET '/Employees'
    // Returns all employees in dataset
    [EnableQuery]
    public IQueryable<Employee> Get()
    {
        return _context.Employees;
    }

    // GET '/Employees(key)' or '/Employees/key'
    // Returns a specific employee
    [EnableQuery]
    public SingleResult<Employee> Get([FromODataUri] int key)
    {
        var employee = _context.Employees.Where(e => e.Id.Equals(key));
        return SingleResult.Create(employee);
    }

    // POST '/Employees'
    // Creates a new Employee entity
    public async Task<IActionResult> Post(Employee employee)
    {
        // This is wat trips me up
    }
}
</code>```

Now this is where I start to doubt

The OData specification mentions the payload for a POST entity creation should contain a valid entity. So for the creation of a new Employee entity linked to company with id 1, this becomes:

```<code>{
    "@odata.type": "MyApplication.Models.Employee",
    "Name": "John Doe",
    "Company": {
        "Id": 1
        ... // potentially even "Name" (???)
    }
}
</code>```

I can't get the model binding to properly work because of the nested object however. Usually I would just define a flattened DTO version of the entity with a 'CompanyId' field instead of the nested object, but the spec makes me think that isn't allowed.

TL;DR: Can I not use a DTO version of the entity as the input parameter's type? Do I have to use the actual entity type Employee?

Body:
I am trying to build an ASP.NET Core OData (v4) web API, but I'm not so clear on some of the best practices. Specifically I am unsure about what kind of payload input to expect for the POST endpoint for an entity that requires a reference to another entity on creation. To clarify, let's say we have the following data models:

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Company Company { get; set; }
}

public class Company
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<Employee> Employees { get; set; }
}

Then we have a controller:

public class EmployeeController : ODataController
{
    // EF DbContext provided via DI
    private readonly ApplicationDbContext _context;

    // Constructor omitted

    // GET '/Employees'
    // Returns all employees in dataset
    [EnableQuery]
    public IQueryable<Employee> Get()
    {
        return _context.Employees;
    }

    // GET '/Employees(key)' or '/Employees/key'
    // Returns a specific employee
    [EnableQuery]
    public SingleResult<Employee> Get([FromODataUri] int key)
    {
        var employee = _context.Employees.Where(e => e.Id.Equals(key));
        return SingleResult.Create(employee);
    }

    // POST '/Employees'
    // Creates a new Employee entity
    public async Task<IActionResult> Post(Employee employee)
    {
        // This is wat trips me up
    }
}

Now this is where I start to doubt

The OData specification mentions the payload for a POST entity creation should contain a valid entity. So for the creation of a new Employee entity linked to company with id 1, this becomes:

{
    "@odata.type": "MyApplication.Models.Employee",
    "Name": "John Doe",
    "Company": {
        "Id": 1
        ... // potentially even "Name" (???)
    }
}

I can't get the model binding to properly work because of the nested object however. Usually I would just define a flattened DTO version of the entity with a 'CompanyId' field instead of the nested object, but the spec makes me think that isn't allowed.

TL;DR: Can I not use a DTO version of the entity as the input parameter's type? Do I have to use the actual entity type Employee?


问:
py-spy Error: Failed to get process executable name. Check that the process is running
I was trying to run performance test by using command line: py-spy top -- python main.py, but got the following error:

Error: Failed to get process executable name. Check that the process is running.
Reason: A device attached to the system is not functioning. (os error 31)
Reason: A device attached to the system is not functioning. (os error 31)

The py-spy version i was using ispy_spy-0.3.14-py2. Python version is 310, and OS is Win 10.

How can i know what device affected this python performance test? How to fix this error?


问:
Redshift Spectrum to Delta Lake integration using manifest files (an issue in the partitioned table when updating a partition column)
I am working with Delta Table and Redshift Spectrum and I notice strange behaviour.

I follow this article to set up a Redshift Spectrum to Delta Lake integration using manifest files and query Delta tables: https://docs.delta.io/latest/redshift-spectrum-integration.html

Environment information

Delta Lake version: 1.0.1 (io.delta)

Spark version: 2.4.3

Scala version: 2.12.10

Describe the problem

In my use case, the delta table is partitioned by 3 columns (year, month and day). Delta table have also the "application_id" column used as the key for the insert/update operations.

```<code>
CREATE EXTERNAL TABLE yyyyy.xxxxxxxx (
application_id string,
general_status_startingoffer string,
general_status_offer string
)
PARTITIONED BY (year string, month string, day string)
ROW FORMAT SERDE 'org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe'
STORED AS INPUTFORMAT 'org.apache.hadoop.hive.ql.io.SymlinkTextInputFormat'
OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'
LOCATION 's3://xxxxxxx/v0/data/\_symlink_format_manifest/'
TBLPROPERTIES ('delta.compatibility.symlinkFormatManifest.enabled'='true');
</code>```

Furthermore, an external schema has been created in redshift for mirroring data of the last version of the delta table.

```<code>
create external schema yyyyy
from data catalog database 'yyyyy'
iam_role '${iam_role}';
</code>```

We are using Athena and Redshift Editor to query the records.

The issue seems linked to an old partition that was been deleted in the last version of the delta table. In particular, redshift raises an Error whether fetching Delta Lake manifest.

Steps to reproduce

Following the steps to replicate the error:

The first glue job run creates 1 record in the following partition: year=2022, month=10, day=5

Symlink manifest is generated for redshift

Data has been correctly written

Delta log shows a newly added partition (year=2022, month=10, day=05)

Query on Athena shows correct results:

Query on redshift shows correct results:

The second glue job run updates this record, changing 2 columns (general_status_offer and day)

Symlink manifest is re-generated for redshift

The redshift manifest seems to be correctly updated

Delta log shows a new added partition (year=2022, month=10, day=13) and a deleted partition (year=2022, month=10, day=05). Query on Athena shows correct results:

Query on redshift fails with the following error message:

```<code>
Caught exception in worker_thread loader thread for location=s3://xxxxxxx/v0/data/\_symlink_format_manifest/year=2022/month=10/day=05: error=DeltaManifest context=Error fetching Delta Lake manifest xxxxx/v0/data/\_symlink_format_manifest/year=2022/month=10/day=05/manifest Message: S3ServiceException:The specified key does not exist.,Status 404,Error NoSuchKey,Rid 8ZCB2E6TTZ7JMHFD,ExtRid vnD7YB7JAPkW/

</code>```

It can be resolved by adding a new symlink folder (year=2022, month=10, day=05) with an empty manifest file or running this statement on redshift:

```<code>
ALTER TABLE xxxx DROP PARTITION (year='2022', month='10', day='05');

</code>```

We need to automatize this step and it is not easy to recognize which partitions are deleted. Are there any properties that I can set to force the automatic resolution?
If not, this could be a good enhancement :)

Body:
I am working with Delta Table and Redshift Spectrum and I notice strange behaviour.

I follow this article to set up a Redshift Spectrum to Delta Lake integration using manifest files and query Delta tables: https://docs.delta.io/latest/redshift-spectrum-integration.html

Environment information

Delta Lake version: 1.0.1 (io.delta)

Spark version: 2.4.3

Scala version: 2.12.10

Describe the problem

In my use case, the delta table is partitioned by 3 columns (year, month and day). Delta table have also the "application_id" column used as the key for the insert/update operations.

CREATE EXTERNAL TABLE yyyyy.xxxxxxxx (
application_id string,
general_status_startingoffer string,
general_status_offer string
)
PARTITIONED BY (year string, month string, day string)
ROW FORMAT SERDE 'org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe'
STORED AS INPUTFORMAT 'org.apache.hadoop.hive.ql.io.SymlinkTextInputFormat'
OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'
LOCATION 's3://xxxxxxx/v0/data/\_symlink_format_manifest/'
TBLPROPERTIES ('delta.compatibility.symlinkFormatManifest.enabled'='true');

Furthermore, an external schema has been created in redshift for mirroring data of the last version of the delta table.

create external schema yyyyy
from data catalog database 'yyyyy'
iam_role '${iam_role}';

We are using Athena and Redshift Editor to query the records.

The issue seems linked to an old partition that was been deleted in the last version of the delta table. In particular, redshift raises an Error whether fetching Delta Lake manifest.

Steps to reproduce

Following the steps to replicate the error:

The first glue job run creates 1 record in the following partition: year=2022, month=10, day=5

Symlink manifest is generated for redshift

Data has been correctly written

Delta log shows a newly added partition (year=2022, month=10, day=05)

Query on Athena shows correct results:

Query on redshift shows correct results:

The second glue job run updates this record, changing 2 columns (general_status_offer and day)

Symlink manifest is re-generated for redshift

The redshift manifest seems to be correctly updated

Delta log shows a new added partition (year=2022, month=10, day=13) and a deleted partition (year=2022, month=10, day=05). Query on Athena shows correct results:

Query on redshift fails with the following error message:

Caught exception in worker_thread loader thread for location=s3://xxxxxxx/v0/data/\_symlink_format_manifest/year=2022/month=10/day=05: error=DeltaManifest context=Error fetching Delta Lake manifest xxxxx/v0/data/\_symlink_format_manifest/year=2022/month=10/day=05/manifest Message: S3ServiceException:The specified key does not exist.,Status 404,Error NoSuchKey,Rid 8ZCB2E6TTZ7JMHFD,ExtRid vnD7YB7JAPkW/

It can be resolved by adding a new symlink folder (year=2022, month=10, day=05) with an empty manifest file or running this statement on redshift:

ALTER TABLE xxxx DROP PARTITION (year='2022', month='10', day='05');

We need to automatize this step and it is not easy to recognize which partitions are deleted. Are there any properties that I can set to force the automatic resolution?
If not, this could be a good enhancement :)


问:
CloudFront Error: This XML file does not appear to have any style information associated with it - Im ussing Vue and Vite
i have a vue app in a S3 Bucket inside AWS, and with my github workflow i can do a npm run build to create dist folder and copy it into the S3 so with that i have the compiled folder ready to production, and i have a CloudFront configured with that S3 bucket and the index.html works well, see the image below:

That page works well and i have a router with the following directory: /home and in localhost the page works well:

But in the cloudfront url the page returns the following error:

¿How can i solve this?

 This is my github action to copy the contents inside the S3 Bucket:


问:
Quarkus Kafka producer name
I have an emitter mapped to a kafka channel named "orders":

```<code>@ApplicationScoped
public class MessageBroker {

    @Inject
    @Channel("orders")
    @OnOverflow(DROP)
    Emitter<String> emitter;
</code>```

I could see the producer name printed in the console as "kafka-producer-orders":

```<code> [io.sma.rea.mes.kafka] (smallrye-kafka-producer-thread-0) SRMSG18258: Kafka producer kafka-producer-orders, connected to Kafka brokers 'OUTSIDE://localhost:32807', is configured to write records to 'orders'
</code>```

Where is this name coming from? And how do I change it?

Title: Quarkus Kafka producer name

Body:
I have an emitter mapped to a kafka channel named "orders":

@ApplicationScoped
public class MessageBroker {

    @Inject
    @Channel("orders")
    @OnOverflow(DROP)
    Emitter<String> emitter;

I could see the producer name printed in the console as "kafka-producer-orders":

 [io.sma.rea.mes.kafka] (smallrye-kafka-producer-thread-0) SRMSG18258: Kafka producer kafka-producer-orders, connected to Kafka brokers 'OUTSIDE://localhost:32807', is configured to write records to 'orders'

Where is this name coming from? And how do I change it?


问:
Nodejs path module and multer file filter
So I'm using multer and created logic for an image file filter but I got stuck because of this one weird hiccup:

const upload = multer({
  storage,
  fileFilter: (req, file, done) => {
    let ext = path.extname(file.originalname);
    if (ext !== ".jpg" || ext !== ".jpeg" || ext !== ".png") {
      done(new Error("File type is not supported"), false);
      return;
    }
    done(null, true);
  },
});```
</div>
</div>
</p>
<p>Why doesnt the code above work? It seems to only work when I switch the || for a &&, like this:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>const upload = multer({
  storage,
  fileFilter: (req, file, done) => {
    let ext = path.extname(file.originalname);
    if (ext !== ".jpg" && ext !== ".jpeg" && ext !== ".png") {
      done(new Error("File type is not supported"), false);
      return;
    }
    done(null, true);
  },
});</code>```

but I can't seem to understand why that's the case, I feel like || should completely work.

Body:
So I'm using multer and created logic for an image file filter but I got stuck because of this one weird hiccup:

const upload = multer({
  storage,
  fileFilter: (req, file, done) => {
    let ext = path.extname(file.originalname);
    if (ext !== ".jpg" || ext !== ".jpeg" || ext !== ".png") {
      done(new Error("File type is not supported"), false);
      return;
    }
    done(null, true);
  },
});

Why doesnt the code above work? It seems to only work when I switch the || for a &&, like this:

const upload = multer({
  storage,
  fileFilter: (req, file, done) => {
    let ext = path.extname(file.originalname);
    if (ext !== ".jpg" && ext !== ".jpeg" && ext !== ".png") {
      done(new Error("File type is not supported"), false);
      return;
    }
    done(null, true);
  },
});

but I can't seem to understand why that's the case, I feel like || should completely work.


问:
Build issue while using library youtube_player_iframe
I have used the plugin youtube_player_iframe: ^3.1.0, but getting below issue :

```<code>ERROR:/Users/hrishikeshrajwade/StudioProjects/my_flutter/my_app/build/webview_pro_android/.transforms/ac0b0f6ffcb9c5566c0134ec2e086d19/transformed/debug/io/flutter/plugins/webviewflutter/BuildConfig.dex: D8: Type io.flutter.plugins.webviewflutter.BuildConfig is defined multiple times: /Users/hrishikeshrajwade/StudioProjects/my_flutter/my_app/build/webview_pro_android/.transforms/ac0b0f6ffcb9c5566c0134ec2e086d19/transformed/debug/io/flutter/plugins/webviewflutter/BuildConfig.dex, /Users/hrishikeshrajwade/StudioProjects/my_flutter/my_app/build/webview_flutter_android/.transforms/671530a4417ab2d8d0097c4e5e2836a9/transformed/debug/io/flutter/plugins/webviewflutter/BuildConfig.dex
com.android.builder.dexing.DexArchiveMergerException: Error while merging dex archives:
Learn how to resolve the issue at https://developer.android.com/studio/build/dependencies#duplicate_classes.
Type io.flutter.plugins.webviewflutter.BuildConfig is defined multiple times: /Users/hrishikeshrajwade/StudioProjects/my_flutter/my_app/build/webview_pro_android/.transforms/ac0b0f6ffcb9c5566c0134ec2e086d19/transformed/debug/io/flutter/plugins/webviewflutter/BuildConfig.dex, /Users/hrishikeshrajwade/StudioProjects/my_flutter/my_app/build/webview_flutter_android/.transforms/671530a4417ab2d8d0097c4e5e2836a9/transformed/debug/io/flutter/plugins/webviewflutter/BuildConfig.dex

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:mergeLibDexDebug'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.DexMergingTaskDelegate
   > There was a failure while executing work items
      > A failure occurred while executing com.android.build.gradle.internal.tasks.DexMergingWorkAction
         > com.android.builder.dexing.DexArchiveMergerException: Error while merging dex archives:
           Learn how to resolve the issue at https://developer.android.com/studio/build/dependencies#duplicate_classes.
           Type io.flutter.plugins.webviewflutter.BuildConfig is defined multiple times: /Users/hrishikeshrajwade/StudioProjects/my_flutter/my_app/build/webview_pro_android/.transforms/ac0b0f6ffcb9c5566c0134ec2e086d19/transformed/debug/io/flutter/plugins/webviewflutter/BuildConfig.dex, /Users/hrishikeshrajwade/StudioProjects/my_flutter/my_app/build/webview_flutter_android/.transforms/671530a4417ab2d8d0097c4e5e2836a9/transformed/debug/io/flutter/plugins/webviewflutter/BuildConfig.dex

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 23s
[!] App requires Multidex support
    Multidex support is required for your android app to build since the number of methods has exceeded 64k. See https://docs.flutter.dev/deployment/android#enabling-multidex-support for more information. You may pass the --no-multidex flag to skip Flutter's multidex support to use a manual solution.

    Your `android/app/src/main/AndroidManifest.xml` does not contain `android:name="${applicationName}"` under the `application` element. This may be due to creating your project with an old version of Flutter. Add the `android:name="${applicationName}"` attribute to your AndroidManifest.xml to enable Flutter's multidex support:

        <manifest xmlns:android="http://schemas.android.com/apk/res/android"
          ...
          <application
            ...
            android:name="${applicationName}"
            ...>

    You may also roll your own multidex support by following the guide at: https://developer.android.com/studio/build/multidex

Exception: Gradle task assembleDebug failed with exit code 1
</code>```

I tired adding webview_flutter in dependency_overrides in same package but didn't work.

Body:
I have used the plugin youtube_player_iframe: ^3.1.0, but getting below issue :

ERROR:/Users/hrishikeshrajwade/StudioProjects/my_flutter/my_app/build/webview_pro_android/.transforms/ac0b0f6ffcb9c5566c0134ec2e086d19/transformed/debug/io/flutter/plugins/webviewflutter/BuildConfig.dex: D8: Type io.flutter.plugins.webviewflutter.BuildConfig is defined multiple times: /Users/hrishikeshrajwade/StudioProjects/my_flutter/my_app/build/webview_pro_android/.transforms/ac0b0f6ffcb9c5566c0134ec2e086d19/transformed/debug/io/flutter/plugins/webviewflutter/BuildConfig.dex, /Users/hrishikeshrajwade/StudioProjects/my_flutter/my_app/build/webview_flutter_android/.transforms/671530a4417ab2d8d0097c4e5e2836a9/transformed/debug/io/flutter/plugins/webviewflutter/BuildConfig.dex
com.android.builder.dexing.DexArchiveMergerException: Error while merging dex archives:
Learn how to resolve the issue at https://developer.android.com/studio/build/dependencies#duplicate_classes.
Type io.flutter.plugins.webviewflutter.BuildConfig is defined multiple times: /Users/hrishikeshrajwade/StudioProjects/my_flutter/my_app/build/webview_pro_android/.transforms/ac0b0f6ffcb9c5566c0134ec2e086d19/transformed/debug/io/flutter/plugins/webviewflutter/BuildConfig.dex, /Users/hrishikeshrajwade/StudioProjects/my_flutter/my_app/build/webview_flutter_android/.transforms/671530a4417ab2d8d0097c4e5e2836a9/transformed/debug/io/flutter/plugins/webviewflutter/BuildConfig.dex

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:mergeLibDexDebug'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.DexMergingTaskDelegate
   > There was a failure while executing work items
      > A failure occurred while executing com.android.build.gradle.internal.tasks.DexMergingWorkAction
         > com.android.builder.dexing.DexArchiveMergerException: Error while merging dex archives:
           Learn how to resolve the issue at https://developer.android.com/studio/build/dependencies#duplicate_classes.
           Type io.flutter.plugins.webviewflutter.BuildConfig is defined multiple times: /Users/hrishikeshrajwade/StudioProjects/my_flutter/my_app/build/webview_pro_android/.transforms/ac0b0f6ffcb9c5566c0134ec2e086d19/transformed/debug/io/flutter/plugins/webviewflutter/BuildConfig.dex, /Users/hrishikeshrajwade/StudioProjects/my_flutter/my_app/build/webview_flutter_android/.transforms/671530a4417ab2d8d0097c4e5e2836a9/transformed/debug/io/flutter/plugins/webviewflutter/BuildConfig.dex

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 23s
[!] App requires Multidex support
    Multidex support is required for your android app to build since the number of methods has exceeded 64k. See https://docs.flutter.dev/deployment/android#enabling-multidex-support for more information. You may pass the --no-multidex flag to skip Flutter's multidex support to use a manual solution.

    Your `android/app/src/main/AndroidManifest.xml` does not contain `android:name="${applicationName}"` under the `application` element. This may be due to creating your project with an old version of Flutter. Add the `android:name="${applicationName}"` attribute to your AndroidManifest.xml to enable Flutter's multidex support:

        <manifest xmlns:android="http://schemas.android.com/apk/res/android"
          ...
          <application
            ...
            android:name="${applicationName}"
            ...>

    You may also roll your own multidex support by following the guide at: https://developer.android.com/studio/build/multidex

Exception: Gradle task assembleDebug failed with exit code 1

I tired adding webview_flutter in dependency_overrides in same package but didn't work.


问:
Libspeexjni JNI integration
Those are Java functions in question:

```<code>targetFunctionPtr1 is public static native long nInitSpxEncoder();

targetFunctionPtr is public static native long nEncodeBuffer(long j12, short[] sArr, byte[] bArr, long j13);
</code>```

Sample pseudo Java code

```<code> long nInitSpxEncoder = LibSpeex.nInitSpxEncoder();
 long nEncodeBuffer = LibSpeex.nEncodeBuffer(nInitSpxEncoder, sArr, bArr, 65536);
</code>```

called below via JNI

```<code>char b[16]={0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,0x00};

jinput = env->NewStringUTF(b);

jclass stringClass = env->FindClass("java/lang/String");
jmethodID getBytesMId = env->GetMethodID(stringClass, "getBytes", "()[B");

in1 = (jbyteArray)env->CallObjectMethod( jinput, getBytesMId);

jlong init;

init = targetFunctionPtr1(env, CallerObj1);

jshort outCArray[] = {100};
jshortArray    retval = env->NewShortArray(10000);  // allocate
env->SetShortArrayRegion(retval, 0 , 1, outCArray);

nenc =  targetFunctionPtr(env, CallerObj, init, retval, in1, 10);

</code>```

Don't get why above segfaults. It calls init, that works, but in second call nEncodeBuffer it segfaults. I see in debugger it loads byte array and shorts array, but cannot figure out why it does not return, just loops until segfault.

I mean I call it via JNI but I would expect targetFunctionPtr to return. It seems it loops somehow, until segmentation occurs.

This is sample implementation of the JNI in Java

```<code> long nInitSpxEncoder = LibSpeex.nInitSpxEncoder();
            if (nInitSpxEncoder != 0) {
                int nGetEncoderFrameSize = (int) LibSpeex.nGetEncoderFrameSize(nInitSpxEncoder);
                System.err.println(String.format("Frame size = %d", Integer.valueOf(nGetEncoderFrameSize)));
                short[] sArr = new short[nGetEncoderFrameSize];
                AudioRecord audioRecord2 = null;
                byte[] bArr3 = bArr2;
                long j12 = 0;
                while (j12 < this.f13733d) {
                    try {
                        synchronized (this) {
                            if (audioRecord2 != this.f13731b) {
                                Log.i("AudioPttRecorder", "source changed");
                            }
                            audioRecord = this.f13731b;
                        }
                        if (audioRecord == null || audioRecord.read(sArr, 0, nGetEncoderFrameSize) != nGetEncoderFrameSize) {
                            break;
                        }
                        if (this.f13730a != null) {
                            this.f13730a.a(j12, a(nGetEncoderFrameSize, sArr));
                        }
                        long j13 = j12;
                        int i12 = nGetEncoderFrameSize;
                        short[] sArr2 = sArr;
                        long nEncodeBuffer = LibSpeex.nEncodeBuffer(nInitSpxEncoder, sArr, bArr, 65536);
                        if (nEncodeBuffer >= 0) {
                            Log.d("AudioPttRecorder", String.format("Write packet len=%d", Long.valueOf(nEncodeBuffer)));
                            bArr3[0] = (byte) (255 & nEncodeBuffer);
                            bArr3[1] = (byte) (nEncodeBuffer >> 8);
                            byte[] bArr4 = bArr3;
                            bufferedOutputStream.write(bArr4, 0, 2);
                            bufferedOutputStream.write(bArr, 0, (int) nEncodeBuffer);
                            bArr3 = bArr4;
                            nGetEncoderFrameSize = i12;
                            sArr = sArr2;
                            j12 = j13 + 1;
                            audioRecord2 = audioRecord;
                        } else {
                            throw new RuntimeException("Something wrong with encoding Speex");
                        }
                    } finally {
                        LibSpeex.nDestroySpxEncoder(nInitSpxEncoder);
                        Log.i("AudioPttRecorder", "exited");
                    }
                }
                bufferedOutputStream.flush();
                Log.d("AudioPttRecorder", "finished");
                return;
            }
</code>```

My code using JNI directly does similar.

Any ideas what is wrong with the native code?

How should I call Libspx to encode a byte array in native code?

Title: Libspeexjni JNI integration

Body:
Those are Java functions in question:

targetFunctionPtr1 is public static native long nInitSpxEncoder();

targetFunctionPtr is public static native long nEncodeBuffer(long j12, short[] sArr, byte[] bArr, long j13);

Sample pseudo Java code

 long nInitSpxEncoder = LibSpeex.nInitSpxEncoder();
 long nEncodeBuffer = LibSpeex.nEncodeBuffer(nInitSpxEncoder, sArr, bArr, 65536);

called below via JNI

char b[16]={0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,0x00};

jinput = env->NewStringUTF(b);

jclass stringClass = env->FindClass("java/lang/String");
jmethodID getBytesMId = env->GetMethodID(stringClass, "getBytes", "()[B");

in1 = (jbyteArray)env->CallObjectMethod( jinput, getBytesMId);

jlong init;

init = targetFunctionPtr1(env, CallerObj1);

jshort outCArray[] = {100};
jshortArray    retval = env->NewShortArray(10000);  // allocate
env->SetShortArrayRegion(retval, 0 , 1, outCArray);

nenc =  targetFunctionPtr(env, CallerObj, init, retval, in1, 10);

Don't get why above segfaults. It calls init, that works, but in second call nEncodeBuffer it segfaults. I see in debugger it loads byte array and shorts array, but cannot figure out why it does not return, just loops until segfault.

I mean I call it via JNI but I would expect targetFunctionPtr to return. It seems it loops somehow, until segmentation occurs.

This is sample implementation of the JNI in Java

 long nInitSpxEncoder = LibSpeex.nInitSpxEncoder();
            if (nInitSpxEncoder != 0) {
                int nGetEncoderFrameSize = (int) LibSpeex.nGetEncoderFrameSize(nInitSpxEncoder);
                System.err.println(String.format("Frame size = %d", Integer.valueOf(nGetEncoderFrameSize)));
                short[] sArr = new short[nGetEncoderFrameSize];
                AudioRecord audioRecord2 = null;
                byte[] bArr3 = bArr2;
                long j12 = 0;
                while (j12 < this.f13733d) {
                    try {
                        synchronized (this) {
                            if (audioRecord2 != this.f13731b) {
                                Log.i("AudioPttRecorder", "source changed");
                            }
                            audioRecord = this.f13731b;
                        }
                        if (audioRecord == null || audioRecord.read(sArr, 0, nGetEncoderFrameSize) != nGetEncoderFrameSize) {
                            break;
                        }
                        if (this.f13730a != null) {
                            this.f13730a.a(j12, a(nGetEncoderFrameSize, sArr));
                        }
                        long j13 = j12;
                        int i12 = nGetEncoderFrameSize;
                        short[] sArr2 = sArr;
                        long nEncodeBuffer = LibSpeex.nEncodeBuffer(nInitSpxEncoder, sArr, bArr, 65536);
                        if (nEncodeBuffer >= 0) {
                            Log.d("AudioPttRecorder", String.format("Write packet len=%d", Long.valueOf(nEncodeBuffer)));
                            bArr3[0] = (byte) (255 & nEncodeBuffer);
                            bArr3[1] = (byte) (nEncodeBuffer >> 8);
                            byte[] bArr4 = bArr3;
                            bufferedOutputStream.write(bArr4, 0, 2);
                            bufferedOutputStream.write(bArr, 0, (int) nEncodeBuffer);
                            bArr3 = bArr4;
                            nGetEncoderFrameSize = i12;
                            sArr = sArr2;
                            j12 = j13 + 1;
                            audioRecord2 = audioRecord;
                        } else {
                            throw new RuntimeException("Something wrong with encoding Speex");
                        }
                    } finally {
                        LibSpeex.nDestroySpxEncoder(nInitSpxEncoder);
                        Log.i("AudioPttRecorder", "exited");
                    }
                }
                bufferedOutputStream.flush();
                Log.d("AudioPttRecorder", "finished");
                return;
            }

My code using JNI directly does similar.

Any ideas what is wrong with the native code?

How should I call Libspx to encode a byte array in native code?


问:
Converting an np.unint8 to a GeoJSON file that can be imported to QuPath
I'm trying to convert the tissue "masks" created in one program (basically regions of tissue annotated on a tissue slide) and I wanted to import them into a program known as QuPath.

The "mask" files are essentially a series of shapes stored as np.unint8 arrays, each value being a pixel, where a positive value corresponds to the presence of tissue and a 0 corresponds to no tissue being present. As an example, this mask:

```<code>[[ 0, 0, 0, 0 ],

[ 0, 1, 1, 0 ],

[ 0, 1, 1, 0 ],

[ 0, 0, 0, 0 ]]
</code>```

would correspond to a 4x4 square.

The arrays are all in a larger H5 file along with associated metadata.

The program I want to import them into (QuPath) only accepts annotations in a GeoJSON format. Is there an existing method to convert pixel-by-pixel arrays into a GeoJSON format or will this have to be a novel method?

Here's the code I have to extract the arrays from the H5 file.

```<code># open and load file
asset_directory = 'D:\pathai_masks'
file_name = os.path.join(asset_directory, "path5_mask.h5")
h5_file = h5py.File(file_name, 'r')

# access attributes like a regular dictionary
# ex. access'wsi_masks'
wsi_masks = h5_file['wsi_masks']

# Load the JSON from the H5 file:
necrosis_dataset = h5_file["wsi_masks"]["predicted_region_mask_l1_5"]

# Encodes as a numpy.ndarray of uint8
necrosis_numpy_array = necrosis_dataset[:, :]
</code>```

This is what I have to convert the array directly to a GeoJSON file.

```<code>coordinates = []

for row in necrosis_numpy_array:
    coordinates.append(row.tolist())

geojson = {
    "type": "FeatureCollection",
    "features": [
        {
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": coordinates
            }
        }
    ]
}

json_data = json.dumps(geojson)
</code>```

And this is the format that QuPath accepts.

```<code>{
        "type": "Feature",
        "id": "PathDetectionObject",
        "geometry": {
            "type": "Polygon",
            "coordinates": [[[17738.72, 42238], [17737.94, 42240.13], [17738.39, 42242.34], [17737.21, 42244.28], [17737.19, 42246.54], [17739.74, 42250.23], [17743.86, 42248.63], [17743.7, 42246.37], [17745.05, 42242.08], [17748.38, 42239.13], [17747.76, 42238.25], [17738.72, 42238]]]
        },
        "properties": {
            "isLocked": false,
            "measurements": [],
            "classification": {
                "name": "Other",
                "colorRGB": -377282
            }
        }
    }
</code>```

Body:
I'm trying to convert the tissue "masks" created in one program (basically regions of tissue annotated on a tissue slide) and I wanted to import them into a program known as QuPath.

The "mask" files are essentially a series of shapes stored as np.unint8 arrays, each value being a pixel, where a positive value corresponds to the presence of tissue and a 0 corresponds to no tissue being present. As an example, this mask:

[[ 0, 0, 0, 0 ],

[ 0, 1, 1, 0 ],

[ 0, 1, 1, 0 ],

[ 0, 0, 0, 0 ]]

would correspond to a 4x4 square.

The arrays are all in a larger H5 file along with associated metadata.

The program I want to import them into (QuPath) only accepts annotations in a GeoJSON format. Is there an existing method to convert pixel-by-pixel arrays into a GeoJSON format or will this have to be a novel method?

Here's the code I have to extract the arrays from the H5 file.

# open and load file
asset_directory = 'D:\pathai_masks'
file_name = os.path.join(asset_directory, "path5_mask.h5")
h5_file = h5py.File(file_name, 'r')

# access attributes like a regular dictionary
# ex. access'wsi_masks'
wsi_masks = h5_file['wsi_masks']

# Load the JSON from the H5 file:
necrosis_dataset = h5_file["wsi_masks"]["predicted_region_mask_l1_5"]

# Encodes as a numpy.ndarray of uint8
necrosis_numpy_array = necrosis_dataset[:, :]

This is what I have to convert the array directly to a GeoJSON file.

coordinates = []

for row in necrosis_numpy_array:
    coordinates.append(row.tolist())

geojson = {
    "type": "FeatureCollection",
    "features": [
        {
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": coordinates
            }
        }
    ]
}

json_data = json.dumps(geojson)

And this is the format that QuPath accepts.

{
        "type": "Feature",
        "id": "PathDetectionObject",
        "geometry": {
            "type": "Polygon",
            "coordinates": [[[17738.72, 42238], [17737.94, 42240.13], [17738.39, 42242.34], [17737.21, 42244.28], [17737.19, 42246.54], [17739.74, 42250.23], [17743.86, 42248.63], [17743.7, 42246.37], [17745.05, 42242.08], [17748.38, 42239.13], [17747.76, 42238.25], [17738.72, 42238]]]
        },
        "properties": {
            "isLocked": false,
            "measurements": [],
            "classification": {
                "name": "Other",
                "colorRGB": -377282
            }
        }
    }


问:
SQL Server Migration- SSRS Reports don't match old server
I am looking for some direction on how to solve this SSRS problem.  Basically, I am migrating a 2012 sql server to a 2016 server.  I am on the last leg which was to ensure the SSRS reports being sent out match the old prod reports.

Two of the three reports being sent out are inaccurate.  One report shows up completely missing all numerical data, aside from the layout of the report.  The second report has all the data in the correct locations, however it is doubling the data in one of its 3 columns. They are connected to an internal data source.

I transferred these reports by downloading (rdl) them from the Old Prod SSRS and simply uploading them to the new Prod SSRS. I have tried tinkering with the report builder/visual studio but I'm not sure what to look for.

Can you please point me in the right direction of where to look or if there is an easier way to migrate said reports?


问:
Is it possible to manage sessions duration with IdentityPlatform/FirebaseAuth custom tokens?
I'm working on a project that has the following requirement: Sessions should never last more than 90 days.

I'm also using Firestore, and by extension to authenticate users, Firebase Auth. I want to give access to Firestore to my android and ios clients, for 90 days maximum. After that duration the session should automatically expire.

I initially thought custom tokens were the solution, because I thought they were just a different term for ID tokens. But in reality they can be used to get a refresh token that never expires.

I therefore thought about managing the refresh tokens myself, by:

issuing my own refresh tokens

verifying their validity

creating a new custom token

exchange the custom token with an id token and refresh token on the back end

only return the ID token to the client

the client would give it to firestore.

I don't mind managing expiration and renewing the id token myself on the my back end.

Now my problem is that when I look at the official SDKs for firestore on Android and SDKs, none seem to allow for just attaching an id token to requests?

Is there a solution to my issue? Or maybe even a better approach?
Thanks!


问:
How do I convert Model.Dog to System.Threading.Tasks.Task<Model.Dog> in Xunit testing?
I have this xunit method that tests the SET method in my dbAccessor class. This simply posts data to a database. I created a mock object of the dbAccessor and am trying to Setup the object so that it expects to return a mock Dog Object instead of null. This is what I have below.

```<code>[Fact]
public async Task TestDB_Accessor()
{
    var dbAccessorMock = CreateMock<IDbAccessor>();
    var test = CreateMock<Dog>().Object;

    // Error here. It says cannot convert Models.Dog to
    // System.Threading.Tasks.Task<Models.Dog>
    dbAccessorMock.Setup(x => x.PostItem(test)).Returns(test);

    await dbAccessorMock.PostItem(CreateMock<Dog>().Object);

    // Verification
    dbAccessorMock.Verify(x => x.PostItem(It.IsAny<Dog>()));
}
</code>```

Does anyone know the proper way to Setup this dbAccessorMock object so that it returns a Mock of Dog?

Body:
I have this xunit method that tests the SET method in my dbAccessor class. This simply posts data to a database. I created a mock object of the dbAccessor and am trying to Setup the object so that it expects to return a mock Dog Object instead of null. This is what I have below.

[Fact]
public async Task TestDB_Accessor()
{
    var dbAccessorMock = CreateMock<IDbAccessor>();
    var test = CreateMock<Dog>().Object;

    // Error here. It says cannot convert Models.Dog to
    // System.Threading.Tasks.Task<Models.Dog>
    dbAccessorMock.Setup(x => x.PostItem(test)).Returns(test);

    await dbAccessorMock.PostItem(CreateMock<Dog>().Object);

    // Verification
    dbAccessorMock.Verify(x => x.PostItem(It.IsAny<Dog>()));
}

Does anyone know the proper way to Setup this dbAccessorMock object so that it returns a Mock of Dog?


问:
MySQL Federated Table. No data returned to remote database
I can generate federated tables from an opencart database to my local database without issue. However, one particular table (option_descriptions) returns no data to its federated (local) table despite there being data in the source table.

I thought this might be a problem with constraints or indexes but have been able to exclude those issues. I expect the problem must be table definition related, but I have no idea what the specifics of that might be.

The problem can be recreated locally using the following script.
Just change the @connection_string variable to suit your database

Thanks in advance.

`

```<code>--
-- Federated Tables Problem
-- Results expected to show 11 for both tables / databases
-- I don't understand why table_2 returns no data on the federated table
--
-- ------------------   ------  ----------
-- TABLE NAME       SOURCE  FEDERATED
-- ------------------   ------  ----------
-- TABLE_1 Row Count    11  11
-- TABLE_2 Row Count    11  <<  0  >>
-- ------------------   ------  ----------

-- The following script generates the result above.

-- Modify this to suit ...
SET @connection_string = "mysql://root:trapdoor@localhost:3306";

-- Create a local database to contain a pair of tables as a source
--
DROP DATABASE IF EXISTS  `fed_test_source`;
CREATE DATABASE `fed_test_source`;
USE fed_test_source;

CREATE TABLE `TABLE_1` (
  `option_id` INT(11) NOT NULL AUTO_INCREMENT,
  `type` VARCHAR(32) NOT NULL,
  `sort_order` INT(3) NOT NULL,
  PRIMARY KEY (`option_id`)
) ENGINE=MYISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

INSERT INTO `TABLE_1` (`option_id`, `type`, `sort_order`)
VALUES('1','select','15')
,('2','select','30')
,('3','radio','10')
,('4','select','20')
,('5','select','-100')
,('6','select','100')
,('7','select','0')
,('8','select','45')
,('9','select','0')
,('10','select','0')
,('11','select','0');

CREATE TABLE `TABLE_2` (
  `option_id` INT(11) NOT NULL,
  `language_id` INT(11) NOT NULL,
  `name` VARCHAR(128) NOT NULL,
  PRIMARY KEY (`option_id`,`language_id`)
) ENGINE=MYISAM DEFAULT CHARSET=utf8;

INSERT INTO `TABLE_2` (`option_id`, `language_id`, `name`)
VALUES('1','1','Barrel Length')
,('2','1','Cast')
,('3','1','Colour')
,('4','1','Size')
,('5','1','Calibre')
,('6','1','Pitch')
,('7','1','Power Level')
,('8','1','Weight')
,('9','1','Capacity')
,('10','1','Length')
,('11','1','Type');

-- Now create a pair of federated tables linked to the tables created above

DROP DATABASE IF EXISTS  `fed_test`;
CREATE DATABASE `fed_test`;
USE fed_test;

DROP TABLE IF EXISTS `fed_TABLE_1`;
DROP TABLE IF EXISTS `fed_TABLE_2`;

-- Create federated table fed_TABLE_1;
SET @sqlstr = CONCAT("
CREATE TABLE `fed_TABLE_1` (
  `option_id` BIGINT(20) NOT NULL AUTO_INCREMENT, -- change
  `type` VARCHAR(32) NOT NULL,
  `sort_order` INT(3) NOT NULL,
  PRIMARY KEY (`option_id`)
) ENGINE=FEDERATED
AUTO_INCREMENT=1
DEFAULT CHARSET=utf8
CONNECTION='",
@connection_string,
"/fed_test_source/TABLE_1';");

        PREPARE stmt FROM @sqlstr;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;

-- Create federated table fed_TABLE_2;
SET @sqlstr = CONCAT("
CREATE TABLE `fed_TABLE_2` (
  `option_id` BIGINT(20) NOT NULL,
  `language_id` INT(11) NOT NULL,
  `name` VARCHAR(128) NOT NULL,
  PRIMARY KEY (`option_id`,`language_id`)
) ENGINE=MYISAM DEFAULT CHARSET=utf8
CONNECTION='",
@connection_string,
"/fed_test_source/TABLE_2';");

        PREPARE stmt FROM @sqlstr;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;

SELECT 'TABLE_1 Row Count' `name`, (SELECT COUNT(*) `row count` FROM `fed_test_source`.`TABLE_1`) `SOURCE`,(SELECT COUNT(*) `row count` FROM fed_test.`fed_TABLE_1`) `FEDERATED`
UNION
SELECT 'TABLE_2 Row Count' `name`, (SELECT COUNT(*) `row count` FROM `fed_test_source`.`TABLE_2`) `SOURCE`,(SELECT COUNT(*) `row count` FROM fed_test.`fed_TABLE_2`) `FEDERATED`;

</code>```

`

Based on the script provided, I would expect the row count for both tables, across remote and source databases, to be equivalent.

I am getting no data on the federated table for one of the sample tables generated in the script.

I have tried using different databases as SOURCE.

Body:
I can generate federated tables from an opencart database to my local database without issue. However, one particular table (option_descriptions) returns no data to its federated (local) table despite there being data in the source table.

I thought this might be a problem with constraints or indexes but have been able to exclude those issues. I expect the problem must be table definition related, but I have no idea what the specifics of that might be.

The problem can be recreated locally using the following script.
Just change the @connection_string variable to suit your database

Thanks in advance.

`

--
-- Federated Tables Problem
-- Results expected to show 11 for both tables / databases
-- I don't understand why table_2 returns no data on the federated table
--
-- ------------------   ------  ----------
-- TABLE NAME       SOURCE  FEDERATED
-- ------------------   ------  ----------
-- TABLE_1 Row Count    11  11
-- TABLE_2 Row Count    11  <<  0  >>
-- ------------------   ------  ----------

-- The following script generates the result above.

-- Modify this to suit ...
SET @connection_string = "mysql://root:trapdoor@localhost:3306";

-- Create a local database to contain a pair of tables as a source
--
DROP DATABASE IF EXISTS  `fed_test_source`;
CREATE DATABASE `fed_test_source`;
USE fed_test_source;

CREATE TABLE `TABLE_1` (
  `option_id` INT(11) NOT NULL AUTO_INCREMENT,
  `type` VARCHAR(32) NOT NULL,
  `sort_order` INT(3) NOT NULL,
  PRIMARY KEY (`option_id`)
) ENGINE=MYISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

INSERT INTO `TABLE_1` (`option_id`, `type`, `sort_order`)
VALUES('1','select','15')
,('2','select','30')
,('3','radio','10')
,('4','select','20')
,('5','select','-100')
,('6','select','100')
,('7','select','0')
,('8','select','45')
,('9','select','0')
,('10','select','0')
,('11','select','0');

CREATE TABLE `TABLE_2` (
  `option_id` INT(11) NOT NULL,
  `language_id` INT(11) NOT NULL,
  `name` VARCHAR(128) NOT NULL,
  PRIMARY KEY (`option_id`,`language_id`)
) ENGINE=MYISAM DEFAULT CHARSET=utf8;

INSERT INTO `TABLE_2` (`option_id`, `language_id`, `name`)
VALUES('1','1','Barrel Length')
,('2','1','Cast')
,('3','1','Colour')
,('4','1','Size')
,('5','1','Calibre')
,('6','1','Pitch')
,('7','1','Power Level')
,('8','1','Weight')
,('9','1','Capacity')
,('10','1','Length')
,('11','1','Type');

-- Now create a pair of federated tables linked to the tables created above

DROP DATABASE IF EXISTS  `fed_test`;
CREATE DATABASE `fed_test`;
USE fed_test;

DROP TABLE IF EXISTS `fed_TABLE_1`;
DROP TABLE IF EXISTS `fed_TABLE_2`;

-- Create federated table fed_TABLE_1;
SET @sqlstr = CONCAT("
CREATE TABLE `fed_TABLE_1` (
  `option_id` BIGINT(20) NOT NULL AUTO_INCREMENT, -- change
  `type` VARCHAR(32) NOT NULL,
  `sort_order` INT(3) NOT NULL,
  PRIMARY KEY (`option_id`)
) ENGINE=FEDERATED
AUTO_INCREMENT=1
DEFAULT CHARSET=utf8
CONNECTION='",
@connection_string,
"/fed_test_source/TABLE_1';");

        PREPARE stmt FROM @sqlstr;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;

-- Create federated table fed_TABLE_2;
SET @sqlstr = CONCAT("
CREATE TABLE `fed_TABLE_2` (
  `option_id` BIGINT(20) NOT NULL,
  `language_id` INT(11) NOT NULL,
  `name` VARCHAR(128) NOT NULL,
  PRIMARY KEY (`option_id`,`language_id`)
) ENGINE=MYISAM DEFAULT CHARSET=utf8
CONNECTION='",
@connection_string,
"/fed_test_source/TABLE_2';");

        PREPARE stmt FROM @sqlstr;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;

SELECT 'TABLE_1 Row Count' `name`, (SELECT COUNT(*) `row count` FROM `fed_test_source`.`TABLE_1`) `SOURCE`,(SELECT COUNT(*) `row count` FROM fed_test.`fed_TABLE_1`) `FEDERATED`
UNION
SELECT 'TABLE_2 Row Count' `name`, (SELECT COUNT(*) `row count` FROM `fed_test_source`.`TABLE_2`) `SOURCE`,(SELECT COUNT(*) `row count` FROM fed_test.`fed_TABLE_2`) `FEDERATED`;

`

Based on the script provided, I would expect the row count for both tables, across remote and source databases, to be equivalent.

I am getting no data on the federated table for one of the sample tables generated in the script.

I have tried using different databases as SOURCE.


问:
How do I get the values of memory adresses used by apps outside of python (on MacOS)
I'm trying to use python to read the value of a memory address that another program is using and I haven't been able to figure out how to. (I'm using macOS)

I've tried many ways but I think the closest I've gotten is this because the website actually shows it working for them, but when i do it in python it just crashes.

```<code>import ctypes

x = "0x7FA09AAE85A0"
a = ctypes.cast(x, ctypes.py_object).value

print(a)
</code>```

Body:
I'm trying to use python to read the value of a memory address that another program is using and I haven't been able to figure out how to. (I'm using macOS)

I've tried many ways but I think the closest I've gotten is this because the website actually shows it working for them, but when i do it in python it just crashes.

import ctypes

x = "0x7FA09AAE85A0"
a = ctypes.cast(x, ctypes.py_object).value

print(a)


问:
Does the Windows ABI allow me to change the stack pointer?
I know that the windows ABI have some restrictions about code generation for procedure's prologs & epilog, but I was wondering if it's fine by the OS to allocate a large heap storage and point the stack pointer to this location (and restore the RSP before the function returns)?
Basically, from what I understand windows threads have a hard limit of 4GB and I wonder if it's OK to increase the stack limit that way or if there's another way to do so?

I have read the information that MSDN has about the x64 stack usage here but I could not find any information about assigning new value to the stack register


问:
Creating a simple multiple users app in Django
So I've created 3 different users: admins, developers, and project managers. When I use the individual signup forms for each of these users and log out, it works, but then I when try to use the login form, it seems to me that it's acting like the signup form. Because when I input the same user details as the one I just created into the login form, it throws up the built-in error message, 'A user with that user name already exists' I'm not sure how to proceed from here.

Here's what I have so far.

models.py

```<code>class CustomUser(AbstractUser):
    ACCOUNT_TYPE_CHOICES = (
        ('admin', 'Admin'),
        ('developer', 'Developer'),
        ('project_manager', 'Project Manager')
    )
    account_type = models.CharField(max_length=20, choices=ACCOUNT_TYPE_CHOICES)
</code>```

login and signupviews

```<code>class LoginView(View):
    def get(self, request):
        # Render the login form
        form = LoginForm()
        return render(request, 'users/login.html', {'form': form})

    def post(self, request):
        # Get the form data from the request
        form = LoginForm(request.POST)

        # Validate the form data
        if form.is_valid():
            # Get the username and password from the form
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']

            # Authenticate the user
            user = authenticate(request, username=username, password=password)

            # If the user is authenticated, log them in and redirect to the homepage
            if user is not None:
                login(request, user)
                if user.account_type == 'admin':
                    return redirect('admin_home')
                elif user.account_type == 'developer':
                    return redirect('developer_home')
                elif user.account_type == 'project_manager':
                    return redirect('projectmanager_home')
                return redirect('home')

            # If the user is not authenticated, render the login form again with an error message
            else:
                form.add_error(None, 'Invalid username or password')
                return render(request, 'users/login.html', {'form': form})
        else:
            return render(request, 'users/login.html', {'form': form})

class LogoutView(View):
    def get(self, request):
        # Log out the user and redirect to the login page
        logout(request)
        return redirect('home')

class AdminSignUpView(CreateView):
    form_class = AdminSignUpForm
    template_name = 'users/admin_signup.html'
    success_url = '/admin_home/'

    def form_valid(self, form):
        # Create the user and log them in
        user = form.save()
        login(self.request, user)
        return redirect(self.success_url)

class DeveloperSignUpView(CreateView):
    form_class = DeveloperSignUpForm
    template_name = 'users/developer_signup.html'
    success_url = '/developer_home/'

    def form_valid(self, form):
        # Create the user and log them in
        user = form.save()
        login(self.request, user)
        return redirect(self.success_url)

class ProjectManagerSignUpView(CreateView):
    form_class = ProjectManagerSignUpForm
    template_name = 'users/projectmanager_signup.html'
    success_url = '/projectmanager_home/'

    def form_valid(self, form):
        # Create the user and log them in
        user = form.save()
        login(self.request, user)
        return redirect(self.success_url)

</code>```

forms.py

```<code>class AdminSignUpForm(forms.ModelForm):
    # Define the form fields for the admin sign-up form
    account_type = forms.CharField(max_length=20, widget=forms.HiddenInput(), initial='admin')
    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=30)
    email = forms.EmailField()
    username = forms.CharField(max_length=150)
    password = forms.CharField(max_length=128, widget=forms.PasswordInput())

    class Meta:
        model = CustomUser
        fields = ['first_name', 'last_name', 'email', 'username', 'password']

class DeveloperSignUpForm(forms.ModelForm):
    # Define the form fields for the developer sign-up form
    account_type = forms.CharField(max_length=20, widget=forms.HiddenInput(), initial='developer')
    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=30)
    email = forms.EmailField()
    username = forms.CharField(max_length=150)
    password = forms.CharField(max_length=128, widget=forms.PasswordInput())

    class Meta:
        model = CustomUser
        fields = ['first_name', 'last_name', 'email', 'username', 'password']

class ProjectManagerSignUpForm(forms.ModelForm):
    # Define the form fields for the admin sign-up form
    account_type = forms.CharField(max_length=20, widget=forms.HiddenInput(), initial='project_manager')
    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=30)
    email = forms.EmailField()
    username = forms.CharField(max_length=150)
    password = forms.CharField(max_length=128, widget=forms.PasswordInput())

    class Meta:
        model = CustomUser
        fields = ['first_name', 'last_name', 'email', 'username', 'password']

class LoginForm(forms.ModelForm):
    class Meta:
        model = CustomUser
        fields = ['username', 'password']
        widgets = {
            'password': forms.PasswordInput(),
        }
</code>```

login template

```<code>{% block content %}
    <h1>Login</h1>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Log in</button>
    </form>
    {% if form.errors %}
        <p>Your username and password didn't match. Please try again.</p>
    {% endif %}
{% endblock %}
</code>```

Let me know if you need any more information.

Body:
So I've created 3 different users: admins, developers, and project managers. When I use the individual signup forms for each of these users and log out, it works, but then I when try to use the login form, it seems to me that it's acting like the signup form. Because when I input the same user details as the one I just created into the login form, it throws up the built-in error message, 'A user with that user name already exists' I'm not sure how to proceed from here.

Here's what I have so far.

models.py

class CustomUser(AbstractUser):
    ACCOUNT_TYPE_CHOICES = (
        ('admin', 'Admin'),
        ('developer', 'Developer'),
        ('project_manager', 'Project Manager')
    )
    account_type = models.CharField(max_length=20, choices=ACCOUNT_TYPE_CHOICES)

login and signupviews

class LoginView(View):
    def get(self, request):
        # Render the login form
        form = LoginForm()
        return render(request, 'users/login.html', {'form': form})

    def post(self, request):
        # Get the form data from the request
        form = LoginForm(request.POST)

        # Validate the form data
        if form.is_valid():
            # Get the username and password from the form
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']

            # Authenticate the user
            user = authenticate(request, username=username, password=password)

            # If the user is authenticated, log them in and redirect to the homepage
            if user is not None:
                login(request, user)
                if user.account_type == 'admin':
                    return redirect('admin_home')
                elif user.account_type == 'developer':
                    return redirect('developer_home')
                elif user.account_type == 'project_manager':
                    return redirect('projectmanager_home')
                return redirect('home')

            # If the user is not authenticated, render the login form again with an error message
            else:
                form.add_error(None, 'Invalid username or password')
                return render(request, 'users/login.html', {'form': form})
        else:
            return render(request, 'users/login.html', {'form': form})

class LogoutView(View):
    def get(self, request):
        # Log out the user and redirect to the login page
        logout(request)
        return redirect('home')

class AdminSignUpView(CreateView):
    form_class = AdminSignUpForm
    template_name = 'users/admin_signup.html'
    success_url = '/admin_home/'

    def form_valid(self, form):
        # Create the user and log them in
        user = form.save()
        login(self.request, user)
        return redirect(self.success_url)

class DeveloperSignUpView(CreateView):
    form_class = DeveloperSignUpForm
    template_name = 'users/developer_signup.html'
    success_url = '/developer_home/'

    def form_valid(self, form):
        # Create the user and log them in
        user = form.save()
        login(self.request, user)
        return redirect(self.success_url)

class ProjectManagerSignUpView(CreateView):
    form_class = ProjectManagerSignUpForm
    template_name = 'users/projectmanager_signup.html'
    success_url = '/projectmanager_home/'

    def form_valid(self, form):
        # Create the user and log them in
        user = form.save()
        login(self.request, user)
        return redirect(self.success_url)

forms.py

class AdminSignUpForm(forms.ModelForm):
    # Define the form fields for the admin sign-up form
    account_type = forms.CharField(max_length=20, widget=forms.HiddenInput(), initial='admin')
    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=30)
    email = forms.EmailField()
    username = forms.CharField(max_length=150)
    password = forms.CharField(max_length=128, widget=forms.PasswordInput())

    class Meta:
        model = CustomUser
        fields = ['first_name', 'last_name', 'email', 'username', 'password']

class DeveloperSignUpForm(forms.ModelForm):
    # Define the form fields for the developer sign-up form
    account_type = forms.CharField(max_length=20, widget=forms.HiddenInput(), initial='developer')
    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=30)
    email = forms.EmailField()
    username = forms.CharField(max_length=150)
    password = forms.CharField(max_length=128, widget=forms.PasswordInput())

    class Meta:
        model = CustomUser
        fields = ['first_name', 'last_name', 'email', 'username', 'password']

class ProjectManagerSignUpForm(forms.ModelForm):
    # Define the form fields for the admin sign-up form
    account_type = forms.CharField(max_length=20, widget=forms.HiddenInput(), initial='project_manager')
    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=30)
    email = forms.EmailField()
    username = forms.CharField(max_length=150)
    password = forms.CharField(max_length=128, widget=forms.PasswordInput())

    class Meta:
        model = CustomUser
        fields = ['first_name', 'last_name', 'email', 'username', 'password']

class LoginForm(forms.ModelForm):
    class Meta:
        model = CustomUser
        fields = ['username', 'password']
        widgets = {
            'password': forms.PasswordInput(),
        }

login template

{% block content %}

Login

    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Log in</button>
    </form>
    {% if form.errors %}

Your username and password didn't match. Please try again.

    {% endif %}
{% endblock %}

Let me know if you need any more information.