城歌

文章 评论 浏览 32

城歌 2025-02-03 04:11:03

Fody的答案有效。因此,在完整的中,my_cypress_spec.js 可以变成类似的东西:

describe('The Home Page Tests', () => {
  it('Test HTML embedded JavaScript function', () => {
    // Assumes, e.g. "baseUrl": "http://127.0.0.1:5500" set in cypress.json
    cy.visit('index.html'); 
    cy.window().then(win => {
      expect(win.foo()).to.eq('bar');
    });
  }); 
});

但是,我得到“ typeError ... win.foo不是函数”的原因是因为在我的 index.html中在我的计算机上(不如上最初发布),我有一个开口< script type =“模块”> 。将其更改回< script> 进行了测试。

因此,为了完整,我将其标记为答案,同时指出洞察力来自@fody和@jonrsharpe。

Fody's answer works. So, in full my_cypress_spec.js can become something like:

describe('The Home Page Tests', () => {
  it('Test HTML embedded JavaScript function', () => {
    // Assumes, e.g. "baseUrl": "http://127.0.0.1:5500" set in cypress.json
    cy.visit('index.html'); 
    cy.window().then(win => {
      expect(win.foo()).to.eq('bar');
    });
  }); 
});

However, the reason I was getting a "TypeError ... win.foo is not a function" was because in my index.html on my machine (not as originally posted above) I had an opening <script type="module">. Changing that back to <script> made the test pass.

So for completeness I'll tag this as The Answer while noting the insights come from @Fody and @jonrsharpe.

我们可以直接单位测试HTML嵌入的JavaScript功能吗?

城歌 2025-02-03 01:16:22

您可以在最后一个/字符之后获取值:

const pokemonID = foo.substring(foo.lastIndexOf("/") + 1)

使用 string.lastindexof 获取slash字符的最终索引,然后使用 string.substring 只有一个参数可以在最后一个/字符。我们将1添加到LastIndexof,以省略最终斜线。

为此,您需要从请求URL中放下最终的拖延斜线(无论如何都不会做任何事情)。

这可以将其抽象成实用程序函数,以获取任何URL的最后值,这是使用拆分和通过索引方法查找的最大改进。

但是,要当心,它将采用最后一个斜线之后的价值。
使用字符串 https://pokeapi.co/api/v2/pokemon/6/pokedex 将返回 pokedex

如果您与内置路由器一起使用Angular,React,Vue等,则该框架的特定API可以获取所需的确切参数,无论URL形状如何。

You can grab the value after the last / character like so:

const pokemonID = foo.substring(foo.lastIndexOf("/") + 1)

Using String.lastIndexOf to get the final index of the slash character, and then using String.substring with only a single argument to parse the part of the string after that last / character. We add 1 to the lastIndexOf to omit the final slash.

