城歌

文章 评论 浏览 32

城歌 2025-02-21 02:21:16

您可以使用附加条目方法来跟踪对实体模型的更改。要确定模型您需要所有键

var query = 
  from model in context
  where key == "someKey"
  select new myDTO
  {
    Id = model.Id,
    Item1 = model.column1,
    Item2 = model.column2
  };

var dto = query.First();

// Here I'm using Entity but you should use the right type
var entityyModified = new Entity();
entityModified.Id = dto.Id;
entityyModified.Item1 = dto.Item1;
entityyModified.Item2 = dto.Item2;

// ...
// Item1 or Item2 properties can be assigned to different values
// ...

// Save the changes
context.Attach(entityyModified);
var dbEntry = context.Entry(entityyModified);
dbEntry.Property(e => e.Item1).IsModified = true;
dbEntry.Property(e => e.Item2).IsModified = true;
context.SaveChanges();

You can use Attach and Entry methods to track the changes to a entity model. To identify the model you would need all the keys (here I'm considering only one primary key: Id)

var query = 
  from model in context
  where key == "someKey"
  select new myDTO
  {
    Id = model.Id,
    Item1 = model.column1,
    Item2 = model.column2
  };

var dto = query.First();

// Here I'm using Entity but you should use the right type
var entityyModified = new Entity();
entityModified.Id = dto.Id;
entityyModified.Item1 = dto.Item1;
entityyModified.Item2 = dto.Item2;

// ...
// Item1 or Item2 properties can be assigned to different values
// ...

// Save the changes
context.Attach(entityyModified);
var dbEntry = context.Entry(entityyModified);
dbEntry.Property(e => e.Item1).IsModified = true;
dbEntry.Property(e => e.Item2).IsModified = true;
context.SaveChanges();

如何按实体框架核心选择和更新特定的列?

城歌 2025-02-20 22:09:54

价格过滤器是由saleschannelproductentity :: CheepeStprice生成的,因此请确保还要更改此问题,如文档中所示。

The price filter is generated from SalesChannelProductEntity::cheapestPrice, so make sure to also change this, as indicated in the docs.

Shopware 6-用装饰商修改的价格在产品价格过滤器中无法正常运行

城歌 2025-02-19 14:58:43

您可以使用scaletransform并为其scalexscale> scaley属性进行动画:

<Storyboard x:Key="ExpandingAnimation">
    <Storyboard>
        <DoubleAnimation
            Storyboard.TargetName="MyScaleTransform"
            Storyboard.TargetProperty="(ScaleTransform.ScaleX)"
            From="0" To ="1" Duration="0:0:3"/>
        <DoubleAnimation
            Storyboard.TargetName="MyScaleTransform"
            Storyboard.TargetProperty="(ScaleTransform.ScaleY)"
            From="0" To ="1" Duration="0:0:3"/>
    </Storyboard>
</Storyboard>
...
<Grid x:Name="ExpandingGrid"
              RenderTransformOrigin="0.5,0.5"
              Height="222">
    <Grid.RenderTransform>
        <ScaleTransform x:Name="MyScaleTransform" ScaleX="0" ScaleY ="0" />
    </Grid.RenderTransform>
</Grid>

You could use a ScaleTransform and animate its ScaleX and ScaleY properties:

<Storyboard x:Key="ExpandingAnimation">
    <Storyboard>
        <DoubleAnimation
            Storyboard.TargetName="MyScaleTransform"
            Storyboard.TargetProperty="(ScaleTransform.ScaleX)"
            From="0" To ="1" Duration="0:0:3"/>
        <DoubleAnimation
            Storyboard.TargetName="MyScaleTransform"
            Storyboard.TargetProperty="(ScaleTransform.ScaleY)"
            From="0" To ="1" Duration="0:0:3"/>
    </Storyboard>
</Storyboard>
...
<Grid x:Name="ExpandingGrid"
              RenderTransformOrigin="0.5,0.5"
              Height="222">
    <Grid.RenderTransform>
        <ScaleTransform x:Name="MyScaleTransform" ScaleX="0" ScaleY ="0" />
    </Grid.RenderTransform>
</Grid>

从网格中心扩展动画

城歌 2025-02-19 09:14:52
# Create DataFrame from data dictionary:
# - set_index(0) makes the keys (column 0) the index values
# - .T takes the transpose and makes the index the columns
# .reset_index(drop=True) resets index to 0 (1 row DataFrame) and drops old index
df = pd.DataFrame(data.items()).set_index(0).T.reset_index(drop=True)

# Select first 3 columns to keep as is
df = df[['calories', 'cautions', 'dietLabels']]

# For loop logic to create all other columns
# Since not all keys from totalNutrients are wanted, they must be selected in col_list
col_list = ['CA', 'CHOLE', 'FAT', 'FE', 'FIBTG', 'K', 'MG', 'NA', 'PROCNT', 'SUGAR', 'VITC']
value_list = []

# For each key and value (dictionary) in data['totalNutrients']
for key, value in data['totalNutrients'].items():
    # If key is in col_list
    if key in col_list:
        # Add value to value_list
        value_list.append(value['quantity'])
        
# Create dictionary of columns and values using zip()
clean_data_dict = dict(zip(col_list, value_list))

# Concatenate df with new DataFrame on the same index. axis=1 to concatenate on columns
df = pd.concat([df, pd.DataFrame(clean_data_dict, index=[0])], axis=1)

print(df)

可选的

# To run the API multiple times and store each run:
# - Try loading data.csv
# - Add new data row to main_df and overwrite
# - If the file is not found then save first run df
try:
    main_df = pd.read_csv('data.csv')
    main_df = pd.concat([main_df, df])
    main_df.reset_index(drop=True, inplace=True)
    print(main_df)
    main_df.to_csv('data.csv', index=False)
except FileNotFoundError:
    df.to_csv('data.csv', index=False)

可选

# To change the column names at the end you can repeat the zip process
new_col_list = ['calories', 'cautions', 'diet_labels', 'calcium', 'cholesterol', 'fat', 'iron', 'dietary_fiber', 'potasssium', 'magnesium', 'sodium', 'protein', 'sugar', 'vitamin_c']

col_dict = dict(zip(col_list, new_col_list))

# .rename() uses a dict to map old column names to new column names
df.rename(columns=col_dict)

print(df)
# Create DataFrame from data dictionary:
# - set_index(0) makes the keys (column 0) the index values
# - .T takes the transpose and makes the index the columns
# .reset_index(drop=True) resets index to 0 (1 row DataFrame) and drops old index
df = pd.DataFrame(data.items()).set_index(0).T.reset_index(drop=True)

# Select first 3 columns to keep as is
df = df[['calories', 'cautions', 'dietLabels']]

# For loop logic to create all other columns
# Since not all keys from totalNutrients are wanted, they must be selected in col_list
col_list = ['CA', 'CHOLE', 'FAT', 'FE', 'FIBTG', 'K', 'MG', 'NA', 'PROCNT', 'SUGAR', 'VITC']
value_list = []

# For each key and value (dictionary) in data['totalNutrients']
for key, value in data['totalNutrients'].items():
    # If key is in col_list
    if key in col_list:
        # Add value to value_list
        value_list.append(value['quantity'])
        
# Create dictionary of columns and values using zip()
clean_data_dict = dict(zip(col_list, value_list))

# Concatenate df with new DataFrame on the same index. axis=1 to concatenate on columns
df = pd.concat([df, pd.DataFrame(clean_data_dict, index=[0])], axis=1)

print(df)

OPTIONAL

# To run the API multiple times and store each run:
# - Try loading data.csv
# - Add new data row to main_df and overwrite
# - If the file is not found then save first run df
try:
    main_df = pd.read_csv('data.csv')
    main_df = pd.concat([main_df, df])
    main_df.reset_index(drop=True, inplace=True)
    print(main_df)
    main_df.to_csv('data.csv', index=False)
except FileNotFoundError:
    df.to_csv('data.csv', index=False)

OPTIONAL

# To change the column names at the end you can repeat the zip process
new_col_list = ['calories', 'cautions', 'diet_labels', 'calcium', 'cholesterol', 'fat', 'iron', 'dietary_fiber', 'potasssium', 'magnesium', 'sodium', 'protein', 'sugar', 'vitamin_c']

col_dict = dict(zip(col_list, new_col_list))

# .rename() uses a dict to map old column names to new column names
df.rename(columns=col_dict)

print(df)

如何从带有嵌套词典的API JSON字典中创建数据框?

城歌 2025-02-19 05:40:11

为什么每个线程运行时间都不同,并且每次运行代码时间都不同?线程的运行时间取决于什么?

您的系统上有很多流程。系统上任何内容的运行时间都受内核安排能力的影响,这取决于系统上其他所有内容的活动。获得一致运行时间的唯一方法是使用某种实时内核(或不运行多个进程的嵌入式设备)。

为什么顺序比多线程更快?

使用多个线程很少会为您提供CPU密集型任务的性能优势。由于Python的设计,实际上只有一个线程同时执行。当您尝试并行化IO-BOND操作(例如,通过网络获取数据)时,线程最有用。

对于CPU密集型操作,多处理模块通常是一个更好的选择(因为这会产生Python解释器的多个独立实例,并且可以利用多个CPU),但是在设置和撕裂中涉及的间接费用根据您的工作负载,这些过程使得解决方案没有比单个过程版本更好(甚至更糟)。

Why each thread run time is different and every time I run code time is different ? What does the running time of thread depend on ?

There are a lot of processes running on your system. The runtime of anything on your system is influenced by the kernel's ability to schedule it, which depends on the activity of everything else on the system. The only way to get consistent runtimes is using some sort of realtime kernel (or embedded devices that don't run multiple processes).

