喜你已久

文章 评论 浏览 31

喜你已久 2025-02-20 16:26:19

如果您查看自动生成的Fastapi Swagger(127.0.0.1:8000/docs),您会发现您必须使用Multipart-Form来上传。

要从Angular上传它,您必须按照以下示例使用FormData。

const chooseFromLibrary = () => {
  ImagePicker.openPicker({ 
    width: 300,
    height: 400,
    cropping: false,
  }).then(image => {
    console.log(image);
    hi(image);
  });
};

const hi = async image => {
  let uploadForm = new FormData();
  uploadForm.append("file", image);
  let response = await fetch(
    'https://receipt-ocr-heroku.herokuapp.com/receiptOcr',
    {
      method: 'POST',
      body: uploadForm,
    }
  );
  console.log(response);
  let result = await response.json();
  console.log(result);
};

If you look into the automatic generated FastAPI swagger (127.0.0.1:8000/docs), you'll see that you have to use multipart-form to upload this.

FastAPI Swagger

To upload this from Angular you will have to use FormData as per the example below.

const chooseFromLibrary = () => {
  ImagePicker.openPicker({ 
    width: 300,
    height: 400,
    cropping: false,
  }).then(image => {
    console.log(image);
    hi(image);
  });
};

const hi = async image => {
  let uploadForm = new FormData();
  uploadForm.append("file", image);
  let response = await fetch(
    'https://receipt-ocr-heroku.herokuapp.com/receiptOcr',
    {
      method: 'POST',
      body: uploadForm,
    }
  );
  console.log(response);
  let result = await response.json();
  console.log(result);
};

致电FastApi上传来自电话React本地的文件

喜你已久 2025-02-20 01:17:22

回应我在关于C ++ :我建议扔掉 scanf()离开,永远不要使用它,而是使用 fgets() sscanf()

这样做的原因是,至少在默认情况下,在类似于Unix的系统中,您的CLI程序运行的终端在您的程序看到它之前对用户输入进行了一些处理。它可以缓冲输入,直到输入新线,并允许进行一些基本的线编辑,例如使BackSpace工作。

因此,您永远无法一次获得一个字符,或者几个字符,只是一条完整的线。但这不是Eg scanf(“%d”)处理,而是仅处理数字,并在此处停止,而其余的则在c库中进行了缓冲未来 stdio 要使用的功能。如果您的程序具有EG

printf("Enter a number: ");
scanf("%d", &a);

printf("Enter a word: ");
scanf("%s", word);

,并且您输入行 123 ABCD ,它将同时完成 scanf() s给出。第一个 scanf()在用户达到空间时不会返回,即使这是数字结束的地方(因为那时行仍在终端的线缓冲区中);第二个 scanf()不等待您输入另一行(因为输入缓冲区已经包含足够的足够填充%s 转换)。

这不是用户通常期望的!

取而代之的是,他们希望击中Enter完成输入,如果您击中Enter,则会获得默认值或错误,并可能有一个建议真正给出答案。

您不能真正使用 scanf(“%d”)来实现这一目标。如果用户只是输入,则什么都不会发生。因为 scanf()仍在等待该数字。终端发送线路,但您的程序看不到它,因为 scanf()食用它。您没有机会对用户的错误做出反应。

这也不是很有用。

因此,我建议使用 fgets() getline()一次读取完整的输入行。这与终端提供的内容完全匹配,并在用户输入线路后始终提供您的程序控件。您对输入行的处理取决于您,如果您需要一个数字,则可以使用 atoi() strtol(),甚至 sscanf( buf,“%d”,& a)分析数字。 sscanf() scanf()没有相同的不匹配,因为它读取的缓冲区的大小有限,并且结束时,它结束时 - 功能等不及更多。

fscanf()在常规文件上也可以很好 fgets() sscanf()。)


因此,而不是我上面的东西,请使用类似的东西:

printf("Enter a number: ");

fgets(buf, bufsize, stdin);
sscanf(buf, "%d", &a);

或者,实际上,检查返回值 sscanf()也可以检测到空行,否则无效数据:

#include <stdio.h>

