痴情

文章 评论 浏览 30

痴情 2025-02-16 10:16:13

您可以 Extend

interface List {
  name: string //without adding id here
}

interface ListId extends List {
  id: string
}

interface ListData {
  type: string
  lists: ListId[]
}

const data: ListData = {
  type: 'something',
  lists: [{
    id: '1',
    name: 'alice'
  }, {
    id: '2',
    name: 'ja'
  }]
}

You can extend the List interface

interface List {
  name: string //without adding id here
}

interface ListId extends List {
  id: string
}

interface ListData {
  type: string
  lists: ListId[]
}

const data: ListData = {
  type: 'something',
  lists: [{
    id: '1',
    name: 'alice'
  }, {
    id: '2',
    name: 'ja'
  }]
}

扩展对象的打字稿数组,而无需修改源

痴情 2025-02-16 09:20:52

尝试这个奇怪的例子。在下面的示例中,如果A是在0初始初始化的数字,则您会看到0,然后是1。除了A是对象,JavaScript将通过F1传递A的指针,而不是它的副本。结果是您两次都会获得相同的警报。

var a = new Date();
function f1(b)
{
    b.setDate(b.getDate()+1);
    alert(b.getDate());
}
f1(a);
alert(a.getDate());

Try this curious example. In the example below if a were a numeric initialized at 0, you'd see 0 and then 1. Except a is an object and javascript will pass f1 a pointer of a rather than a copy of it. The result is that you get the same alert both times.

var a = new Date();
function f1(b)
{
    b.setDate(b.getDate()+1);
    alert(b.getDate());
}
f1(a);
alert(a.getDate());

JavaScript中变量的范围是什么?

痴情 2025-02-16 04:54:32

ActiveMQ“ Classic”不支持专门为主或从属配置经纪人的概念。您只需配置2个经纪人以使用相同的共享存储(无论是磁盘还是数据库),并且哪个经纪人首先获得锁定的是主经纪人,并保持主体经纪人直到失败为止。

您需要使用 activemq artemis 和配置“ nofollow noreferrer”> fofalback 支持您的用例。

ActiveMQ "Classic" doesn't support the notion of configuring a broker specifically as a master or a slave. You simply configure 2 brokers to use the same shared storage (whether that's disk or database) and whichever broker gets the lock first is the master broker and stays the master broker until it fails.

You'd need to use ActiveMQ Artemis and configure failback to support your use-case.

用MySQL在ActiveMQ共享JDBC存储中将经纪人定义为Master

痴情 2025-02-16 04:00:13

一般多边形区域的直接应用(参见 shoelace公式)简单而快速,矢量化计算:

def area(p):
    # for p: 2D vertices of a polygon:
    # area = 1/2 abs(sum(p0 ^ p1 + p1 ^ p2 + ... + pn-1 ^ p0))
    # where ^ is the cross product
    return np.abs(np.cross(p, np.roll(p, 1, axis=0)).sum()) / 2

在两条曲线之间的区域应用。在此示例中,我们甚至没有匹配的X坐标!

np.random.seed(0)
n0 = 10
n1 = 15
xy0 = np.c_[np.linspace(0, 10, n0), np.random.uniform(0, 10, n0)]
xy1 = np.c_[np.linspace(0, 10, n1), np.random.uniform(0, 10, n1)]

p = np.r_[xy0, xy1[::-1]]
>>> area(p)
4.9786...

图:

plt.plot(*xy0.T, 'b-')
plt.plot(*xy1.T, 'r-')
p = np.r_[xy0, xy1[::-1]]
plt.fill(*p.T, alpha=.2)

速度

两种曲线具有100万点的

n = 1_000_000
xy0 = np.c_[np.linspace(0, 10, n), np.random.uniform(0, 10, n)]
xy1 = np.c_[np.linspace(0, 10, n), np.random.uniform(0, 10, n)]

%timeit area(np.r_[xy0, xy1[::-1]])
# 42.9 ms ± 140 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

:多边形区域计算的简单效果

# say:
p = np.array([[0, 3], [1, 0], [3, 3], [1, 3], [1, 2]])

