和我恋爱吧

文章 评论 浏览 32

和我恋爱吧 2025-02-20 22:38:31

如 @ derpirscher所述,您必须将 * *指定为允许原始标头或确切协议:// host:port。

在您的用例中,对CORS请求的响应缺少所需的访问控制 - 允许原始标头,该标头用于确定是否可以通过在当前来源中运行的内容访问资源。

您还可以配置一个站点,以允许任何站点使用 *通配符访问它。您只能将其用于公共API。私有API永远不要使用 *,而应具有特定的域或域设置。此外,通配符仅适用于用versorigin属性设置为匿名的请求,并防止在请求中发送凭证。

Access-Control-Allow-Origin: *

确保请求具有原始标头,并且标头值与CORS配置中的原始值至少匹配。请注意,方案,主机和端口的值必须完全匹配。可接受匹配的一些示例如下:

http://origin.example.com 匹配 http://origin.example.com:80 (因为80是默认的http端口),但不匹配 https://origin.example.com http://origin.example.com:8080 http://origin.example.com:5151 http:// sub。 Origin.example.com

https://example.com:443 匹配 https://example.com 但不是 http://example.com http://example.com:443

http:// localhost:8080仅与http:// localhost:8080,不是http:// localhost:5555或 http://localhost.example.com:8080

As mentioned by @ derpirscher you must either specify * as Allow-Origin header or the exact protocol://host:port.

In your use case the response to the CORS request is missing the required Access-Control-Allow-Origin header, which is used to determine whether or not the resource can be accessed by content operating within the current origin.

You can also configure a site to allow any site to access it by using the * wildcard. You should only use this for public APIs. Private APIs should never use *, and should instead have a specific domain or domains set. In addition, the wildcard only works for requests made with the crossorigin attribute set to anonymous, and it prevents sending credentials like cookies in requests.

Access-Control-Allow-Origin: *

Ensure that the request has an Origin header and that the header value matches at least one of the Origins values in the CORS configuration. Note that the scheme, host, and port of the values must match exactly. Some examples of acceptable matches are as follows:

http://origin.example.com matches http://origin.example.com:80 (because 80 is the default HTTP port), but does not match https://origin.example.com, http://origin.example.com:8080, http://origin.example.com:5151, or http://sub.origin.example.com.

https://example.com:443 matches https://example.com but not http://example.com or http://example.com:443.

http://localhost:8080 only matches exactly http://localhost:8080 , not http://localhost:5555 or http://localhost.example.com:8080 .

Google云负载平衡服务中的Access-Control-Allow-Allow-Origin通配符子域

和我恋爱吧 2025-02-20 20:29:40

因此,看起来这是一个版本 - 请参阅 https://github.com/ansible/ansible/ansible/sible/issues/issues/issues/issues/issues /39389

我的原始代码可与2.12.2一起使用,

我在查询中添加了类别,以按字母顺序返回文件列表。

- name:
  set_fact:
    mytests: "{{ mytests|d([]) + (lookup('file', item)|from_yaml).test }}" # this gets the list called 'test' from current file.
  loop: "{{ query('fileglob', 'test_suites/QS_suite/*.yml')|sort }}" # loops through the files

So looks like it's a version thing - see https://github.com/ansible/ansible/issues/39389

My original code works with 2.12.2

I've added a sort to the query to return the file list in alphabetical order.

- name:
  set_fact:
    mytests: "{{ mytests|d([]) + (lookup('file', item)|from_yaml).test }}" # this gets the list called 'test' from current file.
  loop: "{{ query('fileglob', 'test_suites/QS_suite/*.yml')|sort }}" # loops through the files

为什么我可以用Ansible附加到列表

和我恋爱吧 2025-02-20 17:49:46