Why Sequential is faster than Multithread ?

Using multiple threads will seldom give you a performance advantage for CPU-intensive tasks. Due to the design of Python, only one thread is ever actually executing at the same time. Threads are most useful when you are trying to parallelize IO-bound operations (e.g., fetching data over the network).

For CPU-intensive operations, the multiprocessing module is often a better choice (because this spawns multiple independent instances of the Python interpreter and can take advantage of multiple CPUs), but the overhead involved in setting up and tearing down the processes make the solution no better (or even worse) than the single process version depending on your workload.

为什么每个线程运行时间不同

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

是的,您不能将儿童和儿童财产分配给专栏。专栏将孩子带到[](正方形支架)内部的儿童街区。

Yeah you can't assign both child and children property to a Column. Column takes children so move ElevatedButton to children block inside [](square brackets).

高架按钮在身体条款中不用作为儿童的小部件

城歌 2025-02-18 18:47:37

好吧,有不同的方法可以解决问题。一种方法是使用zipwith订阅可观察到的源的管道操作员,并将其与任何数量的可观察结果输入的值结合使用。 zipwith操作员是RXJS 8的替代zip运算符。您可以做类似的事情:

import { zipWith } from 'rxjs';

private createResult() {
   this.userObservable.getFullName().pipe(
      zipWith(
        this.userObservable.getPhoneNumber(),
        this.userObservable.getEmailAddress()
      ),
      map(([fullName, phoneNumber, emailAddress]) => this.httpService.createSomething(fullName, phoneNumber, emailAddress))
    ).subscribe((result) => console.log(result))
  }