p_closed = np.r_[p, p[:1]]
fig, axes = plt.subplots(ncols=2, figsize=(10, 5), subplot_kw=dict(box_aspect=1), sharex=True)
ax = axes[0]
ax.set_aspect('equal')
ax.plot(*p_closed.T, '.-')
ax.fill(*p_closed.T, alpha=0.6)
center = p.mean(0)
txtkwargs = dict(ha='center', va='center')
ax.text(*center, f'{area(p):.2f}', **txtkwargs)
ax = axes[1]
ax.set_aspect('equal')
for a, b in zip(p_closed, p_closed[1:]):
    ar = 1/2 * np.cross(a, b)
    pos = ar >= 0
    tri = np.c_[(0,0), a, b, (0,0)].T
    # shrink a bit to make individual triangles easier to visually identify
    center = tri.mean(0)
    tri = (tri - center)*0.95 + center
    c = 'b' if pos else 'r'
    ax.plot(*tri.T, 'k')
    ax.fill(*tri.T, c, alpha=0.2, zorder=2 - pos)
    t = ax.text(*center, f'{ar:.1f}', color=c, fontsize=8, **txtkwargs)
    t.set_bbox(dict(facecolor='white', alpha=0.8, edgecolor='none'))

plt.tight_layout()

//i.sstatic.net/hqyg3.png“ alt =”在此处输入图像描述”>

A straightforward application of the area of a general polygon (see Shoelace formula) makes for a super-simple and fast, vectorized calculation:

def area(p):
    # for p: 2D vertices of a polygon:
    # area = 1/2 abs(sum(p0 ^ p1 + p1 ^ p2 + ... + pn-1 ^ p0))
    # where ^ is the cross product
    return np.abs(np.cross(p, np.roll(p, 1, axis=0)).sum()) / 2

Application to area between two curves. In this example, we don't even have matching x coordinates!

np.random.seed(0)
n0 = 10
n1 = 15
xy0 = np.c_[np.linspace(0, 10, n0), np.random.uniform(0, 10, n0)]
xy1 = np.c_[np.linspace(0, 10, n1), np.random.uniform(0, 10, n1)]

p = np.r_[xy0, xy1[::-1]]
>>> area(p)
4.9786...

Plot:

plt.plot(*xy0.T, 'b-')
plt.plot(*xy1.T, 'r-')
p = np.r_[xy0, xy1[::-1]]
plt.fill(*p.T, alpha=.2)

Speed

For both curves having 1 million points:

n = 1_000_000
xy0 = np.c_[np.linspace(0, 10, n), np.random.uniform(0, 10, n)]
xy1 = np.c_[np.linspace(0, 10, n), np.random.uniform(0, 10, n)]

%timeit area(np.r_[xy0, xy1[::-1]])
# 42.9 ms ± 140 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

Simple viz of polygon area calculation

# say:
p = np.array([[0, 3], [1, 0], [3, 3], [1, 3], [1, 2]])

p_closed = np.r_[p, p[:1]]
fig, axes = plt.subplots(ncols=2, figsize=(10, 5), subplot_kw=dict(box_aspect=1), sharex=True)
ax = axes[0]
ax.set_aspect('equal')
ax.plot(*p_closed.T, '.-')
ax.fill(*p_closed.T, alpha=0.6)
center = p.mean(0)
txtkwargs = dict(ha='center', va='center')
ax.text(*center, f'{area(p):.2f}', **txtkwargs)
ax = axes[1]
ax.set_aspect('equal')
for a, b in zip(p_closed, p_closed[1:]):
    ar = 1/2 * np.cross(a, b)
    pos = ar >= 0
    tri = np.c_[(0,0), a, b, (0,0)].T
    # shrink a bit to make individual triangles easier to visually identify
    center = tri.mean(0)
    tri = (tri - center)*0.95 + center
    c = 'b' if pos else 'r'
    ax.plot(*tri.T, 'k')
    ax.fill(*tri.T, c, alpha=0.2, zorder=2 - pos)
    t = ax.text(*center, f'{ar:.1f}', color=c, fontsize=8, **txtkwargs)
    t.set_bbox(dict(facecolor='white', alpha=0.8, edgecolor='none'))

plt.tight_layout()

enter image description here

在matplotlib(填充区域之间)绘制的两条曲线之间找到区域

痴情 2025-02-15 16:59:42

尽管HashCode对您的业务逻辑没有任何作用,但在大多数情况下,我们必须照顾它。因为当将对象放入基于哈希的容器中( hashset hashmap ...)时,容器puts/for元素的哈希码。