int main(void)
{
    const int bufsize = 100;
    char buf[bufsize];
    int a;
    int ret;
    char word[bufsize];

    printf("Enter a number: ");
    fgets(buf, bufsize, stdin);

    ret = sscanf(buf, "%d", &a);

    if (ret != 1) {
        fprintf(stderr, "Ok, you don't have to.\n");
        return 1;
    }

    printf("Enter a word: ");
    fgets(buf, bufsize, stdin);

    ret = sscanf(buf, "%s", word);
    if (ret != 1) {
        fprintf(stderr, "You make me sad.\n");
        return 1;
    }

    printf("You entered %d and %s\n", a, word);
}

当然,如果您希望该程序坚持,您可以创建一个简单的功能来循环循环 fgets( ) sscanf(),直到用户被否定执行他们告诉他们的操作;或立即出现错误的退出。取决于您认为如果用户不想打球应该做什么。


您可以通过循环 getchar()读取字符,直到返回 scanf(“%d”)返回,从缓冲区,但这对用户只是在空线上输入输入的情况并没有任何作用。无论如何, fgets()将读取直到newline,因此您不必自己做。

To echo what I have posted in another answer about C++: I suggest to toss scanf() away, to never use it, and to instead use fgets() and sscanf().

The reason for this is, that at least in Unix-like systems by default, the terminal your CLI program runs on does some processing of the user input before your program sees it. It buffers input until a newline is entered, and allows for some rudimentary line editing, like making backspace work.

So, you can never get a single character at a time, or a few single characters, just a full line. But that's not what e.g. scanf("%d") processes, instead it processes just the digits, and stops there, leaving the rest buffered in the C library, for a future stdio function to use. If your program has e.g.

printf("Enter a number: ");
scanf("%d", &a);

printf("Enter a word: ");
scanf("%s", word);