该方法的好处是,您没有将多个订阅彼此嵌套,这可能会导致意想不到的副作用。

well there are different ways of approaching the problem. One way would be to use the zipWith pipe operator that subscribes to a source observable and combines it with the values of any number of observables inputs. The zipWith operator is RxJS 8's replacement for the deprecated zip operator. You could do something similar like:

import { zipWith } from 'rxjs';

private createResult() {
   this.userObservable.getFullName().pipe(
      zipWith(
        this.userObservable.getPhoneNumber(),
        this.userObservable.getEmailAddress()
      ),
      map(([fullName, phoneNumber, emailAddress]) => this.httpService.createSomething(fullName, phoneNumber, emailAddress))
    ).subscribe((result) => console.log(result))
  }

That approach has the benefit that your are not nesting multiple subscriptions inside each other which may lead to unintended side-effects.

将多个观察者值作为方法参数

城歌 2025-02-18 18:30:45

您在正确的轨道上!几件事会有所帮助...

首先,您忽略了输出中的信息,因为求解器说您的配方是不可行的!

Status: Infeasible

因此,变量中出现的任何内容都是胡言乱语,您必须首先弄清楚该部分。

那么,为什么不可行?看看您的约束。您正在尝试 force 如果您的距离值为零,则不可能无法正确:

prob += int(distances[w][b]) * J[w]  >= 1