Although hashcode does nothing with your business logic, we have to take care of it in most cases. Because when your object is put into a hash based container(HashSet, HashMap...), the container puts/gets the element's hashcode.

Java中的哈希码的用途是什么?

痴情 2025-02-15 12:57:20

JavaScript的我发现来自一本关于

JavaScript的“自动半插入”规则是奇怪的。如果其他语言假设大多数新线是有意义的,并且在多行语句中只能忽略少数语言,则JS假定相反。除非遇到解析错误,否则它将所有新线视为毫无意义的空格。如果是这样,它会返回并尝试将以前的newline变成半隆以获得语法有效的东西。

他继续描述它,就像您代码气味

如果我完整地详细介绍了它的工作方式,那么这个设计说明就会变成设计的次数,而少于一个坏主意的所有各种方式。这是一团糟。 JavaScript是我知道的唯一一种语言,即使语言理论上可以让您掌握它们。

The most contextual description of JavaScript's Automatic Semicolon Insertion I have found comes from a book about Crafting Interpreters.

JavaScript’s “automatic semicolon insertion” rule is the odd one. Where other languages assume most newlines are meaningful and only a few should be ignored in multi-line statements, JS assumes the opposite. It treats all of your newlines as meaningless whitespace unless it encounters a parse error. If it does, it goes back and tries turning the previous newline into a semicolon to get something grammatically valid.

He goes on to describe it as you would code smell.

This design note would turn into a design diatribe if I went into complete detail about how that even works, much less all the various ways that that is a bad idea. It’s a mess. JavaScript is the only language I know where many style guides demand explicit semicolons after every statement even though the language theoretically lets you elide them.

JavaScript自动插入(ASI)的规则是什么?

痴情 2025-02-14 20:30:23

简短的答案是您不能。您需要使用 line_items 并通过价格对象ID( PRISE_XXX )或使用 Price_data 参数使用临时定价。然后,结帐将计算所有订单项中的总数,以任何您提供的。

您有几个选项可以实现所需的行为:

  • 重新计算 PRICE_DATA.UNIT_AMOUNT 值,以反映客户所应用的折扣。
  • 利用条纹优惠券适用于结帐会话为你。

Short answer is that you can't. You need to use the line_items parameter and either pass a Price object ID (price_xxx) or use ad-hoc pricing with the price_data parameter. Checkout will then compute the total from all line items, factoring in any discounts that you provide.

You have a couple of options to achieve the behaviour you want:

  • Re-calculate the price_data.unit_amount value to reflect the discount applied by your customers.
  • Utilise Stripe coupons to apply to the Checkout Session which will take care of the dedication for you.

Stripe Checkout会话总价,而不是Unit_price

痴情 2025-02-14 10:07:16

从您的问题标题中猜测(如何检查数组是否包含一个值,但以串联为单位),据我了解,这是一个很好的解决方案。

def check_substring(string, letters):
    word = list(string)
    return any(letters == word[i:i+2] for i in range(len(word) - 1))


word = "hello"
print(check_substring(word, ["h","e"]))

Guessing from your question title (how to check if array contains a value but in series), this is a great solution for your problem, as far as I understand it.

def check_substring(string, letters):
    word = list(string)
    return any(letters == word[i:i+2] for i in range(len(word) - 1))


word = "hello"
print(check_substring(word, ["h","e"]))

python-如何检查数组是否包含值,但串联

痴情 2025-02-13 22:04:50