For this to work you need to drop your final trailing slash (which won't do anything anyways) from your request URL.

This could be abstracted into a utility function to get the last value of any url, which is the biggest improvement over using a split and find by index approach.

However, beware, it will take whatever the value is after the last slash.
Using the string https://pokeapi.co/api/v2/pokemon/6/pokedex would return pokedex.

If you are using Angular, React, Vue etc with built in router, there will be specific APIs for the framework that can get the exact parameter you need regardless of URL shape.

从JavaScript中的字符串获得值的清洁方法

城歌 2025-02-02 23:33:26

不要与 ID 一起工作。而不是将 id 作为参数传递给 insertcolumn ,而是传递表元素本身。您可以通过从沿节点上沿DOM树来找到哪个表是当前的表格:

onclick="insertColumn(this.closest(table))"

在所有HTML表中重复此功能。

然后在中insertcolumn 适应并将分配删除到 table ,因为 table 现在将是参数名称:

const insertColumn = (table) => { // Notice change of parameter name
    // Removed the assignment to table variable here
    let cell_1 = table.rows[0].insertCell(1);
    // ...etc
}

Don't work with id. Instead of passing an id as argument to insertColumn, pass the table element itself. You can find out which table is the current one, by walking up the DOM tree from the this node:

onclick="insertColumn(this.closest(table))"

Repeat this in all your HTML tables.

Then in insertColumn adapt and remove the assignment to table, as table will now be the parameter name:

const insertColumn = (table) => { // Notice change of parameter name
    // Removed the assignment to table variable here
    let cell_1 = table.rows[0].insertCell(1);
    // ...etc
}

JavaScript:如何通过JavaScript从新生成的标签获得ID

城歌 2025-02-02 19:54:18

应该使用Osmwidget,这是我使用以下解决方案的方式:
如何在django?

我的模型:

from django.contrib.gis.db import models

class Territory(models.Model):
    poly = models.PolygonField(_('Polygon, borders of territory.'))
    location = models.PointField(_('Location, point on the map.'))

我的直列模型:

from django.contrib.gis.forms.widgets import OSMWidget

class TerritoryStackedInline(admin.StackedInline):
    model = Territory
    extra = 1

    def formfield_for_dbfield(self, db_field, **kwargs):
        if db_field.name in ('poly', 'location'):
            kwargs['widget'] = OSMWidget
        return super().formfield_for_dbfield(db_field,**kwargs)

OSMWIDGET覆盖模板为“ GIS/OPENLAYERS-OSM.HTML”的模板发生在哪里发生的基本层的覆盖在哪里:

{% block base_layer %}
var base_layer = new ol.layer.Tile({source: new ol.source.OSM()});
{% endblock %}

没有它,基本层代码看起来像这样(使用的模板使用了”(模板) gis/openlayers.html”):

{% block base_layer %}
    var base_layer = new ol.layer.Tile({
        source: new ol.source.XYZ({
            attributions: "NASA Worldview",
            maxZoom: 8,
            url: "https://map1{a-c}.vis.earthdata.nasa.gov/wmts-webmerc/" +
                 "BlueMarble_ShadedRelief_Bathymetry/default/%7BTime%7D/" +
                 "GoogleMapsCompatible_Level8/{z}/{y}/{x}.jpg"
        })
    });
{% endblock %}

如您所见,有不同的来源。

There should be used OSMWidget and here is how I have used the following solution:
How do I add a custom inline admin widget in Django?

My model:

from django.contrib.gis.db import models

class Territory(models.Model):
    poly = models.PolygonField(_('Polygon, borders of territory.'))
    location = models.PointField(_('Location, point on the map.'))

My inline model:

from django.contrib.gis.forms.widgets import OSMWidget

class TerritoryStackedInline(admin.StackedInline):
    model = Territory
    extra = 1

    def formfield_for_dbfield(self, db_field, **kwargs):
        if db_field.name in ('poly', 'location'):
            kwargs['widget'] = OSMWidget
        return super().formfield_for_dbfield(db_field,**kwargs)

The OSMWidget overrides template to "gis/openlayers-osm.html" where does following override of basic layer is happen:

{% block base_layer %}
var base_layer = new ol.layer.Tile({source: new ol.source.OSM()});
{% endblock %}

without it the basic layer code looks like this(template used "gis/openlayers.html"):

{% block base_layer %}
    var base_layer = new ol.layer.Tile({
        source: new ol.source.XYZ({
            attributions: "NASA Worldview",
            maxZoom: 8,
            url: "https://map1{a-c}.vis.earthdata.nasa.gov/wmts-webmerc/" +
                 "BlueMarble_ShadedRelief_Bathymetry/default/%7BTime%7D/" +
                 "GoogleMapsCompatible_Level8/{z}/{y}/{x}.jpg"
        })
    });
{% endblock %}

As you can see there is different source.

在Geodjango中,使用Geomodeladmin作为Django Admin中的堆栈

城歌 2025-02-02 04:10:33

考虑以下情况。

您安装了三个版本的Python:

  • Python 3.7
  • Python 3.8
  • Python 3.9

您的“默认”版本为3.8。这是出现在您的路径中的第一个。因此,当您键入 python3 (linux或mac)或 python (windows)在shell中,您将启动3.8解释器,因为这是第一个在穿越时发现的python可执行文件你的道路。

假设您正在启动一个新项目,您要在其中使用Python 3.9。您创建一个称为 .venv 的虚拟环境并激活它。

python3.9 -m venv .venv         # "py -3.9" on Windows
source .venv/bin/activate    # ".venv\Scripts\activate" on Windows 

现在,我们使用Python 3.9激活了虚拟环境。在外壳中键入 python 启动了3.9解释器。

但是,如果您键入

pip install <some-package>

,则使用哪种版本的 pip ?是默认版本的PIP,即Python 3.8还是虚拟环境中的Python版本?

解决这种歧义的一种简单方法是仅使用

python -m pip install <some-package>

-M 标志,确保您使用与活动python可执行的pip。

即使您只安装了一个全局版本的Python,也可以始终使用 -M ,这是一个很好的做法。

关于。路径

所谓的路径是您的系统搜索可执行文件的目录列表。当您键入命令(例如 python )时,此列表将从第一个目录到最后一个目录,搜索与您键入的命令匹配的文件名。

如果找到文件名/命令,则匹配的文件将执行,而无需考虑潜在的以后匹配。如果没有发生匹配,则找不到命令或其变体。这种行为是设计的。

在UNIX系统上,路径环境变量被称为 $ path ,而在Windows系统上,它被称为%path%

更多有关 -m -flag(2022年12月)

大多数查看此问题的人可能希望上面用PIP给出的解释。不过,从更一般的意义上讲,当使用 python -m some_module 时, -m flag使Python Execute some_module 作为脚本。这在
“以脚本运行”是什么意思

?在导入文件的顶部语句。这可以使用 some_module 在导入文件中定义的函数,类和变量。
要执行 some_module 作为脚本而不是导入它,如果__name__ ==“ __ -main __” block在文件中,您将定义。在命令行上运行 python some_module.py 时,该块将执行。这很有用,因为您 不希望此代码块在导入其他文件时运行,但是您 do 希望它在从命令行调用时运行。

对于项目中的模块,此脚本/模块构造应按原样运行,因为从终端运行时,Python会从您的工作目录中找到模块:

python some_module.py

但是对于Python标准库的一个模块,这将行不通。 Python文档中的示例使用 timeIt pip 工作相同):