因此,您需要重新格式化!您在这里缺少一个概念。实际上,对于此问题,您需要2个约束。

  1. 如果路由太长,
  2. 您需要强制涵盖每个目的地,则需要约束源用途的选择。

您还需要一个双重指数的决策变量。为什么?好吧,可以说,来源'a'涵盖了目标1、2; “ B”覆盖2、3、4、5 ....您将能够知道所有目的地都被一个变量“覆盖”,但是您不知道使用了哪些源,因此您需要保持跟踪两者都得到完整的图片。

这是一个开始,还有几个编辑。我建议变量名称source目标,因为这是标准的。在此特定问题中,您没有特定的需求,只是需要连接。您可能还希望使用词典多于嵌套列表,我认为这更清楚。以下是一个示例以第一个约束开始。在限制覆盖变量时,请注意这里的技巧。如果距离小于限制,则s,则可以满足此约束。例如,如果距离为3:

3 * 1 <= s

无论如何,这是建议的开始。另一个约束未实施。您将需要在所有来源上总结,以确保目的地被“覆盖”。如果您被卡住,请回信。

prob = LpProblem('source minimzer', LpMinimize)
dist_limit = 5
sources = ['A', 'B']            # the source locations
# note this is zero-indexed to work with the list indexes in dist dictionary...
destinations = list(range(5))   # the demand locations 0, 1, 2, 3, 4   
dist = {    'A': [2, 23, 30, 54, 1],
            'B': [3, 1, 2, 2, 3]}

covered = LpVariable.dicts('covered', [(s, d) for s in sources for d in destinations], cat='Binary')
# set up constraint to limit covered if the destination is "reachable"
for s in sources:
    for d in destinations:
        prob += covered[s, d] * dist[s][d] <= dist_limit

# add one more constraint to make sure that every destination is "covered"...

You are on the right track! A couple things will help...

First, you overlooked a key piece of information in your output in that the solver says your formulation is INFEASIBLE!

Status: Infeasible

So whatever came out in the variables is gibberish and you must figure that part out first.

So, why is it infeasible? Take a look at your constraint. You are trying to force the impossible if your distance value is zero this cannot be true:

prob += int(distances[w][b]) * J[w]  >= 1

So, you need to reformulate! You are missing a concept here. You actually need 2 constraints for this problem.

  1. You need to constrain the selection of a source-destination if the route is too long
  2. You need to enforce that every destination is covered.

You also need a double-indexed decision variable. Why? Well, lets say that source 'A' covers destination 1, 2; and 'B' covers 2, 3, 4, 5.... You will be able to know that all the destinations are "covered" with one variable, but you will not know which sources were used, so you need to keep track of both to get the full picture.

Here is a start, along with a couple edits. I'd suggest the variable names source and destination as that is kinda standard. You do not have a specific demand in this particular problem, just the need for a connection. You might also want to use dictionaries more than nested lists, I think it is clearer. Below is an example start with the first constraint. Note the trick here in limiting the covered variable. If the distance is less than the limit, s, then this constraint is satisfiable. For instance, if the distance is 3:

3 * 1 <= s

Anyhow, here is a recommended start. The other constraint is not implemented. You will need to sum across all the sources to ensure the destination is "covered". Comment back if your are stuck.

prob = LpProblem('source minimzer', LpMinimize)
dist_limit = 5
sources = ['A', 'B']            # the source locations
# note this is zero-indexed to work with the list indexes in dist dictionary...
destinations = list(range(5))   # the demand locations 0, 1, 2, 3, 4   
dist = {    'A': [2, 23, 30, 54, 1],
            'B': [3, 1, 2, 2, 3]}

covered = LpVariable.dicts('covered', [(s, d) for s in sources for d in destinations], cat='Binary')
# set up constraint to limit covered if the destination is "reachable"
for s in sources:
    for d in destinations:
        prob += covered[s, d] * dist[s][d] <= dist_limit

# add one more constraint to make sure that every destination is "covered"...

无意设施的位置覆盖

城歌 2025-02-18 15:42:28

由于您需要根据您的条件删除和添加频道,因此我提到了一种方法来达到您的要求,它适用于您。