我也有同样的问题。事实证明,当我从测试JS脚本发送消息时,Stomp.js并未自动将传递的对象序列化作为消息主体传递给JSON,而是仅将其施加到字符串中,然后发送“ [[[对象]” 作为有效载荷,杰克逊(Jackson)将其解释为数组,因为 [在前面,并且立即失败,因为它没想到会收到一个数组。

client.publish({
  destination: '/app/publish',
  body: {
    id: 0,
    content: 'I am very frustrated',
    sender: 'test_user',
    chat: 0
  }
}); // => "[Object object]"

作为有效载荷做的事情,在将其传递之前,明确对对象进行序列化:

client.publish({
  destination: '/app/publish',
  body: JSON.stringify({
    id: 0,
    content: 'I am very frustrated',
    sender: 'test_user',
    chat: 0
  })
}); // => {id: 0, ...}

问题一直是JavaScript。

I had the same issue. Turns out, as I was sending messages from a test JS script, Stomp.js didn't automatically serialize the object passed as the message body to JSON, what it did instead was just cast it to a string and send "[Object object]" as payload, which Jackson interpreted as an array because of the [ in front, and immediately failed because it didn't expect to receive an array.

client.publish({
  destination: '/app/publish',
  body: {
    id: 0,
    content: 'I am very frustrated',
    sender: 'test_user',
    chat: 0
  }
}); // => "[Object object]"

Explicitly serializing the object manually before passing it as payload did the thing:

client.publish({
  destination: '/app/publish',
  body: JSON.stringify({
    id: 0,
    content: 'I am very frustrated',
    sender: 'test_user',
    chat: 0
  })
}); // => {id: 0, ...}

The issue was Javascript all along.

面对JSON解析问题,无法从阵列值Jackson.databind.exc.mismatchedInputeXception typer'java.lang.string类型的值进行估算。

痴情 2025-02-13 07:15:21

可能是您可以使用该代码的按钮作为EG

---- html -----

<div class="dropdown">
      <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">
      <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1" name="selected" >
      <li><a class="dropdown-item" data-bs-toggle="modal" *ngFor="let option of Menu">
      <button class="btn btn-secondary" type="button" (click)="selectedChanged(option)">{{option}}</button>
       </a></li>
  </ul>
</button>

May be You can use button for that code for e.g

----HTML----

<div class="dropdown">
      <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">
      <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1" name="selected" >
      <li><a class="dropdown-item" data-bs-toggle="modal" *ngFor="let option of Menu">
      <button class="btn btn-secondary" type="button" (click)="selectedChanged(option)">{{option}}</button>
       </a></li>
  </ul>
</button>

如何使用&lt; ul&gt;如何控制选定的下拉选项。 &lt; li&gt;

痴情 2025-02-12 07:58:10

您正在修改(通过调用移动)您要迭代的收集,这可能会导致某些项目被跳过。从 itemss.count 向后使用向后进行循环,向下循环。

You are modifying (by calling Move) the very collection you are iterating over, this can result in some items being skipped. Use a backward for loop from Items.Count down to 1.

重复代码执行或替代方案:Python,Outlook

痴情 2025-02-12 07:14:17

Snowflake确实在CTA上使用订单。您可以看到,通过使用系统$ clustering_information-受到高基数的某些限制以及该功能如何在运行自动群集服务之前至少使用新密钥一次运行群集状态。

但是,仅仅因为Snowflake在CTA中使用订单,这并不意味着无需使用订单子句即可按顺序返回行。 Snowflake是MPP系统,在查询期间将扫描多个小部分。如果没有指定订单,则没有理由优化器应生成保证订单的计划。它生成的计划可以并且将按照他们为结果准备就绪的顺序返回行。

这是一个过于简单的示例:在您按日期订购的CTA上,微分节1的所有行都有日期2022-01-01;微型分支机构中的所有行均具有2022-01-02的日期。当您从该表中选择行时,微分节2的扫描可能与微分节1的可能性一样。如果#2首先结束,则这些行将在结果集中首先成为。

同样,当桌子变大并且比仓库中可用的CPU具有更多的扫描小部分时,将需要一个或多个CPU来扫描多个微型分支。在这种情况下,没有理由希望在另一个小问题上扫描一个微型。

Snowflake does use ORDER BY on a CTAS. You can see that by using the system$clustering_information - subject to some limitations on high cardinality and how the function checks clustering state before it runs the auto clustering service with a new key at least once.

However, just because Snowflake uses the ORDER BY in a CTAS, it doesn't mean the rows will return in order without using an ORDER BY clause. Snowflake is an MPP system and will scan multiple micropartitions during a query. Without specifying an ORDER BY, there is no reason the optimizer should generate a plan that guarantees order. The plan it generates can and will return rows in the order they're ready for the result.

Here's an over-simplistic example: on a CTAS you order by date and all rows in micropartition 1 have date 2022-01-01; all rows in micropartition have date 2022-01-02. When you select rows from that table, the scan for micropartition 2 is just as likely to finish first as micropartition 1 is. If #2 finishes first, those rows will be first in the result set.

Also, when the table becomes large and it has more micropartitions assigned to scan than there are available CPUs in the warehouse, one or more CPUs will need to scan multiple micropartitions. In this case, there's no reason to prefer to scan one micropartition before another.

为什么雪花将表格创建表作为选择(CTA)忽略子句的顺序?

痴情 2025-02-12 06:44:44

我对您的方法了解不多,但这是我使用的内容的广义示例:

dataset = pd.read_csv(filename)                          # Take your df from wherever

with dpg.table(label='DatasetTable'):
    for i in range(dataset.shape[1]):                    # Generates the correct amount of columns
        dpg.add_table_column(label=dataset.columns[i])   # Adds the headers
    for i in range(n):                                   # Shows the first n rows
        with dpg.table_row():
            for j in range(dataset.shape[1]):
                dpg.add_text(f"{dataset.iloc[i,j]}")     # Displays the value of
                                                         # each row/column combination

希望它对某人有用。

I don't know much about your approach but here is a generalized example of what i use:

dataset = pd.read_csv(filename)                          # Take your df from wherever

with dpg.table(label='DatasetTable'):
    for i in range(dataset.shape[1]):                    # Generates the correct amount of columns
        dpg.add_table_column(label=dataset.columns[i])   # Adds the headers
    for i in range(n):                                   # Shows the first n rows
        with dpg.table_row():
            for j in range(dataset.shape[1]):
                dpg.add_text(f"{dataset.iloc[i,j]}")     # Displays the value of
                                                         # each row/column combination

I hope it can be useful to someone.

使用大熊猫填充Dearpygui桌子的有效方法

痴情 2025-02-12 03:30:25

我们可以尝试在此处使用 min 作为分析功能:

SELECT id, CASE WHEN id <> MIN(id) OVER (PARTITION BY fname, lname)
                THEN MIN(id) OVER (PARTITION BY fname, lname) END AS NewId,
       fname, lname
FROM emp
ORDER BY id;

We can try using MIN as an analytic function here:

SELECT id, CASE WHEN id <> MIN(id) OVER (PARTITION BY fname, lname)
                THEN MIN(id) OVER (PARTITION BY fname, lname) END AS NewId,
       fname, lname
FROM emp
ORDER BY id;

如何添加包含一组重复记录的第一个不同记录的ID值的列

痴情 2025-02-11 21:54:45

您的代码有效,因为我认为为什么您看不到.log()的问题是因为您没有达到它。

如果卷轴是(如您所说)“设备的1%ScreenHeight”,则需要HTML高度〜3倍您的屏幕高度;

document.documentElement.style.height = "300vh";

// getting 1% of screen height
const scrollHeight = screen.height / 100; 
const scrollTriggerPoint = scrollHeight * 150;

let point1 = false;

document.addEventListener("scroll", (e) => {
  if (document.documentElement.scrollTop >= scrollTriggerPoint) {
    if (point1 == false){
        point1 = true;
        point1F();
    };
  }
});

function point1F() {
  console.log("u've done it");
}

PS

不要使用以大写字母开头的变量/函数的名称,请在; y上用于构造函数函数或类。

Your code works, as i think the problem why you don't see your .log() is because you didn't reach it.

If scrollHeight is (as you said) "1% of the devices' screenheight", then you need html height to be ~ 3x your screen height;

document.documentElement.style.height = "300vh";

// getting 1% of screen height
const scrollHeight = screen.height / 100; 
const scrollTriggerPoint = scrollHeight * 150;

let point1 = false;

document.addEventListener("scroll", (e) => {
  if (document.documentElement.scrollTop >= scrollTriggerPoint) {
    if (point1 == false){
        point1 = true;
        point1F();
    };
  }
});

function point1F() {
  console.log("u've done it");
}

P.S.

Don't use variable's/function's names starting with a capital letter, use it on;y for constructor functions or classes.

如果我的网页的用户在其上达到某个点,是否可以运行一个函数?

更多

推荐作者

佚名

文章 0 评论 0

今天

文章 0 评论 0

゛时过境迁

文章 0 评论 0

达拉崩吧

文章 0 评论 0

呆萌少年

文章 0 评论 0

孤者何惧

文章 0 评论 0

更多

友情链接

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