我的一个朋友的解决方案与真实的答案相对应:(

λx .yx)((λy.λt.yt)ZX)=> y(((((λy).λt.yt)z)x)=> y((λt .zt)x)=> y(zx)=> yzx

我的错误本来是我解决了lambda,好像(λx.yx)((λy.λt.yt)(zx)),我将ZX视为Singol Block,不知道默认情况下不是,您不是,并且您需要父母来指定它。
唯一仍然存在的问题是,为什么教授答案YZX与在线答案YX不同。

A friend of mine had this solution that apperently corresponds to the real answer:

(λx.yx)((λy.λt.yt)zx) => y(((λy.λt.yt)z)x) => y((λt.zt)x) => y(zx) => yzx

my error would have been that I resolved the lambda as if (λx.yx)((λy.λt.yt)(zx)), I considered zx as a singol block not knowing that by default they aren't and that you need parenteses to specify it.
Only question that remains is why the professor answer yzx is different from the online answer yx.

我该如何减少?

和我恋爱吧 2025-02-20 17:44:33

Python没有功能过载。 do 具有的是头等函数对象。

创建 dict 将映射接收器值映射到适当的函数。

def send_to_all():
    pass

def send_to_last_three_months():
    pass

def send_to_last_six_months():
    pass

senders = {
    Receiver.ALL: send_to_all,
    Receiver.THREE_MONTHS: send_to_last_three_months,
    Receiver.SIX_MONTHS: send_to_last_six_months,
}

@api_view(["POST"])
def send_email(request):
    email_to = request.data["emailTo"]
    sender = senders[email_to]
    sender()

Python doesn't have function overloading. What it does have is first-class function objects.

Create a dict that maps Receiver values to the appropriate function.

def send_to_all():
    pass

def send_to_last_three_months():
    pass

def send_to_last_six_months():
    pass

senders = {
    Receiver.ALL: send_to_all,
    Receiver.THREE_MONTHS: send_to_last_three_months,
    Receiver.SIX_MONTHS: send_to_last_six_months,
}

@api_view(["POST"])
def send_email(request):
    email_to = request.data["emailTo"]
    sender = senders[email_to]
    sender()

超载和策略模式

和我恋爱吧 2025-02-20 03:24:08

以下类可用于从 classPath 中加载资源,并且还会收到一条拟合错误消息,以防给定 filepath 有问题。 。

import java.io.InputStream;
import java.nio.file.NoSuchFileException;

public class ResourceLoader
{
    private String filePath;

    public ResourceLoader(String filePath)
    {
        this.filePath = filePath;

        if(filePath.startsWith("/"))
        {
            throw new IllegalArgumentException("Relative paths may not have a leading slash!");
        }
    }

    public InputStream getResource() throws NoSuchFileException
    {
        ClassLoader classLoader = this.getClass().getClassLoader();

        InputStream inputStream = classLoader.getResourceAsStream(filePath);

        if(inputStream == null)
        {
            throw new NoSuchFileException("Resource file not found. Note that the current directory is the source folder!");
        }

        return inputStream;
    }
}

The following class can be used to load a resource from the classpath and also receive a fitting error message in case there's a problem with the given filePath.

import java.io.InputStream;
import java.nio.file.NoSuchFileException;

public class ResourceLoader
{
    private String filePath;

    public ResourceLoader(String filePath)
    {
        this.filePath = filePath;

        if(filePath.startsWith("/"))
        {
            throw new IllegalArgumentException("Relative paths may not have a leading slash!");
        }
    }

    public InputStream getResource() throws NoSuchFileException
    {
        ClassLoader classLoader = this.getClass().getClassLoader();

        InputStream inputStream = classLoader.getResourceAsStream(filePath);

        if(inputStream == null)
        {
            throw new NoSuchFileException("Resource file not found. Note that the current directory is the source folder!");
        }

        return inputStream;
    }
}

如何从资源文件夹加载文件?

和我恋爱吧 2025-02-19 20:07:57

如果打开开发人员工具控制台,当窗口不通过 window.close.close()

脚本只能关闭他们打开的窗口。

消息很清楚。使用 window.close()关闭窗口时,会有一些限制。在Chromium中, window.close()如果新窗口/TAB具有开启器,或者背面/正向堆栈包含少于两个条目。 window.close()的限制用于安全性和用户体验。有关更多详细信息,您可以参考此博客

以编程方式关闭“继续进行窗口”的唯一方法是通过 window.open()打开窗口。例如,如果要通过单击链接打开新窗口,则可以使用以下代码:

<a href="javascript:;" onclick="window.open('test.html', '_blank')">link</a>

然后在 test.html 上使用 window.close() >关闭窗口。

If you open the Developer Tools console, you'll find this message when the window doesn't close by window.close():

Scripts may close only the windows that were opened by them.

The message is clear. There're some restrictions when using window.close() to close window. In Chromium, window.close() succeeds if the new window/tab has an opener or if the back/forward stack contains fewer than two entries. The limitation of window.close() is for security and user-experience. For more detailed information, you can refer to this blog.

The only way to close the proceed window programmatically is opening the window by window.open(). For example, if you want to open a new window by clicking a link, you can use the code like below:

<a href="javascript:;" onclick="window.open('test.html', '_blank')">link</a>

Then on test.html you can use window.close() to close the window.

如何以编程方式退出亭子模式

和我恋爱吧 2025-02-19 20:06:01

对于简单的情况,您只需使用 std :: String 类和 std :: to_string 函数,这两个函数都在C ++中始终是很长一段时间。

#include <string>
#include <iostream>

int main()
{
  float t = 30.2;
  std::string r = "Temperature is " + std::to_string(t);
  std::cout << r;
}

但是, std :: to_string 不能为您提供对格式的太大控制,因此,如果您需要指定字段宽度或小数点之后的数字或类似的数字,则是最好看到洛尔的答案。

如果您在微控制器上对C ++标准库进行了不完整的实现,因此您不能使用上面的功能,或者您只想避免动态内存分配,请尝试此代码(在C或C ++中有效):

float t = 30.2;
char buffer[80];
sprintf(buffer, "Temperature is %f.", t);

请注意,请注意缓冲区必须足够大,以确保永远不会有缓冲区溢出,并且无法使其足够大可能会导致崩溃和安全问题。

For simple cases, you can just use the std::string class and the std::to_string function, which have both been part of C++ for a long time.

#include <string>
#include <iostream>

int main()
{
  float t = 30.2;
  std::string r = "Temperature is " + std::to_string(t);
  std::cout << r;
}

However, std::to_string doesn't give you much control over the formatting, so if you need to specify a field width or a number of digits after the decimal point or something like that, it would be better to see lorro's answer.

If you have an incomplete implementation of the C++ standard library on your microcontroller so you can't use the functions above, or maybe you just want to avoid dynamic memory allocation, try this code (which is valid in C or C++):

float t = 30.2;
char buffer[80];
sprintf(buffer, "Temperature is %f.", t);

Note that buffer must be large enough to guarantee there will never be a buffer overflow, and failing to make it large enough could cause crashes and security issues.

如何con弦和浮动

和我恋爱吧 2025-02-18 23:57:30

选择除pandas dataframe

df.loc [:,df.columns!=&lt; column&gt;] 的所有列以外的所有列。

To select all columns except one column in Pandas DataFrame

df.loc[:, df.columns != <column name>]

如何将操作G应用于DataFrame的所有列名,除了PANDAS中的一个名称?

和我恋爱吧 2025-02-18 15:07:50

git格式patch 非常适合提取提交的线性历史记录,但不是为了合并:

描述
用其“补丁” ...

[...]
警告
请注意,即使它们属于请求范围的一部分,格式patch将省略合并

  • 如您在示例中所看到的:

为您的每个提交创建一个补丁程序 enternbranch main ,但没有用于合并提交,如果您检查了Pacthes,则他们不包含信息以指出他们俩都有相同的父母。

这不足以自动重建与合并的历史记录。


在保存分支和合并的同时,可能有几种策略可以从 repo-a repo-b ,但我们需要更多的上下文来为您提供更精确的上下文回答。

例如:一种方法可以是将 repo-a 添加为 repo-b 中的远程,并使用 git rebase -r (<代码> -r 是的简短 - rebase-merges )或 git> git filter-repo 的某些子命令到端口完整的历史记录块。


如果要从repo-a中删除文件,但可以显示其余文件的历史记录,则可以使用 git filter-repo repo-a repo-a 变成剥离版本。上行是该命令以可重复的方式创建提交,因此新提交的历史记录与先前的提取相匹配。

git format-patch is well suited to extract a linear history of commits, but not for merges :

DESCRIPTION
Prepare each non-merge commit with its "patch" ...

[...]
CAVEATS
Note that format-patch will omit merge commits from the output, even if they are part of the requested range.

  • as you can see in your example :

a patch is created for each of your commits on anotherbranch and main, but none for the merge commit, and if you inspect the pacthes, they do not include information to state that they both have the same parent.

This is not enough information to automatically rebuild a history with merges.


There may be several strategies to port commits from repo-a to repo-b while preserving branching and merges, but we would need a bit more context to give you a more precise answer.

For example : one way could be to add repo-a as a remote in repo-b, and use git rebase -r (-r is short for --rebase-merges) or some subcommand of git filter-repo to port complete chunks of history.


If you want to remove files from repo-a, but are okay with presenting the history for the remaining files, you could use git filter-repo to turn repo-a into a stripped down version. The upside would be that this command creates commits in a repeatable way, so the history for new commits would match the previous extraction.

git格式点和分支冲突

和我恋爱吧 2025-02-18 11:58:36

将其分为三个步骤。

  1. 准备:获取数据 +缓存数据
const fetchResult = fetch(...).then(response => response.json());
  1. 构建列表(使用ID来识别记录!)

fetchResult.then(data => {
  // Create select list
    const mainEl = document.querySelector('.container');
    let selectList = document.createElement('select');
    selectList.id = 'selectorList';
    mainEl.appendChild(selectList);

    data.forEach(employee => {
      const option = document.createElement('option');
      option.value = employee.id;
      option.text = employee.lastName;
      selectList.appendChild(option);
    });

    let selectList.addEventListener('change', e => {
      selectorChoice = parseInt(e.target.value);
      handleUserChoice(data, selectorChoice)
    });
  }
)

  1. 根据 id 处理用户选择
function handleUserChoice(data, id) {
    const chosenEmployee = data.find(e => e.id === id);
    
    if (choosenEmployee) {
      // ... do what you want here!
    }
}

Break this into three steps.

  1. Prepare: Fetch data + cache data
const fetchResult = fetch(...).then(response => response.json());
  1. Build list (use id to identify records!)

fetchResult.then(data => {
  // Create select list
    const mainEl = document.querySelector('.container');
    let selectList = document.createElement('select');
    selectList.id = 'selectorList';
    mainEl.appendChild(selectList);

    data.forEach(employee => {
      const option = document.createElement('option');
      option.value = employee.id;
      option.text = employee.lastName;
      selectList.appendChild(option);
    });

    let selectList.addEventListener('change', e => {
      selectorChoice = parseInt(e.target.value);
      handleUserChoice(data, selectorChoice)
    });
  }
)

  1. Handle user choice based on id
function handleUserChoice(data, id) {
    const chosenEmployee = data.find(e => e.id === id);
    
    if (choosenEmployee) {
      // ... do what you want here!
    }
}

等到eventlistener被要求返回承诺

和我恋爱吧 2025-02-18 01:32:07

在这些情况下,最常见的错误是呈现组件已被渲染,并在某些毫秒后加载了道具。
因此,该组件第一次尝试渲染选择组件,但是尚未初始化道具,您会看到此错误。

在这种情况下,如果填补了这种道具的延迟,则应使用这样的STH

{props.legs && props.legs.secondClassCalmPrices ?
<Select
                        labelId="demo-simple-select-standard-label"
                        id="demo-simple-select-standard"
                        value={props.legs.secondClassCalmPrices}
                        label="ticket type"
                        variant="standard"
                        className="calm-class-select"
                      >
                        {props.legs.secondClassCalmPrices.map((info) => {
                          return <MenuItem>{info}</MenuItem>;
                        })}
                      </Select>
: null}

The most common error in these situations is that component has been rendered and some milliseconds later the props are loaded.
So the very first time the component tries to render the Select component, but props are not initialized yet and you see this error.

In such cases, where there is this delay of props being filled, you should use sth like this

{props.legs && props.legs.secondClassCalmPrices ?
<Select
                        labelId="demo-simple-select-standard-label"
                        id="demo-simple-select-standard"
                        value={props.legs.secondClassCalmPrices}
                        label="ticket type"
                        variant="standard"
                        className="calm-class-select"
                      >
                        {props.legs.secondClassCalmPrices.map((info) => {
                          return <MenuItem>{info}</MenuItem>;
                        })}
                      </Select>
: null}

无法使用地图循环数据

和我恋爱吧 2025-02-17 13:24:52

这就是所谓的“混合”
英特尔的内在指南小组融合说明“ nofollow noreferrer”>在“ swizzle”类别下,以及与夏普斯(Shizzle)类别。

您正在寻找sse4.1 blendvps (intinsic _mm_blendv_ps )。其他元素大小为 _mm_blendv_pd _mm_blendv_epi8 。这些使用相应元素的高位作为控件,因此您可以直接使用float(没有 _mm_cmp_ps ),如果其符号位很有趣。

__m128i mask = _mm_castps_si128(_mm_cmplt_ps(x, y));   // integer 0 / -1 bit patterns
__m128 c = _mm_blendv_ps(b, a, mask);  // copy element from 2nd op where the mask is set

请注意,我将 a,b 转换为 b,a ,因为SSE混合物将元素从第二个操作数中删除,以设置掩码的位置。就像有条件的移动,在条件为真时复制。如果您将您的常数 /变量命名,则可以编写 Blend(A,B,Mask)< / code>,而不是使它们向后。或给他们有意义的名称行 Ones


在其他情况下,您的控制操作数为常数,也有 _mm_blend_ps /pd/ _mm_blend_epi16 (一个8--位直接操作数只能控制8个单独的元素,因此8x 2字节。)

performance

Blendps XMM,XMM,IMM8 是Intel CPU上任何矢量Alu端口的单uop指令,如<代码> andps 。 ( https://uops.info/ )。 pblendw 也是单uop,但仅在英特尔的端口5上运行,并与Shuffles竞争。 AVX2 VPBlendd 与dword granularity, vblendps 的整数版本以及相同的效率相同。 Intel CPU上具有额外的旁路延迟。

(这是一项整数 - simd指令;与随机相比,如果您混合整数和fp simd,则混合物在 5)。不幸的是,AVX版本( vblendvps )仍然是Intel上的2个UOP(Alder Lake-P上的3个,Alder Lake-e上4个)。尽管UOPS至少可以在3个矢量Alu端口中的任何一个上运行。

vblendvps 版本在ASM中很时髦,因为它具有4个操作数,而不是覆盖任何输入寄存器。 (非AVX版本覆盖一个输入,并隐式使用XMM0作为掩码输入。)Intel UOPS显然无法处理4个单独的寄存器,只有3个用于FMA, ADC cmov 。 (和avx-512 vpternlogd 可以在单个UOP 中进行比切的混合物)

AMD具有完全有效的 vblendvps ,单个UOP(除外)对于Zen1上的YMM),带2/时钟吞吐量。


效仿

没有SSE4.1,您可以使用Andn/and/或(X&amp; bask) | (y&amp; bask)等于 _mm_blendv_ps(x,y,bask),除了它是纯粹的位,因此每个掩码元素的所有位都应匹配顶部位。 (例如,比较结果,或用 _mm_srai_epi32(bask,31)。)

编译器知道此技巧,如果您在没有任何ARCH选项(如<代码> -March = Haswell 或其他。 (SSE4.1在第二代核心2中是新的,因此它越来越广泛,但不是

通用 ^ y)&amp;如果您可以重复使用 x ^ y (在AKI中建议)。级别的平行性。

没有AVX的非毁灭性3-动作指令,此方式将需要一个移动XMM,XMM register-copy来保存 b mask 而不是 a 。 Andn销毁掩码( 〜mask&amp; x )。

用 关心AMD,如果可以预先计算 A^B ,您仍然可以选择一个和/XOR

。代码>

(适用于整数和FP; 0.0F 0.0 的位模式是全元素,与整数 0 。)

您无需复制零从任何地方,只有 x&amp; mask x&amp; 〜mask

(x&amp; 〜mask)|(y&amp; mask)表达式减少为x = 0或y = 0;该项变为零, z | = 0 < /code>是一个no-op

。 x +y:x ,将添加和混合的延迟放在关键路径上,您可以根据掩码 x +=选择y或零> x += y&amp; mask; 或做相反的事情, x += 〜mask&amp; y 使用 _mm_andn_ps(bask,vy)

这具有添加和一个操作(因此已经比某些CPU上的混合物便宜,并且您不需要在另一台寄存器中使用0.0源操作数)。另外,如果您是在循环中使用+= 操作,则通过 x 现在仅包括+= 操作独立 y&amp;蒙版。例如,仅将数组的元素匹配, sum += a [i]&gt; = thresh? a [i]:0.0f;

,示例是由于不必要地延长关键路径而导致额外放缓的示例,请参见 gcc优化flag -o3使代码比-o2 gcc的标量ASM使用 cmov 具有该缺陷,执行 cmov 作为循环依赖链的一部分,而不是准备 0 arr [i] 输入它。

如果您想要

a&lt;上?答:上,您可以用 _mm_min_ps 而不是 cmpps / blendvps 。 (类似地, _mm_max_ps _mm_min_pd / _mm_max_pd 。)

请参见有关其确切语义的详细信息,什么指令给出了什么指令? ,包括一个长期存在的(但最近固定)的GCC错误,其中FP内含物没有提供预期的严格FP语义,如果一个人是Nan,则可以保留哪种操作数。

或对于整数,SSE2是高度非正交的(iNT16_T的签名最小/最大,UINT8_T的未签名最小/最大)。类似于饱和包说明。 SSE4.1填充缺失的操作数大小和签名组合。

  • 签名:sse2 _mm_max_epi16 (以及所有这些的相应 min s)
    • sse4.1 _mm_max_epi32 / _mm_max_epi8 ; avx-512 _mm_max_epi64
  • unsigned:sse2 _mm_max_epu8
    • sse4.1 _mm_max_epu16 / _mm_max_epu32 ; avx-512 _mm_max_epu64

avx-512使蒙版/混合一流操作

AVX-512比较掩码寄存器, k0..k7..K7..K7..K7..K7 (内部类型 __ MMASK1616161616161616 等)。合并屏蔽或零掩蔽可能是大多数ALU指令的一部分。还有一个专用的混合说明,可以根据口罩融合。

我不会在这里详细介绍,可以说如果您有很多有条件的事情要做,AVX-512很棒(即使您仅使用256位矢量来避免涡轮时钟速度惩罚等等。)您将需要专门阅读AVX-512的详细信息。

That's called a "blend".
Intel's intrinsics guide groups blend instructions under the "swizzle" category, along with shuffles.

You're looking for SSE4.1 blendvps (intrinsic _mm_blendv_ps). The other element sizes are _mm_blendv_pd and _mm_blendv_epi8. These use the high bit of the corresponding element as the control, so you can use a float directly (without _mm_cmp_ps) if its sign bit is interesting.

__m128i mask = _mm_castps_si128(_mm_cmplt_ps(x, y));   // integer 0 / -1 bit patterns
__m128 c = _mm_blendv_ps(b, a, mask);  // copy element from 2nd op where the mask is set

Note that I reversed a, b to b, a because SSE blends take the element from the 2nd operand in positions where the mask was set. Like a conditional-move which copies when the condition is true. If you name your constants / variables accordingly, you can write blend(a,b, mask) instead of having them backwards. Or give them meaningful names line ones and twos.


In other cases where your control operand is a constant, there's also _mm_blend_ps / pd / _mm_blend_epi16 (an 8-bit immediate operand can only control 8 separate elements, so 8x 2-byte.)

Performance

blendps xmm, xmm, imm8 is a single-uop instruction for any vector ALU port on Intel CPUs, as cheap as andps. (https://uops.info/). pblendw is also single-uop, but only runs on port 5 on Intel, competing with shuffles. AVX2 vpblendd blends with dword granularity, an integer version of vblendps, and with the same very good efficiency. (It's an integer-SIMD instruction; unlike shuffles, blends have extra bypass latency on Intel CPUs if you mix integer and FP SIMD.)

But variable blendvps is 2 uops on Intel before Skylake (and only for port 5). And the AVX version (vblendvps) is unfortunately still 2 uops on Intel (3 on Alder Lake-P, 4 on Alder Lake-E). Although the uops can at least run on any of 3 vector ALU ports.

The vblendvps version is funky in asm because it has 4 operands, not overwriting any of the inputs registers. (The non-AVX version overwrites one input, and uses XMM0 implicitly as the mask input.) Intel uops apparently can't handle 4 separate registers, only 3 for stuff like FMA, adc, and cmov. (And AVX-512 vpternlogd which can do a bitwise blend as a single uop)

AMD has fully efficient handling of vblendvps, single uop (except for YMM on Zen1) with 2/clock throughput.


Without SSE4.1, you can emulate with ANDN/AND/OR

(x&~mask) | (y&mask) is equivalent to _mm_blendv_ps(x,y,mask), except it's pure bitwise so all the bits of each mask element should match the top bit. (e.g. a compare result, or broadcast the top bit with _mm_srai_epi32(mask, 31).)

Compilers know this trick and will use it when auto-vectorizing scalar code if you compile without any arch options like -march=haswell or whatever. (SSE4.1 was new in 2nd-gen Core 2, so it's increasingly widespread but not universal.)

For constant / loop-invariant a^b without SSE4.1

x ^ ((x ^ y) & mask saves one operation if you can reuse x ^ y. (Suggested in comments by Aki). Otherwise this is worse, longer critical-path latency and no instruction-level parallelism.

Without AVX non-destructive 3-operand instructions, this way would need a movaps xmm,xmm register-copy to save b, but it can choose to destroy the mask instead of a. The AND/ANDN/OR way would normally destroy its 2nd operand, the one you use with y&mask, and destroy the mask with ANDN (~mask & x).

With AVX, vblendvps is guaranteed available. Although if you're targeting Intel (especially Haswell) and don't care about AMD, you might still choose an AND/XOR if a^b can be pre-computed.

Blending with 0: just AND[N]

(Applies to integer and FP; the bit-pattern for 0.0f and 0.0 is all-zeros, same as integer 0.)

You don't need to copy a zero from anywhere, just x & mask, or x & ~mask.

(The (x & ~mask) | (y & mask) expression reduces to this for x=0 or y=0; that term becomes zero, and z|=0 is a no-op.)

For example, to implement x = mask ? x+y : x, which would put the latency of an add and blend on the critical path, you simplify to x += select y or zero according to mask, i.e. to x += y & mask; Or to do the opposite, x += ~mask & y using _mm_andn_ps(mask, vy).

This has an ADD and an AND operation (so already cheaper than blend on some CPUs, and you don't need a 0.0 source operand in another register). Also, the dependency chain through x now only includes the += operation, if you were doing this in a loop with loop-carried x but independent y & mask. e.g. summing only matching elements of an array, sum += A[i]>=thresh ? A[i] : 0.0f;

For an example of an extra slowdown due to lengthening the critical path unnecessarily, see gcc optimization flag -O3 makes code slower than -O2 where GCC's scalar asm using cmov has that flaw, doing cmov as part of the loop-carried dependency chain instead of to prepare a 0 or arr[i] input for it.

Clamping to a MIN or MAX

If you want something like a < upper ? a : upper, you can do that clamping in one instruction with _mm_min_ps instead of cmpps / blendvps. (Similarly _mm_max_ps, and _mm_min_pd / _mm_max_pd.)

See What is the instruction that gives branchless FP min and max on x86? for details on their exact semantics, including a longstanding (but recently fixed) GCC bug where the FP intrinsics didn't provide the expected strict-FP semantics of which operand would be the one to keep if one was NaN.

Or for integer, SSE2 is highly non-orthogonal (signed min/max for int16_t, unsigned min/max for uint8_t). Similar for saturating pack instructions. SSE4.1 fills in the missing operand-size and signedness combinations.

  • Signed: SSE2 _mm_max_epi16 (and corresponding mins for all of these)
    • SSE4.1 _mm_max_epi32 / _mm_max_epi8; AVX-512 _mm_max_epi64
  • Unsigned: SSE2 _mm_max_epu8
    • SSE4.1 _mm_max_epu16 / _mm_max_epu32; AVX-512 _mm_max_epu64

AVX-512 makes masking/blending a first-class operation

AVX-512 compares into a mask register, k0..k7 (intrinsic types __mmask16 and so on). Merge-masking or zero-masking can be part of most ALU instructions. There is also a dedicated blend instruction that blends according to a mask.

I won't go into the details here, suffice it to say if you have a lot of conditional stuff to do, AVX-512 is great (even if you only use 256-bit vectors to avoid the turbo clock speed penalties and so on.) And you'll want to read up on the details for AVX-512 specifically.

SSE Interleave/Merge/合并2个向量,使用掩码,每个元素的条件移动?

和我恋爱吧 2025-02-16 07:47:53
select max(t.salary) as salary 
from(
    SELECT department_id AS `department Id`, SUM(salary) AS `salary`
    FROM EMPLOYEES
    GROUP BY department_id
) AS t
select max(t.salary) as salary 
from(
    SELECT department_id AS `department Id`, SUM(salary) AS `salary`
    FROM EMPLOYEES
    GROUP BY department_id
) AS t

如何从SQL中的子查询中选择最大值?

和我恋爱吧 2025-02-16 05:52:46

也许您的文本数据包含&amp;&lt; ?尝试以下操作:

    let result_string = result
      .join('\n')
      .replace(/&/g, '&')
      .replace(/</g, '<')
      .replace(/>/g, '>');

请参阅在Slack Api参考中逃脱的文本

您还应该在数据中搜索可能会在工作中抛出扳手的标记符号。

Perhaps your text data contains &<>? Try this:

    let result_string = result
      .join('\n')
      .replace(/&/g, '&')
      .replace(/</g, '<')
      .replace(/>/g, '>');

See Escaping text at Slack API reference.

You should also search your data for markdown symbols that could throw a spanner in the works.

是否有原因为什么通知脚本突然开始抛出Slack API代码400:无效的块?

和我恋爱吧 2025-02-15 16:22:13

您可以使用管道轻松地做到这一点 -


class BotPipeline:
    def process_item(self, item, spider):
        if item['category'] == 'business':
            # insert db operation with this filtered item
            return item
        if item['category'] == 'sports':
            # insert db operation with this filtered item
            return item

You can easily do that using your pipeline -


class BotPipeline:
    def process_item(self, item, spider):
        if item['category'] == 'business':
            # insert db operation with this filtered item
            return item
        if item['category'] == 'sports':
            # insert db operation with this filtered item
            return item

使用过滤条件将刮擦数据保存在不同词典中

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

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