and you enter the line 123 abcd, it completes both scanf()s at once, but only after a newline is given. The first scanf() doesn't return when a user has hit space, even though that's where the number ends (because at that point the line is still in the terminal's line buffer); and the second scanf() doesn't wait for you to enter another line (because the input buffer already contains enough to fill the %s conversion).

This isn't what users usually expect!

Instead, they expect that hitting enter completes the input, and if you hit enter, you either get a default value, or an error, with possibly a suggestion to please really just give the answer.

You can't really do that with scanf("%d"). If the user just hits enter, nothing happens. Because scanf() is still waiting for the number. The terminal sends the line onward, but your program doesn't see it, because scanf() eats it. You don't get a chance to react to the user's mistake.

That's also not very useful.

Hence, I suggest using fgets() or getline() to read a full line of input at a time. This exactly matches what the terminal gives, and always gives your program control after the user has entered a line. What you do with the input line is up to you, if you want a number, you can use atoi(), strtol(), or even sscanf(buf, "%d", &a) to parse the number. sscanf() doesn't have the same mismatch as scanf(), because the buffer it reads from is limited in size, and when it ends, it ends -- the function can't wait for more.

(fscanf() on a regular file can also be fine if the file format is one that supports how it skims over newlines like any whitespace. For line-oriented data, I'd still use fgets() and sscanf().)


So, instead of what I had above, use something like this:

printf("Enter a number: ");

fgets(buf, bufsize, stdin);
sscanf(buf, "%d", &a);

or, actually, check the return value of sscanf() too, so you can detect empty lines and otherwise invalid data:

#include <stdio.h>

int main(void)
{
    const int bufsize = 100;
    char buf[bufsize];
    int a;
    int ret;
    char word[bufsize];

    printf("Enter a number: ");
    fgets(buf, bufsize, stdin);

    ret = sscanf(buf, "%d", &a);

    if (ret != 1) {
        fprintf(stderr, "Ok, you don't have to.\n");
        return 1;
    }

    printf("Enter a word: ");
    fgets(buf, bufsize, stdin);

    ret = sscanf(buf, "%s", word);
    if (ret != 1) {
        fprintf(stderr, "You make me sad.\n");
        return 1;
    }

    printf("You entered %d and %s\n", a, word);
}

Of course, if you want the program to insist, you can create a simple function to loop over the fgets() and sscanf() until the user deigns to do what they're told; or to just exit with an error immediately. Depends on what you think your program should do if the user doesn't want to play ball.


You could do something similar e.g. by looping over getchar() to read characters until a newline after scanf("%d") returned, thus clearing up any garbage left in the buffer, but that doesn't do anything about the case where the user just hits enter on an empty line. Anyway, fgets() would read until a newline, so you don't have to do it yourself.

scanf()将newline字符留在缓冲区中

喜你已久 2025-02-19 00:59:22

在我的解决方案,您将在员工在第一个示例中显示的员工在这里的时间内拥有一个具有ID和布尔值的数据框。

import pandas as pd

#Your initial Dataframe
df = pd.DataFrame([[123,"2022-06-13 09:03", "2022-06-13 22:12"],[633, "2022-06-13 08:15", "2022-06-13 13:09"]], columns=['IdNum', 'BeginDate', 'Exitdate'])

#The dictionnary where I'll stock the result
dico_res = {}
for i in range(df.shape[0]):

  #I define a range of dates to know if your enter and exit is in the range
  enter = pd.to_datetime(df.loc[i]["BeginDate"])
  exit = pd.to_datetime(df.loc[i]["Exitdate"])
  start = pd.to_datetime(enter.strftime("%d/%m/%Y"))
  range_15_minutes = pd.date_range(start=start, end=end,freq="15min")
  list_boolean, idx = [], []
  
  for date in range(len(range_15_minutes)-1):
    if enter >= range_15_minutes[date] and enter < range_15_minutes[date+1]:
      list_boolean.append(True)
      
    elif exit >= range_15_minutes[date] and exit < range_15_minutes[date+1]:
      list_boolean.append(True)
    
    elif exit < range_15_minutes[date] or enter > range_15_minutes[date]:
        list_boolean.append(False)
    
    else:
      list_boolean.append(True)
      
    idx.append(range_15_minutes[date].strftime("%H:%M") + "-" + range_15_minutes[date+1].strftime("%H:%M"))

  dico_res[df.loc[i]["IdNum"]]=list_boolean

dataframe_solution = pd.DataFrame(dico_res, index=idx).T

Here my solution, you will have a Dataframe with Id as idex and booleans for the hours where the employees were here like you've shown in your first example.

import pandas as pd

#Your initial Dataframe
df = pd.DataFrame([[123,"2022-06-13 09:03", "2022-06-13 22:12"],[633, "2022-06-13 08:15", "2022-06-13 13:09"]], columns=['IdNum', 'BeginDate', 'Exitdate'])

#The dictionnary where I'll stock the result
dico_res = {}
for i in range(df.shape[0]):

  #I define a range of dates to know if your enter and exit is in the range
  enter = pd.to_datetime(df.loc[i]["BeginDate"])
  exit = pd.to_datetime(df.loc[i]["Exitdate"])
  start = pd.to_datetime(enter.strftime("%d/%m/%Y"))
  range_15_minutes = pd.date_range(start=start, end=end,freq="15min")
  list_boolean, idx = [], []
  
  for date in range(len(range_15_minutes)-1):
    if enter >= range_15_minutes[date] and enter < range_15_minutes[date+1]:
      list_boolean.append(True)
      
    elif exit >= range_15_minutes[date] and exit < range_15_minutes[date+1]:
      list_boolean.append(True)
    
    elif exit < range_15_minutes[date] or enter > range_15_minutes[date]:
        list_boolean.append(False)
    
    else:
      list_boolean.append(True)
      
    idx.append(range_15_minutes[date].strftime("%H:%M") + "-" + range_15_minutes[date+1].strftime("%H:%M"))

  dico_res[df.loc[i]["IdNum"]]=list_boolean

dataframe_solution = pd.DataFrame(dico_res, index=idx).T

计数两个定时之间的表中的行数

喜你已久 2025-02-18 20:14:21

因此,经过多次尝试和长时间的研究,我几乎使用UseContext来完成这项工作,但是最后我找到了解决方案,这些步骤是:

  1. 首先,我添加了一个新的组件&lt; adminottions /&gt; < /code>其中包含渲染我的&lt; adduser /&gt; < /code> and &lt; deleteuser /&gt; < /code> and &lt; updateusers /questusers /&gt; < /code>的所有逻辑。
  2. 我通过最后一个孩子(&lt; item /&gt; < /code>)传递了一个函数,将其调用并通过某些参数传递给parent code>&lt; gassindash /&gt; < /code的父组件。 >告诉单击哪个项目并渲染哪个项目。
  3. 然后,我使用这些参数,然后再次将它们传递到我的新组件`以渲染该特定项目,它有点复杂且许多层次结构,但对我来说是一个完美的解决方案。

admindash

const[componentId, setComponentId]= React.useState(false);
const [show, setShowComponent] = React.useState(false);

const handleClick=(id)=>{
      if(id===componentId){
        setShowComponent(!show);
      }
      else{
        setComponentId(id);
        setShowComponent(true);
      }
    }
return (
//Here I pass the handleClick hooks to the childs
<SideMenu handleClick={handleClick} />
//my new component who will render the items component
<AdminOptions whatToShow={componentId} show={show}  />
);

sidemenu

//passing again the handleClick to childs
<Items handleClick={props.handleClick} />

项目

//I'm passing again the handleClick and giving each item an ID to differentiate between them 
<Item 
  Name="addUser"
  Id="AddUser"
  handleClick={props.handleClick} />
<Item 
  Name="deleteUser"
  Id="DeleteUser"
  handleClick={props.handleClick} />
<Item 
  Name="updateUser"
  Id="UpdateUser"
  handleClick={props.handleClick} />

item

<ul>
//here in the onClick i pass the function handleclick with an item id as a parameter
  <li   
onClick={()=>{props.handleClick(props.Id)}}
>
    <div> {props.Name} </div>
  </li>
</ul>

//So here is a switch case conditional rendering depending on Item's ID
switch (props.whatToShow){
            case "AddUser":
                return(props.show && <AddUser />);
            case "DeleteUser":
                return(props.show && <DeleteUser />);
            case "UpdateUser":
                return(props.show && <UpdateUser />);
            default :
                return (<> </>);

管理使用该项目ID的那个处理,并使管理员在admindash中显示该项目组件,
我尽力使它尽可能清楚,任何有疑问的人都将其留在评论中。

So after a very many tries and long researches, I almost used useContext to do the job, but finally I found the solution, these are the steps :

  1. First I added a new component <AdminOptions /> which contains all the logic of rendering my <AddUser /> and <DeleteUser /> and <UpdateUsers /> .
  2. I Passed a function through the last child ( <Item /> ) to call it and pass some parameters with, to the parent component which is <AdminDash /> to tell which item is clicked and which to render.
  3. Then I used these parameters and pass them again to my new component ` to render that specific item, it's a bit complex and many hierarchy but it's a perfect solution for me.

AdminDash

const[componentId, setComponentId]= React.useState(false);
const [show, setShowComponent] = React.useState(false);

const handleClick=(id)=>{
      if(id===componentId){
        setShowComponent(!show);
      }
      else{
        setComponentId(id);
        setShowComponent(true);
      }
    }
return (
//Here I pass the handleClick hooks to the childs
<SideMenu handleClick={handleClick} />
//my new component who will render the items component
<AdminOptions whatToShow={componentId} show={show}  />
);

SideMenu

//passing again the handleClick to childs
<Items handleClick={props.handleClick} />

Items

//I'm passing again the handleClick and giving each item an ID to differentiate between them 
<Item 
  Name="addUser"
  Id="AddUser"
  handleClick={props.handleClick} />
<Item 
  Name="deleteUser"
  Id="DeleteUser"
  handleClick={props.handleClick} />
<Item 
  Name="updateUser"
  Id="UpdateUser"
  handleClick={props.handleClick} />

Item

<ul>
//here in the onClick i pass the function handleclick with an item id as a parameter
  <li   
onClick={()=>{props.handleClick(props.Id)}}
>
    <div> {props.Name} </div>
  </li>
</ul>

AdminOptions

//So here is a switch case conditional rendering depending on Item's ID
switch (props.whatToShow){
            case "AddUser":
                return(props.show && <AddUser />);
            case "DeleteUser":
                return(props.show && <DeleteUser />);
            case "UpdateUser":
                return(props.show && <UpdateUser />);
            default :
                return (<> </>);

So when I click on Add user item it pass an Id of that specific Item to the parent component(AdminDash) which execute that handleClick with the Id of the item, and make the AdminOptions Show that item Component in the AdminDash,
I did my best to make it as clear as possible, anyone who has a question leave it in the comment.

单击React JS之后,如何显示组件?

喜你已久 2025-02-17 23:47:28

您之所以发出此错误消息是因为您正在调用一个函数,该函数期望其参数不需要梯度计算。更具体地说, nn.bceloss 期望目标(第二参数)不需要梯度。

您可以通过从图表中分离参数来解决此问题:

lossFn(outputs, outputs.detach())

The reason you're having this error message is because you are calling a function which expects its argument to not require gradient computation. More specifically, nn.BCELoss expects the target (2nd argument) to not require gradient.

You can fix this by detaching the argument from the graph:

lossFn(outputs, outputs.detach())

RuntimeError:目标&#x2019;未针对自动编码器实施

喜你已久 2025-02-17 16:19:42

功能 t()什么都没有返回,或。您可以按照上一个答案暗示并返回self 进行操作,但这通常不是一个好主意。如果您只想C,请使用:

SecondTest = test(3,4)
SecondTest.t(30,40)
print(SecondTest.c)

The function t() returns nothing, or None. You can do as the previous answer suggests and return self, but this isn't normally a good idea. If you just want c, use:

SecondTest = test(3,4)
SecondTest.t(30,40)
print(SecondTest.c)

如何访问Python中类的实例变量(在“ __ Init __&quot”中未定义的变量?

喜你已久 2025-02-17 09:34:28

最简单的方法是将 geom_smooth 与loess: geom_smooth(method =“ loess”,span = 0.5)并播放 span parameter要获得更光滑或摇摆的形状。

The simplest way would be to use geom_smooth with LOESS: geom_smooth(method="loess", span=0.5) and play with the span parameter to get a more smooth or wiggly shape.

绘制我在GGPLOT中GAM的平滑功能

喜你已久 2025-02-16 12:27:46

不可能编写一个可以压缩每个字符串的函数。充其量您可以编写一个可以压缩最多但不是全部的功能。

压缩通过在某种程度上降低冗余而起作用。您的示例字符串似乎没有很多冗余,因此可能不是很容易压缩。

It is impossible to write a function that will compress every string. At best you can write a function that will compress most, but not all, strings.

Compression works by reducing redundancy at some level. Your example string does not appear to have a lot of redundancy, so is probably not very compressible.

缩小并解开字符串功能

喜你已久 2025-02-16 09:56:28

使用 re.findall 我们可以尝试:

inp = "document.getElementById('dlbutton').href = \"/d/05UJmMTa/\" + (213059 % 51245 + 213059 % 913) + \"/Cool%20Customer%20-%20In%20Your%20Face%20%28Original%20Mix%29.mp3\";"
parts = re.findall(r'\.href\s*=\s*"(.*?)"\s*\+\s*\((.*?)\)\s*\+\s*"(.*?)"', inp)
print(parts[0])

此打印:

['/d/05UJmMTa/',
 '213059 % 51245 + 213059 % 913',
 '/Cool%20Customer%20-%20In%20Your%20Face%20%28Original%20Mix%29.mp3']

Using re.findall we can try:

inp = "document.getElementById('dlbutton').href = \"/d/05UJmMTa/\" + (213059 % 51245 + 213059 % 913) + \"/Cool%20Customer%20-%20In%20Your%20Face%20%28Original%20Mix%29.mp3\";"
parts = re.findall(r'\.href\s*=\s*"(.*?)"\s*\+\s*\((.*?)\)\s*\+\s*"(.*?)"', inp)
print(parts[0])

This prints:

['/d/05UJmMTa/',
 '213059 % 51245 + 213059 % 913',
 '/Cool%20Customer%20-%20In%20Your%20Face%20%28Original%20Mix%29.mp3']

Python Regex提取变量

喜你已久 2025-02-16 09:49:16

这是我在 href =“ - 在一定程度上,这是一个猜测,因为我无法测试它,因为您没有发布可运行的最小,可再现的例子

warning_shown = False  # Define global variable.

class MyClass:
    ...

    def setinitqty(self):
        global warning_shown  # IMPORTANT.

        if self.btqty.get() == '':
            msg.showerror('Error','Set Bt Address Quantity')
        else:
            self.count = 0
            with open('C:/Users/user/Desktop/Test/test.txt','r') as f:
                for line in f:
                    if line.strip():
                        self.count += 1
            self.prntbtadd = self.count
            self.initqty = self.btqty.get()
            self.setbtn['state'] = 'disable'
            self.btqty['state'] = 'disable'
            self.rstbtn['state'] = 'active'
            self.rmn = int(self.initqty) - self.prntbtadd
            self.rmnqtylbl['text'] = str(self.rmn)
            self.rmnqtylbl.after(1000,self.setinitqty)
            if self.rmn <= 10:
                if not warning_shown:
                    msg.showwarning('Warning','Warning')
                    warning_shown = True
                    self.rmnbtaddfrm['bg'] = 'red'
                    self.rmnqtylbl['bg'] = 'red'

Here's how to use a global flag variable as I suggested in my comment — to a certain degree it's a guess, since I can't test it since you didn't post a runnable minimal, reproducible example.

warning_shown = False  # Define global variable.

class MyClass:
    ...

    def setinitqty(self):
        global warning_shown  # IMPORTANT.

        if self.btqty.get() == '':
            msg.showerror('Error','Set Bt Address Quantity')
        else:
            self.count = 0
            with open('C:/Users/user/Desktop/Test/test.txt','r') as f:
                for line in f:
                    if line.strip():
                        self.count += 1
            self.prntbtadd = self.count
            self.initqty = self.btqty.get()
            self.setbtn['state'] = 'disable'
            self.btqty['state'] = 'disable'
            self.rstbtn['state'] = 'active'
            self.rmn = int(self.initqty) - self.prntbtadd
            self.rmnqtylbl['text'] = str(self.rmn)
            self.rmnqtylbl.after(1000,self.setinitqty)
            if self.rmn <= 10:
                if not warning_shown:
                    msg.showwarning('Warning','Warning')
                    warning_shown = True
                    self.rmnbtaddfrm['bg'] = 'red'
                    self.rmnqtylbl['bg'] = 'red'

如何一次弹出tkinter消息框?

喜你已久 2025-02-16 04:52:27

最后,我找到了原因:

我有一个启动daemon,可以执行bash脚本 webstack.sh

该脚本启动Nginx和PHP-FPM,并在不太可能崩溃的情况下重新启动它们。

启动daemon使用 sh 在我的系统上执行脚本和 sh 没有完整的磁盘访问。

ZSH 具有完整的磁盘访问,因此我用 zsh 更改了 sh ,现在php-fpm可以访问外部驱动器。

Finally I found the cause:

I have a LaunchDaemon that executes the bash script webstack.sh.

The script launches nginx and php-fpm and restart them in the unlikely case they crash.

The LaunchDaemon use sh to execute the script and sh on my system does not have full disk access.

zsh has full disk access so I changed sh with zsh and now php-fpm can access external drives.

Macos Monterey上的php-fpm |无法访问外部驱动器上的文件

喜你已久 2025-02-16 00:54:06

但是,当我运行时,RenderPass会导致无效的指针:0xe00000000000e

有两种类型的手柄,由Vulkan函数返回:

  • 派遣:

可调度手柄类型是通向不透明类型的指针。该指针可以由层用作截取API命令的一部分,因此每个API命令将可调度类型作为其第一个参数。

  • 不及格:

不可触摸的句柄类型是64位整数类型,其含义取决于实现。

vkrenderpass 作为不可触及的手柄。没有理由将其视为64位价值以外的任何东西。这是否是有效的内存指针完全无关紧要。

您在评论中说,该功能返回 vk_success ,并且验证层不会报告任何错误。那是什么问题?如果您仍在呈现问题,那可能不是渲染通行对象,而是其他东西。

However when I run it renderPass results in an invalid pointer: 0xe000000000e

There are two types of handle returned by Vulkan functions:

  • dispatchable:

Dispatchable handle types are a pointer to an opaque type. This pointer may be used by layers as part of intercepting API commands, and thus each API command takes a dispatchable type as its first parameter.

  • non-distpatchable:

Non-dispatchable handle types are a 64-bit integer type whose meaning is implementation-dependent.

VkRenderPass is defined as a non-distpatchable handle. There's no reason to look at the value and consider it as anything other than a 64 bit value. Whether or not it's a valid memory pointer is completely irrelevant.

You say in the comments that the function returns VK_SUCCESS and the validation layers don't report anything wrong. So what is the problem? If you're still having a problem rendering, it's likely not the render pass object, but something else.

vkcreaterenderpass返回无效指针

喜你已久 2025-02-15 13:39:54

您可以在细节视图的背景下提供它们。例如,例如以下方法,例如以下方法,例如

class ChapterDetailView(DetailView):
    model = Chapter
    template_name = 'chapter_detail.html'
    context_object_name = 'current_chapter'
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['previous_chapter'] = your_previous_chapter_link_if_any_else_none
        context['next_chapter'] = your_next_chapter_link_if_any_else_none
        return context

以下方法,presurn_chapter和next_ chapter可能是在模型中定义URL.py如下

class Chapter(models.Model):
    # ... your models field
    def get_next_chapter_url(self):
        next_chapter = Chapter.objects.filter(id__gt=self.id).order_by('id').first()
        if next_chapter:
            return reverse('chapter-detail', kwargs={'id': next_chapter.id})

和章节详细信息页面模板,假设上下文对象名称为current_ chapter

<a href="{{current_chapter.get_next_chapter_url}}">Next Chapter</a>

You can provide them in a context of detail view. For example like previous_chapter, current_chapter and next_chapter as follow

class ChapterDetailView(DetailView):
    model = Chapter
    template_name = 'chapter_detail.html'
    context_object_name = 'current_chapter'
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['previous_chapter'] = your_previous_chapter_link_if_any_else_none
        context['next_chapter'] = your_next_chapter_link_if_any_else_none
        return context

Another approach may be defining urls in models.py as follow

class Chapter(models.Model):
    # ... your models field
    def get_next_chapter_url(self):
        next_chapter = Chapter.objects.filter(id__gt=self.id).order_by('id').first()
        if next_chapter:
            return reverse('chapter-detail', kwargs={'id': next_chapter.id})

And in chapter detail page template assuming context object name as current_chapter

<a href="{{current_chapter.get_next_chapter_url}}">Next Chapter</a>

django在QuerySet中给定当前对象获取下一个对象

喜你已久 2025-02-15 03:06:50

尽管我不知道您的 checking_plus_1 函数,但是的,您可以在每次迭代时在循环中突变您的数组。

您还可以通过在循环中添加 console.log(array)来查看更改。

Despite I don't know your checking_plus_1 function, yes you can mutate your array in your for loop on each iteration.

You can also see the changes by adding console.log(array) in your for loop.

在数组中执行功能后,数组是否更新?如果没有,有人可以向我解释为什么?

喜你已久 2025-02-14 17:56:35

对于我无法完全理解的过程相关的内容,您必须行 driver = uc.chrome() and driver.get('https://namecheap.com')< /code>在中,如果__name__ =='__ main __':

此外,链接必须具有 https:// http:// 才能工作。

这是我的工作代码:

import undetected_chromedriver as uc # The .v2 is not necessary in the last version of undetected_chromedriver
import time
def main():
    time.sleep(4)
    # Continue your code here

if __name__ == '__main__':
    driver = uc.Chrome()
    driver.get('https://namecheap.com')
    main()

For something related to processes, which I cannot fully understand, you have to the lines driver = uc.Chrome() and driver.get('https://namecheap.com') in the if __name__ == '__main__':.

Also the link has to have the https:// or http:// for it to work.

Here's my working code:

import undetected_chromedriver as uc # The .v2 is not necessary in the last version of undetected_chromedriver
import time
def main():
    time.sleep(4)
    # Continue your code here

if __name__ == '__main__':
    driver = uc.Chrome()
    driver.get('https://namecheap.com')
    main()

硒:我无法制作一个机器人,可以使用Cloudflare登录网站

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文