let Channels = {
    "channel-1": "2022-06-29T11:20:14.000Z",
    "channel-2": "2022-06-29T05:58:18.000Z",
    "channel-3": "2022-06-29T05:18:49.000Z",
    "channel-4": "2022-06-29T04:08:35.000Z",
    "channel-5": "2022-06-29T01:52:31.000Z",
    "channel-6": "2022-06-29T01:00:40.000Z",
    "channel-7": "2022-06-29T00:59:47.000Z",
    "channel-8": "2022-06-29T00:07:28.000Z",
    "channel-9": "2022-06-28T23:55:27.000Z",
}

if(!channel.live) {
  delete Channels[name];
  Channels[name] = date.toJSON();
}

if(channel.live)
  Channels = { [name]: time.toJSON(), ...Channels };
}

const updatedChannels = {};
Object.keys(Channels).sort().forEach(item => (updatedChannels[item] = Channels[item]));

Channels = updatedChannels;

As you have requirement to delete and add channels as per your conditions i have mention one method to achieve your requirement it should works for you.

let Channels = {
    "channel-1": "2022-06-29T11:20:14.000Z",
    "channel-2": "2022-06-29T05:58:18.000Z",
    "channel-3": "2022-06-29T05:18:49.000Z",
    "channel-4": "2022-06-29T04:08:35.000Z",
    "channel-5": "2022-06-29T01:52:31.000Z",
    "channel-6": "2022-06-29T01:00:40.000Z",
    "channel-7": "2022-06-29T00:59:47.000Z",
    "channel-8": "2022-06-29T00:07:28.000Z",
    "channel-9": "2022-06-28T23:55:27.000Z",
}

if(!channel.live) {
  delete Channels[name];
  Channels[name] = date.toJSON();
}

if(channel.live)
  Channels = { [name]: time.toJSON(), ...Channels };
}

const updatedChannels = {};
Object.keys(Channels).sort().forEach(item => (updatedChannels[item] = Channels[item]));

Channels = updatedChannels;

是否有更好的方法可以通过其属性对对象进行分类?

城歌 2025-02-17 07:10:26

检查您的身份验证设置 - &GT;未经验证的请求,如果不是“ HTTP 302”,则Azure将不会返回授权_uri和其他数据。

Check your Authentication settings -> Unauthenticated requests, if it's not "HTTP 302", then Azure will not return authorization_uri and other data.

enter image description here

在www-oderorize azure函数easyauth中缺少授权_uri

城歌 2025-02-17 06:01:01
const data=[{_id:"D01",name:"Lunetts",profession:"shop"},{_id:"D02",name:"Glasses",profession:"keeper"},{_id:"D03",name:"Auros",profession:"UiiSii"}];

const out = {};

for (const obj of data) {
  out[obj._id] = obj.name;
}

console.log(out);

Use a simple loop to create a new object.

const data=[{_id:"D01",name:"Lunetts",profession:"shop"},{_id:"D02",name:"Glasses",profession:"keeper"},{_id:"D03",name:"Auros",profession:"UiiSii"}];

const out = {};

for (const obj of data) {
  out[obj._id] = obj.name;
}

console.log(out);

将对象的数组组合到JavaScript中的一个对象

城歌 2025-02-17 03:34:51

也许有两个传说,一个使用自定义字形?

draw_key_arrow_left <- function(data, params, size, dir) {
  if (is.null(data$linetype)) {
    data$linetype <- 0
  } else {
    data$linetype[is.na(data$linetype)] <- 0
  }
  
  segmentsGrob(0.9, 0.5, 0.1, 0.5,
               gp = gpar(
                 col = alpha(data$colour %||% data$fill %||% "black", data$alpha),
                 # the following line was added relative to the ggplot2 code
                 fill = alpha(data$colour %||% data$fill %||% "black", data$alpha),
                 lwd = (data$size %||% 0.5) * .pt,
                 lty = data$linetype %||% 1,
                 lineend = "butt"
               ),
               arrow = params$arrow
  )
}


arrows2 <- arrows %>%
  mutate(x_orig = x, xend_orig = xend,
         x = if_else(direction == "forward", x_orig, xend_orig),
         xend = if_else(direction == "forward", xend_orig, x_orig))