python3 timeit -s 'print("hello")'  # 'python timeit.py ...' fails as well 

这返回错误:“ Python:coble file'/home/&lt ;用户名&gt;/timeit':[errno 2]否此类文件或目录“

添加 -m flag告诉Python告诉Python,请在 timeit.py.py 的路径中寻找路径并执行如果__name__ ==“ __ -main __” 从文件中的子句。

python3 -m timeit -s 'print("hello")'

这是预期的。

的来源如果__name __ ==“ __ main __” 可以找到时间级模块的块此处

Consider the following scenario.

You have three versions of Python installed:

  • Python 3.7
  • Python 3.8
  • Python 3.9

Your "default" version is 3.8. It's the first one appearing in your path. Therefore, when you type python3 (Linux or Mac) or python (Windows) in a shell you will start a 3.8 interpreter because that's the first Python executable that is found when traversing your path.

Suppose you are then starting a new project where you want to use Python 3.9. You create a virtual environment called .venv and activate it.

python3.9 -m venv .venv         # "py -3.9" on Windows
source .venv/bin/activate    # ".venv\Scripts\activate" on Windows 

We now have the virtual environment activated using Python 3.9. Typing python in a shell starts the 3.9 interpreter.

BUT, if you type

pip install <some-package>

Then what version of pip is used? Is it the pip for the default version, i.e. Python 3.8, or the Python version within the virtual environment?

An easy way to get around that ambiguity is simply to use

python -m pip install <some-package>

The -m flag makes sure that you are using the pip that's tied to the active Python executable.

It's good practice to always use -m, even if you have just one global version of Python installed from which you create virtual environments.

Re. path

The so-called path is a list of directories where your system searches for executables. When you type a command, like python, this list is traversed from the first directory to the last, searching for a filename that matches the command you typed.

If the filename/command is found, the matched file gets executed without taking into account potential later matches. If no match occurs, you get a Command not found or a variation thereof. This behavior is by design.

On UNIX systems the path environment variable is called $PATH, while on Windows systems it's referred to as %PATH%

More general comments about the -m-flag (Dec. 2022)

Most people viewing this will likely want the explanation given above with pip. In a more general sense though, when using python -m some_module, the -m flag makes Python execute some_module as a script. This is stated in the docs, but might be difficult to understand without some baseline knowledge.
What does it mean to "run as a script"?

In Python, a module some_module is typically imported into another Python file with an import some_module statement at the top of the importing file. This enables the use of functions, classes, and variables defined in some_module inside the importing file.
To execute some_module as a script instead of importing it, you would define an if __name__ == "__main__" block inside the file. This block gets executed when running python some_module.py on the command line. This is useful because you do not want this code block to run when importing into other files, but you do want it to run when invoked from the command line.

For modules inside your project, this script/module construct should run as is, because Python will find the module from your working directory when running from the terminal:

python some_module.py

But for modules that are part of Python's Standard Library, this will not work. The example from the Python docs uses timeit (pip works the same):

python3 timeit -s 'print("hello")'  # 'python timeit.py ...' fails as well 

This returns the error: "python: can't open file '/home/<username>/timeit': [Errno 2] No such file or directory"

Adding the -m flag tells Python to look in path for timeit.py and execute the if __name__ == "__main__" clause from the file.

python3 -m timeit -s 'print("hello")'

This works as expected.

The source for the if __name__ == "__main__" block for the timeit module can be found here.

使用`python -m pip'而不是只是`pip'有什么影响?

城歌 2025-02-01 06:30:51

bash 4.4或更高版本中,进程替换将设置 $!,这意味着您可以等待该过程以获取其退出状态。

#!/usr/bin/env bash
set -Eeuo pipefail
shopt -s inherit_errexit

echo 'before'

mapfile -t tuples < <(exit 1)
wait $!

echo 'after'

mapfile 本身(通常)不会具有非零的状态,因为它非常高兴地阅读过程替换会产生什么(如果有的话)。

In bash 4.4 or later, process substitutions will set $!, which means you can wait on that process to get its exit status.

#!/usr/bin/env bash
set -Eeuo pipefail
shopt -s inherit_errexit

echo 'before'

mapfile -t tuples < <(exit 1)
wait $!

echo 'after'

mapfile itself (in general) won't have a non-zero status, because it's perfectly happy read what, if anything, the process substitution produces.

如何让bash继承stdin子壳失败

城歌 2025-02-01 04:53:02

尝试在RouteserviceProvider中添加域线。

Route::middleware("web")->domain('Domain Name')->namespace($this->namespace)->group(base_path("routes/web.php"));

Try to add a domain line in RouteServiceProvider.

Route::middleware("web")->domain('Domain Name')->namespace($this->namespace)->group(base_path("routes/web.php"));

Laravel 8处理子域路由,但它不起作用,我对此有些困惑

城歌 2025-01-31 16:20:54

我有一些您可能会执行的步骤:

  1. 照常上传文件,但是在此步骤中,您必须将用户ID作为参数

    包含

  2. 重命名文件之前,请先保存图像,示例:

      $ user-&gt; id。时间() 。 '。' 。 $ file-&gt; getClientExtension();
     
  3. 将其上传到文件夹

  4. 保存到您的表格

I have some steps that you might do :

  1. Upload file as usual, but in this step you must include user id as parameter

  2. Query user by id

  3. Rename file before save image, example :

    $user->id . time() . '.' . $file->getClientExtension();
    
  4. Upload it to folder

  5. Save to your table

如何将用户照片大量上传到MySQL数据库

城歌 2025-01-31 09:03:54

从文档中:

密度bool,可选的
如果为错误,则结果将包含每个垃圾箱中的样本数量。如果为true,结果是bin处的概率密度函数的值,归一化,使得范围内的积分为1

我怀疑您做了 np.sum(hist)并获得了0.0017。 np.sum(hist)*bin_size 应为您提供正确的值1

From the docs:

density bool, optional
If False, the result will contain the number of samples in each bin. If True, the result is the value of the probability density function at the bin, normalized such that the integral over the range is 1.

I suspect you did np.sum(hist) and got your 0.0017. np.sum(hist)*bin_size should give you the correct value of 1

NP。在指定的垃圾箱中产生非常小的计数

城歌 2025-01-31 08:44:27

您可以使用Python请求获取DAG_RUN_ID信息。之后您将能够计算运行时间。

response = requests.get(url=f"{base_url}/dags/{dag_id}/dagRuns/{dag_run_id}", headers={"Authorization": _basic_auth_str("username", "password")})

You can get the dag_run_id information with a python request. You will be able to calculate the running time afterwards.

response = requests.get(url=f"{base_url}/dags/{dag_id}/dagRuns/{dag_run_id}", headers={"Authorization": _basic_auth_str("username", "password")})

如何使用python在气流中跑步DAG的持续时间?

城歌 2025-01-31 08:04:51

基本模板中包含的模板需要上下文变量 able_apps ,其结构如上所述在这里

由于您可能无法使其与您的应用程序正确合作,因此您也可以在基本模板中覆盖 {%block nav-sidebar%} ,并提供一些适合您使用的HTML案件。