ggplot() +
  geom_segment(data = arrows2 %>% filter(direction == "forward"),
               aes(x, y, xend = xend, yend = yend, col = direction),
               arrow = arrow(length = unit(0.3, "cm"), type = "closed")) +
  scale_color_manual(values = "#F8766D") +
  
  ggnewscale::new_scale_color() +
  geom_segment(data = arrows2 %>% filter(direction == "backward"),
               aes(x, y, xend = xend, yend = yend, col = direction),
               arrow = arrow(length = unit(0.3, "cm"), type = "closed"),
               key_glyph = "arrow_left") +
  scale_color_manual(values = "#619CFF", name = "") +
  theme(legend.key.width=unit(0.7,"cm"))

Perhaps with two legends, one using a custom glyph?

enter image description here

draw_key_arrow_left <- function(data, params, size, dir) {
  if (is.null(data$linetype)) {
    data$linetype <- 0
  } else {
    data$linetype[is.na(data$linetype)] <- 0
  }
  
  segmentsGrob(0.9, 0.5, 0.1, 0.5,
               gp = gpar(
                 col = alpha(data$colour %||% data$fill %||% "black", data$alpha),
                 # the following line was added relative to the ggplot2 code
                 fill = alpha(data$colour %||% data$fill %||% "black", data$alpha),
                 lwd = (data$size %||% 0.5) * .pt,
                 lty = data$linetype %||% 1,
                 lineend = "butt"
               ),
               arrow = params$arrow
  )
}


arrows2 <- arrows %>%
  mutate(x_orig = x, xend_orig = xend,
         x = if_else(direction == "forward", x_orig, xend_orig),
         xend = if_else(direction == "forward", xend_orig, x_orig))

ggplot() +
  geom_segment(data = arrows2 %>% filter(direction == "forward"),
               aes(x, y, xend = xend, yend = yend, col = direction),
               arrow = arrow(length = unit(0.3, "cm"), type = "closed")) +
  scale_color_manual(values = "#F8766D") +
  
  ggnewscale::new_scale_color() +
  geom_segment(data = arrows2 %>% filter(direction == "backward"),
               aes(x, y, xend = xend, yend = yend, col = direction),
               arrow = arrow(length = unit(0.3, "cm"), type = "closed"),
               key_glyph = "arrow_left") +
  scale_color_manual(values = "#619CFF", name = "") +
  theme(legend.key.width=unit(0.7,"cm"))

如何在GGPLOT2传奇中向后和向前的方向显示箭头?

城歌 2025-02-16 23:43:20

如@Teemu所示,您必须使用命名函数,因为如果要从侦听器中删除该功能,则需要对该函数进行引用。

因此,您没有在addeventListener()中编写匿名函数,而是向其提供您在其他地方定义的函数的名称 - 最重要的是,不在循环中。

例如:

parent[i].addEventListener('mouseover', e => {
    this.addChildrenActive(i)
});

变为

parent[i].addEventListener('mouseover', mouseOverHandler);

命名函数,

function mouseOverHandler(e)
{
  console.log("mouse over", e.currentTarget);
}

您可能已经注意到该函数内部的e参数。这将填充与事件有关的数据,例如事件的名称或元素引起的。

然后可以使用以下方式删除此听众:

parent[i].removeEventListener('mouseover', mouseOverHandler);

让我给您一个更完整的示例:

class Navigation {
  constructor() {
    this.isMobile = false;
    this.parent = document.querySelectorAll("div");
    this.navbarInteraction();
  }

  navbarInteraction() {
    for (let i = 0; i < this.parent.length; i++) {
      this.parent[i].removeEventListener('mouseover', this.addChildrenActive);
      this.parent[i].removeEventListener('click', this.addChildrenActive);
      if (this.isMobile) {
        this.parent[i].addEventListener('click', this.addChildrenActive);
      } else {
        this.parent[i].addEventListener('mouseover', this.addChildrenActive);
      }
    }
  }

  addChildrenActive(e) {
    console.log("addChildrenActive()", e.currentTarget, e.type);
  }
}

let navigation = new Navigation();
<div id="divA">DIV1</div>
<div id="divB">DIV2</div>
<input type="checkbox" onchange="navigation.isMobile=this.checked;navigation.navbarInteraction();">
<span>isMobile</span>

As @Teemu indicated you have to use a named function because you need a reference to that function if you want to remove it from a listener.

So instead of writing an anonymous function inside the addEventListener() you supply it the name of a function you defined elsewhere - and most importantly not inside your loop.

For example:

parent[i].addEventListener('mouseover', e => {
    this.addChildrenActive(i)
});

becomes

parent[i].addEventListener('mouseover', mouseOverHandler);

and it's named function

function mouseOverHandler(e)
{
  console.log("mouse over", e.currentTarget);
}

You might have noticed the e parameter inside the function. This will be populated with data related to the event e.g. the name of the event or which element caused it.

This listener can then be removed using:

parent[i].removeEventListener('mouseover', mouseOverHandler);

Let me give you a more complete example:

class Navigation {
  constructor() {
    this.isMobile = false;
    this.parent = document.querySelectorAll("div");
    this.navbarInteraction();
  }

  navbarInteraction() {
    for (let i = 0; i < this.parent.length; i++) {
      this.parent[i].removeEventListener('mouseover', this.addChildrenActive);
      this.parent[i].removeEventListener('click', this.addChildrenActive);
      if (this.isMobile) {
        this.parent[i].addEventListener('click', this.addChildrenActive);
      } else {
        this.parent[i].addEventListener('mouseover', this.addChildrenActive);
      }
    }
  }

  addChildrenActive(e) {
    console.log("addChildrenActive()", e.currentTarget, e.type);
  }
}

let navigation = new Navigation();
<div id="divA">DIV1</div>
<div id="divB">DIV2</div>
<input type="checkbox" onchange="navigation.isMobile=this.checked;navigation.navbarInteraction();">
<span>isMobile</span>

将内部删除内部循环ES6

城歌 2025-02-16 21:10:20

前提您将调用sql_script规则:

myTree = parser.sql_script();

Assuming you're using this grammar, you'd invoke the sql_script rule:

myTree = parser.sql_script();

如何从Antlr4解析器中获取解析树?

城歌 2025-02-16 18:13:31

您可以将combine_images传递到预期列的功能号码space像素中的图像和> > images> images的列表:

from PIL import Image


def combine_images(columns, space, images):
    rows = len(images) // columns
    if len(images) % columns:
        rows += 1
    width_max = max([Image.open(image).width for image in images])
    height_max = max([Image.open(image).height for image in images])
    background_width = width_max*columns + (space*columns)-space
    background_height = height_max*rows + (space*rows)-space
    background = Image.new('RGBA', (background_width, background_height), (255, 255, 255, 255))
    x = 0
    y = 0
    for i, image in enumerate(images):
        img = Image.open(image)
        x_offset = int((width_max-img.width)/2)
        y_offset = int((height_max-img.height)/2)
        background.paste(img, (x+x_offset, y+y_offset))
        x += width_max + space
        if (i+1) % columns == 0:
            y += height_max + space
            x = 0
    background.save('image.png')


combine_images(columns=3, space=20, images=['apple_PNG12507.png', 'banana_PNG838.png', 'blackberry_PNG45.png', 'cherry_PNG635.png', 'pear_PNG3466.png', 'plum_PNG8670.png', 'strawberry_PNG2595.png'])

7张图像和3列的结果:

“

You can pass to the combine_images function number of expected columns, space between images in pixels and the list of images:

from PIL import Image


def combine_images(columns, space, images):
    rows = len(images) // columns
    if len(images) % columns:
        rows += 1
    width_max = max([Image.open(image).width for image in images])
    height_max = max([Image.open(image).height for image in images])
    background_width = width_max*columns + (space*columns)-space
    background_height = height_max*rows + (space*rows)-space
    background = Image.new('RGBA', (background_width, background_height), (255, 255, 255, 255))
    x = 0
    y = 0
    for i, image in enumerate(images):
        img = Image.open(image)
        x_offset = int((width_max-img.width)/2)
        y_offset = int((height_max-img.height)/2)
        background.paste(img, (x+x_offset, y+y_offset))
        x += width_max + space
        if (i+1) % columns == 0:
            y += height_max + space
            x = 0
    background.save('image.png')


combine_images(columns=3, space=20, images=['apple_PNG12507.png', 'banana_PNG838.png', 'blackberry_PNG45.png', 'cherry_PNG635.png', 'pear_PNG3466.png', 'plum_PNG8670.png', 'strawberry_PNG2595.png'])

Result for 7 images and 3 columns:

7 images and 3 columns

Result for 6 images and 2 columns:

6 images and 2 columns

如何在Python的网格结构中将几个图像结合到一个图像中?

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

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