但是毕竟,重复使用您的应用程序为其他应用程序(管理员)重复使用模板可能不是一个好主意成为一个问题,因为它们可能会随后的Django版本而改变。

The app_list.html template which is included in your base template requires a context variable available_apps with a structure as described here.

As you probably won't be able to make this include work properly with your app you could also override the {% block nav-sidebar %} in your base template and provide some HTML that fits your use-case.

But after all it's probably not such a good idea to reuse templates which are made for a different app (admin) with your app because it's difficult to predict how they will behave, what their requirements are and beyond this maintainance in the long term will also be a problem as they might change with future Django versions.

如何在自定义视图中启用Django管理侧栏导航?

城歌 2025-01-30 07:12:18

昨天我想起,当我使用V-container时,这并没有发生,因此我模仿了V-Container的CSS,但进行了一些更改以应用不同的样式。
本质上,如果V-Select的宽度相当低,则如果您希望它保持一定尺寸,则无法手动设置V-Select的宽度,最终是V-COL实际上在做的事情。
我希望根据父母的宽度进行更改,因此我使用了一个百分比,并减去了flexbox差距(20px)除以父母中的项目数(2),因此:

.v-select-class {
    width: calc(50% - 10px);
}

希望这对将来的人有帮助。

Yesterday I remembered that it didn't happen when I used a v-container, so I mimicked the css of a v-container but with a few changes to apply a different style.
Essentially, if the v-select has rather low width, you can't get around setting the width of the v-select manually if you want it to stay a certain size, which in the end is what v-col is effectively doing.
I wanted it to change depending on the parent's width so I used a percentage and subtracted the total flexbox gap (20px) divided by the number of items (2) in the parent, like this:

.v-select-class {
    width: calc(50% - 10px);
}

Hope this helps someone in the future.

V-Select根据选定项目的长度更改宽度

城歌 2025-01-30 04:04:39

即使您解决了问题,但事实证明您已经指定了 -MEM_PER_CPU = 300MB 在您的 sbatch 脚本中,我想添加就我而言,我的slurm设置不允许 -Mem_per_cpu in sbatch ,只有 - mem 。因此, srun 命令仍将分配所有内存并阻止后续步骤。对我的关键是指定 -MEM_PER_CPU (或 - mem srun 命令。

Even though you have solved your problem which turned out to be something else, and that you have already specified --mem_per_cpu=300MB in your sbatch script, I would like to add that in my case, my Slurm setup doesn't allow --mem_per_cpu in sbatch, only --mem. So the srun command will still allocate all the memory and block the subsequent steps. The key for me, is to specify --mem_per_cpu (or --mem) in the srun command.

在Slurm中运行并行作业

城歌 2025-01-30 01:33:06

收集变量是该集合的一部分。它们适用于单次驱动器中的驾驶测试。
我很少使用它们,仅用于脚本的内部逻辑,而不是与环境相关的(例如常数为ISO代码))。

如果有必要在不同的配置中驱动相同的集合,则根据用例,我将变量转移到全球变量或ENV变量。

您可以在
https://learlearning.postman.postman.com/docs/docs/sending-requests/sending-requests/sending-requests- /变量/#变量 - 划分

The collection-variables are part of the collection. They're suitable for driving tests in single-enviroments.
I'm using them very rarely and only collection-related for the inner logic of my scripts, that is not environment related (e.g. constants as ISO-Codes).

If it becomes necessary to drive the same collection in different configs, i shift my variables to globals or env variables, depending on the use-case.

You can finde more details about this topic in
https://learning.postman.com/docs/sending-requests/variables/#variable-scopes

如果我在测试范围内声明了使用的变量,则应使用什么标志?

城歌 2025-01-30 00:17:28

您可以通过更改QR码的字符串中的发行器名称来更改帐户名。这是我用您的应用程序名称生成替换“ awscognito”的字符串

`otpauth://totp/AWSCognito:${email}?secret=${code}&issuer=https://cognito-idp.ap-southeast-2.amazonaws.com/`

You can change the account name by changing the issuer name in the string that goes into the QR code. Here's the string I was generating

`otpauth://totp/AWSCognito:${email}?secret=${code}&issuer=https://cognito-idp.ap-southeast-2.amazonaws.com/`

Replace 'AWSCognito' with your app name.

AWS cognito-设置MFA身份验证器应用中的默认帐户名称

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

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