倾城花音

文章 评论 浏览 30

倾城花音 2025-02-13 05:59:24

这是两个可以提高系统性能的建议:

  1. 使工作较短,以使工作不那么平行:

    • 使用在本地完成工作的存储过程,而不是在API和DB之间移动数据
    • 将数据库扩展到
    • 优化查询
    • 确认索引
    • 使用缓存
    • 等。
  2. 接受接受请求,但将它们放在队列中,并使队列的消费者分批地处理它们,而不是一个一个。

Here are two suggestions that could improve the performance of the system:

  1. Make the work shorter so that there is less parallel work:

    • Use a stored procedure that does the work locally rather that moving data between the api and the db
    • Scale the database up,
    • Optimize the queries
    • Confirm indexes
    • Use caching
    • etc.
  2. Accept the requests but put them on a queue and make the consumer of the queue process them in batches rather than one by one.

在.net5.0 Web API中,异步API性能瓶颈

倾城花音 2025-02-13 05:29:59

这是使用“ ArrayFilters” 进行操作的另一种方法。

db.collection.update({
  "data.category.subcategory": "EDUCATION"
},
{
  "$set": {
    "data.category.$[].subcategory.$[elem]": "SPORTS"
  }
},
{
  "arrayFilters": [
    { "elem": "EDUCATION" }
  ],
  "multi": true
})

尝试一下 mongoplayground.net.net

Here's another way to do it using "arrayFilters".

db.collection.update({
  "data.category.subcategory": "EDUCATION"
},
{
  "$set": {
    "data.category.$[].subcategory.$[elem]": "SPORTS"
  }
},
{
  "arrayFilters": [
    { "elem": "EDUCATION" }
  ],
  "multi": true
})

Try it on mongoplayground.net.

mongodb-如何在嵌套数组中查找和更新元素

倾城花音 2025-02-13 02:16:23

由于映射类型只能访问类型中的访问密钥,因此您需要提供额外的通用类型以进行比较。

type OptionsFlags<T extends {}, K extends string> = {
  [k in K]: k extends keyof T ? boolean : string;
};

Since the mapped type can only access keys live within Type, you need to provide an extra Generic Type for comparison.

type OptionsFlags<T extends {}, K extends string> = {
  [k in K]: k extends keyof T ? boolean : string;
};

“不在Keyof中”在打字稿中

倾城花音 2025-02-12 21:01:01

令我惊讶的是,尚未提及这一点,因此为了完整的目的,

您可以执行用“ Splat Operator”打开包装的列表:*,它也将复制列表的元素。

old_list = [1, 2, 3]

new_list = [*old_list]

new_list.append(4)
old_list == [1, 2, 3]
new_list == [1, 2, 3, 4]

这种方法的明显缺点是它仅在Python 3.5+中可用。

明智的定时,这似乎比其他常见方法更好。

x = [random.random() for _ in range(1000)]

%timeit a = list(x)
%timeit a = x.copy()
%timeit a = x[:]

%timeit a = [*x]

#: 2.47 µs ± 38.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
#: 2.47 µs ± 54.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
#: 2.39 µs ± 58.2 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

#: 2.22 µs ± 43.2 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

It surprises me that this hasn't been mentioned yet, so for the sake of completeness...

You can perform list unpacking with the "splat operator": *, which will also copy elements of your list.

old_list = [1, 2, 3]

new_list = [*old_list]

new_list.append(4)
old_list == [1, 2, 3]
new_list == [1, 2, 3, 4]

The obvious downside to this method is that it is only available in Python 3.5+.

Timing wise though, this appears to perform better than other common methods.

x = [random.random() for _ in range(1000)]

%timeit a = list(x)
%timeit a = x.copy()
%timeit a = x[:]

%timeit a = [*x]

#: 2.47 µs ± 38.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
#: 2.47 µs ± 54.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
#: 2.39 µs ± 58.2 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

#: 2.22 µs ± 43.2 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

我如何克隆列表,以免在分配后意外变化?

倾城花音 2025-02-12 17:51:49

您可以使用LocalStorage(与较旧的浏览器不兼容):

<script type="text/javascript">
    var alerted = localStorage.getItem('alerted') || '';
    if (alerted != 'yes') {
     alert("My alert.");
     localStorage.setItem('alerted','yes');
    }
</script>

You can use localStorage (not compatible with older browsers):

<script type="text/javascript">
    var alerted = localStorage.getItem('alerted') || '';
    if (alerted != 'yes') {
     alert("My alert.");
     localStorage.setItem('alerted','yes');
    }
</script>

如何仅显示警报一次?

倾城花音 2025-02-12 04:04:46

您无法设置这样的状态:

<View>
              <Text>
                            {letter.description[pass]}
                            {pass++}
                            {setPass((pass2) => pass2 + 1)}
                            {pass2}
                  
          </Text>
</View>

您需要创建一个函数:

cost handlePress = () => {
 letter.description[pass]
 setPass(prev => {
   prev += 1    
   })
}

    <View>
                      <Text onPress={handlePress}>{pass2}</Text>
    </View>

You cant set state like this :

<View>
              <Text>
                            {letter.description[pass]}
                            {pass++}
                            {setPass((pass2) => pass2 + 1)}
                            {pass2}
                  
          </Text>
</View>

You need to create a function :

cost handlePress = () => {
 letter.description[pass]
 setPass(prev => {
   prev += 1    
   })
}

    <View>
                      <Text onPress={handlePress}>{pass2}</Text>
    </View>

反应本地,设置状态(设置)发行

倾城花音 2025-02-11 18:55:21

您正在观看的教程告诉您在其中创建一个名为 config.py 的文件,并将其定义放在其中的 email_address email_passwordword 。但是,您似乎将这些定义与其他所有内容相同。

这还可以,但是如果您要这样做,则无需将导入config 放在代码的顶部。您也不需要在每次引用变量的名称之前添加 config。

工作代码看起来像这样:

import smtplib

EMAIL_ADDRESS = "***"
EMAIL_ADDRESS2 = "***"
EMAIL_PASSWORD = "***"


def send_email(subject, msg):
    try:
        server = smtplib.SMTP("smtp-mail.outlook.com:587")
        server.ehlo()
        server.starttls()
        server.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
        message = f"Subject: {subject}\n\n{msg}"
        server.sendmail(EMAIL_ADDRESS, EMAIL_ADDRESS2, message)
        server.quit()
        print("email sent ツ")
    except:
        print("Email failed to send :(")

但是,在Python脚本中放置诸如密码之类的敏感信息并不是一个好主意,以防您与其他人共享它们,而忘记了您已经这样做。

教程建议创建一个称为 config.py 存储此单独的python文件,但这实际上不是通常的方法。

隐藏信息的通常方法将其放在与主脚本同一目录中的名为 .env 的文件中,并将信息从代码中取出。

使用 .env 文件是因为它是存储环境变量的常规方式。

如果您想执行此操作(这可能是最好的选择),那么这就是您要做的:

  1. 在与主脚本同一目录中创建一个称为 .env 的文件,然后填写信息如下:
      email_address = ***
    email_address2 = ***
    email_password = ***
     

    (请注意,您不需要语音标记。)

  2. 使用以下命令安装 dotenv 模块:
      pip安装python-dotenv
     
  3. 修改您的代码以从环境文件中获取值,而不是定义脚本中的变量:
     导入smtplib
    导入操作系统
    来自dotenv import load_dotenv
    
    load_dotenv()
    email_address = os.getEnv(“ email_address”)
    email_address2 = os.getEnv(“ email_address2”)
    email_password = os.getEnv(“ email_password”)
    
    
    def send_email(主题,msg):
        尝试:
            server = smtplib.smtp(“ smtp-mail.outlook.com:587”)
            server.ehlo()
            server.starttls()
            server.login(email_address,email_password)
            消息= f“主题:{主题} \ n \ n {msg}”
            server.sendmail(email_address,email_address2,邮件)
            server.quit()
            打印(“电子邮件发送ツ”)
        除了:
            打印(“电子邮件未能发送:(”)
     

要查找有关 dotenv 的更多信息,请参见他们的官方pypi页

The tutorial you are watching tells you to create a file called config.py, and put the definitions of EMAIL_ADDRESS and EMAIL_PASSWORD in there. However, you seem to be putting these definitions in the same script as everything else.

This is OK, but if you are going to do this, you do not need to put import config at the top of your code. You also don't need to put config. before the names of the variables each time you reference them.

The working code looks like this:

import smtplib

EMAIL_ADDRESS = "***"
EMAIL_ADDRESS2 = "***"
EMAIL_PASSWORD = "***"


def send_email(subject, msg):
    try:
        server = smtplib.SMTP("smtp-mail.outlook.com:587")
        server.ehlo()
        server.starttls()
        server.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
        message = f"Subject: {subject}\n\n{msg}"
        server.sendmail(EMAIL_ADDRESS, EMAIL_ADDRESS2, message)
        server.quit()
        print("email sent ツ")
    except:
        print("Email failed to send :(")

However, it is not really a good idea to put sensitive information like passwords in Python scripts, in case you share them with someone else, forgetting that you have done so.

The tutorial suggests creating a separate Python file called config.py to store this, but this is not actually the usual way it is done.

The usual method of hiding information is putting it in a file called .env in the same directory as the main script, and taking the information out of there in the code.

The .env file is used because it is the conventional way of storing environment variables.

If you want to do this (which is probably the best option), then here is what you have to do:

  1. Create a file called .env in the same directory as your main script, and fill it out with the information as follows:
    EMAIL_ADDRESS=***
    EMAIL_ADDRESS2=***
    EMAIL_PASSWORD=***
    

    (Note that you do not need speech marks.)

  2. Install the dotenv module using the following command:
    pip install python-dotenv
    
  3. Modify your code to take values from the environment file instead of defining the variables in the script:
    import smtplib
    import os
    from dotenv import load_dotenv
    
    load_dotenv()
    EMAIL_ADDRESS = os.getenv("EMAIL_ADDRESS")
    EMAIL_ADDRESS2 = os.getenv("EMAIL_ADDRESS2")
    EMAIL_PASSWORD = os.getenv("EMAIL_PASSWORD")
    
    
    def send_email(subject, msg):
        try:
            server = smtplib.SMTP("smtp-mail.outlook.com:587")
            server.ehlo()
            server.starttls()
            server.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
            message = f"Subject: {subject}\n\n{msg}"
            server.sendmail(EMAIL_ADDRESS, EMAIL_ADDRESS2, message)
            server.quit()
            print("email sent ツ")
        except:
            print("Email failed to send :(")
    

To find out more information about dotenv, see their official PyPI page.

如何修复:modulenotfounderror:no模块名为&#x27; config#x27;

倾城花音 2025-02-11 11:42:39

applicationUsername 自ios 7.0以来就可以在此处参见文档: https://developer.apple.com/documentation/storekit/skmutablepayment/1506088-applicationusername

但是由于某些原因,我需要Apple verifyReciept API的AppacCountToken

这也是一个可选的属性,StoreKit不需要您为ApplicationUsername或AppacCountToken设置值。

applicationUsername has been available since iOS 7.0 see the docs here: https://developer.apple.com/documentation/storekit/skmutablepayment/1506088-applicationusername

But for some reason currently I need appAccountToken from apple verifyReciept api also

This is an optional property, StoreKit does not require you to set a value for either applicationUsername or appAccountToken.

我将如何从StoreKit verifyReceipt API中获得legacy用户的appaccounttoken?

倾城花音 2025-02-11 10:03:15

由于您没有示例,我们可以自行编译,并且有一些缺少的细节,我将解决您的问题的核心:如何从 fn fnonce >?

您已经知道的第一个问题是:如果您尝试直接调用 fnonce ,这是不允许的,因为它消耗了该值,这将使调用封闭本身 fnonce ,但是您需要 fn

第二个是,如果您尝试使用 option take()方法之类的东西,您会发现 fn 无法突变其捕获的状态(必须是 fnmut 才能执行此操作)。

解决方案是将选项包裹在提供内部变异性的类型中。取决于您是否需要 fn 也为 send + sync ,您可以使用 cell mutex

使用单元格,它是不是 send + sync ,它看起来像这样:

use std::cell::Cell;

fn print_owned(x: String) {
    println!("print_owned called with {:?}", x);
}

fn call_twice(f: impl Fn()) {
    f();
    f();
}

fn main() {
    let foo = "foo".to_string();
    let fnonce = move || print_owned(foo);
    
    let maybe_fnonce = Cell::new(Some(fnonce));
    
    call_twice(move || {
        match maybe_fnonce.take() {
            Some(inner) => inner(),
            None => println!("maybe_fnonce is None"),
        }
    });
}

当闭合传递到 call_twice()< /code> indokes take()单元格上,提取内值并用 none 替换。如果再次调用该函数,则内部值将为 none 先前放置的。这也意味着您可以检测到这种情况,并可能向JavaScript侧发出问题。

如果封闭需要发送 +同步,则可以使用 mutex&lt; option&lt; _&gt;&gt;&gt;

use std::sync::Mutex;

fn print_owned(x: String) {
    println!("print_owned called with {:?}", x);
}

fn call_twice(f: impl Fn()) {
    f();
    f();
}

fn main() {
    let foo = "foo".to_string();
    let fnonce = move || print_owned(foo);
    
    let maybe_fnonce = Mutex::new(Some(fnonce));
    
    call_twice(move || {
        match maybe_fnonce.lock().unwrap().take() {
            Some(inner) => inner(),
            None => println!("maybe_fnonce is None"),
        }
    });
}

您所要做的就是将此技术应用于您的特定情况。

Since you don't have an example we can compile ourselves and there is some missing detail, I will address the heart of your question: how do you call an FnOnce from an Fn?

The first problem you already know: if you try to call the FnOnce directly, this is disallowed because it consumes the value, which would make the calling closure itself FnOnce, but you need an Fn.

The second is that if you try to use something like Option with its take() method, you'll find that Fn can't mutate its captured state (it would have to be FnMut to do that).

The solution is to wrap an Option in a type providing interior mutability. Depending on whether you need your Fn to also be Send + Sync, you could use either Cell or Mutex.

With Cell, which is not Send + Sync, it would look something like this:

use std::cell::Cell;

fn print_owned(x: String) {
    println!("print_owned called with {:?}", x);
}

fn call_twice(f: impl Fn()) {
    f();
    f();
}

fn main() {
    let foo = "foo".to_string();
    let fnonce = move || print_owned(foo);
    
    let maybe_fnonce = Cell::new(Some(fnonce));
    
    call_twice(move || {
        match maybe_fnonce.take() {
            Some(inner) => inner(),
            None => println!("maybe_fnonce is None"),
        }
    });
}

When the closure passed to call_twice() invokes take() on the Cell, the inner value is extracted and replaced with None. If the function is called again, the inner value will be the None previously put there. This also means you can detect this situation and possibly signal the problem back to the JavaScript side.

If the closure needs to be Send + Sync then you can instead use Mutex<Option<_>>:

use std::sync::Mutex;

fn print_owned(x: String) {
    println!("print_owned called with {:?}", x);
}

fn call_twice(f: impl Fn()) {
    f();
    f();
}

fn main() {
    let foo = "foo".to_string();
    let fnonce = move || print_owned(foo);
    
    let maybe_fnonce = Mutex::new(Some(fnonce));
    
    call_twice(move || {
        match maybe_fnonce.lock().unwrap().take() {
            Some(inner) => inner(),
            None => println!("maybe_fnonce is None"),
        }
    });
}

All you need to do is apply this technique to your specific situation.

从`fn'呼叫`fnonce`

倾城花音 2025-02-11 08:04:23

我正在使用M2 Ventura 13.2

  1. Arch -Arm64 Pyenv install 3.11.1
  2. Pyenv Virtualenv 3.11.1 Artifact
  3. Pyenv pyenv local trifact
  4. pip install -prech torchvision torchvision torchvision torchaudio -index -index -url https://download.pytorch.org/whl/nightly/cpu
  5. 在外壳中检查
>>> import torch

>>> torch.backends.mps.is_available()

True

I am using M2 Ventura 13.2

  1. arch -arm64 pyenv install 3.11.1
  2. pyenv virtualenv 3.11.1 artifact
  3. pyenv local artifact
  4. pip install --pre torch torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/cpu
  5. Check in the shell
>>> import torch

>>> torch.backends.mps.is_available()

True

Pyenv不能在MacOS M1上安装Python

倾城花音 2025-02-11 05:58:35

进行了一些搜索之后,我意识到Flutter提供了一种使用 changeNotifierProxyProvider2 来解决此问题的优雅开箱即用的方式。

MultiProvider(
  providers: [
    ChangeNotifierProvider(create: (context) => A()),
    ChangeNotifierProvider(create: (context) => B()),
    ChangeNotifierProxyProvider2<A, B, C>(
      create: (context) => C(),
      update: (_, a, b, c) => c!..updateFromA(a)..updateFromB(b),
    ),
  ]

Flutter还提供 ChangeNotifierProxyProvider3 通过 changeNotifierProxyProvider6 ,但这当然会变得非常冗长且令人困惑。

After doing some searching, I realized that Flutter provides an elegant out-of-the-box way of solving this problem using ChangeNotifierProxyProvider2.

MultiProvider(
  providers: [
    ChangeNotifierProvider(create: (context) => A()),
    ChangeNotifierProvider(create: (context) => B()),
    ChangeNotifierProxyProvider2<A, B, C>(
      create: (context) => C(),
      update: (_, a, b, c) => c!..updateFromA(a)..updateFromB(b),
    ),
  ]

Flutter also provides ChangeNotifierProxyProvider3 through ChangeNotifierProxyProvider6, but that would, of course, get very verbose and confusing.

多个ChangeNotifierProxyProviders将更新馈送到ChangeNotifier

倾城花音 2025-02-11 03:18:28

第一个汇总列表,例如上一个解决方案,并将新列添加到 df2 带有聚合列表的列表:

s = (df1.groupby(['N_Id','N_Name'])['pcode']
        .agg(list)
        .rename('Pcode'))

df = df2.join(s, on=['N_Id','N_Name'])

然后每个组需要拆分列表(每个组相同,因此选择的第一个列表 iat [0] terminal_load 诸如链接解决方案之类的值 - 仅是累积总和,并以 0 开始:

def f(x):
    indices = [0] + x['Terminal_Load'].cumsum().tolist()
    s = x['Pcode'].iat[0]
    #https://stackoverflow.com/a/10851479/2901002
    x['Pcode'] = [','.join(s[indices[i]:indices[i+1]]) for i in range(len(indices)-1)]
    return x

df = df.groupby(['N_Id','N_Name']).apply(f)
print (df)
   BusID  Tcap  Terminal_Load  N_Id    N_Name          Pcode
0     V1     4              1     1    N_Area           M023
1     V1     4              2     2  Pstation     L123,M0232
2     V1     4              1     5   T_depot         M01368
3     V4     8              2     2  Pstation    L1234,K0324
4     V4     8              1     5   T_depot         M01369
5     V4     8              1    10  B_colony         M01375
6     V5    12              2    11  c_colony  F04609,F04610
7     V5    12              1     4    A_Area          M0137
8     V5    12              1    10  B_colony         F04509
9     V0    12              0     0   Destiny               
10  v100     8              4    13  Z_colony    F1,F2,F3,F4

First aggregate list like previous solution and add new column to df2 with aggregate lists:

s = (df1.groupby(['N_Id','N_Name'])['pcode']
        .agg(list)
        .rename('Pcode'))

df = df2.join(s, on=['N_Id','N_Name'])

Then need split lists per groups (same per groups, so selected first list by iat[0]) by Terminal_Load values like linked solution - only is necessary cumulative sum and starting by 0:

def f(x):
    indices = [0] + x['Terminal_Load'].cumsum().tolist()
    s = x['Pcode'].iat[0]
    #https://stackoverflow.com/a/10851479/2901002
    x['Pcode'] = [','.join(s[indices[i]:indices[i+1]]) for i in range(len(indices)-1)]
    return x

df = df.groupby(['N_Id','N_Name']).apply(f)
print (df)
   BusID  Tcap  Terminal_Load  N_Id    N_Name          Pcode
0     V1     4              1     1    N_Area           M023
1     V1     4              2     2  Pstation     L123,M0232
2     V1     4              1     5   T_depot         M01368
3     V4     8              2     2  Pstation    L1234,K0324
4     V4     8              1     5   T_depot         M01369
5     V4     8              1    10  B_colony         M01375
6     V5    12              2    11  c_colony  F04609,F04610
7     V5    12              1     4    A_Area          M0137
8     V5    12              1    10  B_colony         F04509
9     V0    12              0     0   Destiny               
10  v100     8              4    13  Z_colony    F1,F2,F3,F4

淋巴结/标签分配根据pandas数据框架中的端子的负载python

倾城花音 2025-02-10 09:38:28

需要2个步骤:

  1. 获取身份验证

样品卷曲:

curl --location --request POST "https://YOUR_AUTH0_DOMAIN/oauth/token" \
--header "content-type: application/json" \
--data-raw "{
    \"grant_type\": \"client_credentials\",
    \"audience\": \"https://YOUR_AUTH0_DOMAIN/api/v2/\",
    \"client_id\": \"YOUR_AUTH0_APPLICATION_CLIENT_ID\",
    \"client_secret\": \"YOUR_AUTH0_APPLICATION_CLIENT_SECRET\"
}"
  1. 致电更新app_metadata

示例卷曲:

curl --request PATCH \
  --url 'https://YOUR_AUTH0_DOMAIN/api/v2/users/USER_ID' \
  --header 'authorization: Bearer TOKEN_FROM_STEP_1' \
  --header 'content-type: application/json' \
  --data '{"email": "[email protected]", "user_metadata": {"hobby": "surfing"}, "app_metadata": {"plan": "full"}}'

编辑:用USERID的补丁请求

2 steps are needed:

  1. Get the authentication token for management API:

sample curl:

curl --location --request POST "https://YOUR_AUTH0_DOMAIN/oauth/token" \
--header "content-type: application/json" \
--data-raw "{
    \"grant_type\": \"client_credentials\",
    \"audience\": \"https://YOUR_AUTH0_DOMAIN/api/v2/\",
    \"client_id\": \"YOUR_AUTH0_APPLICATION_CLIENT_ID\",
    \"client_secret\": \"YOUR_AUTH0_APPLICATION_CLIENT_SECRET\"
}"
  1. call the management api to update app_metadata

sample curl:

curl --request PATCH \
  --url 'https://YOUR_AUTH0_DOMAIN/api/v2/users/USER_ID' \
  --header 'authorization: Bearer TOKEN_FROM_STEP_1' \
  --header 'content-type: application/json' \
  --data '{"email": "[email protected]", "user_metadata": {"hobby": "surfing"}, "app_metadata": {"plan": "full"}}'

Edit: Patch request with userID

Auth0请求并使用Flutter应用程序中的管理API令牌

倾城花音 2025-02-10 04:11:10

这可以通过将 datasets.data 定义为对象数组具有 x y 属性的每个。

data: [
  { 'x': 1, 'y': 2 },
  { 'x': 2, 'y': 4 },
  { 'x': 3, 'y': 6 },
  { 'x': 4, 'y': 8 },
  { 'x': 5, 'y': 10 }
]

您可以使用轻松转换您的数据。请查看以下可运行的代码,然后查看其工作原理。

const y = [2, 4, 6, 8, 10];
const x1 = [1, 2, 3, 4, 5];
const x2 = [5, 6, 7, 8, 9];
const x3 = [8, 9, 10, 12, 14];

new Chart('myChart', {
  type: 'line',
  data: {
    datasets: [{
      label: 'A',
      data: y.map((v, i) => ({ x: x1[i], y: v })),
      borderColor: 'rgb(255, 0, 0)',
      backgroundColor: 'rgba(255, 0, 0, 0.2)'
    },
    {
      label: 'B',
      data: y.map((v, i) => ({ x: x2[i], y: v })),
      borderColor: 'rgb(0, 255, 0)',
      backgroundColor: 'rgba(0, 255, 0, 0.2)'
    },
    {
      label: 'C',
      data: y.map((v, i) => ({ x: x3[i], y: v })),
      borderColor: 'rgb(0, 0, 255)',
      backgroundColor: 'rgba(0, 0, 255, 0.2)'
    }]
  },
  options: {
    scales: {
      x: {
        type: 'linear',
        suggestedMin: 1,
        suggestedMax: 14,
        ticks: {
          stepSize: 1
        }
      },
      y: {
        beginAtZero: true
      }
    }
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.js"></script>
<canvas id="myChart" height="80"></canvas>

This can be done by defining datasets.data as an array of objects having an x and y property each.

data: [
  { 'x': 1, 'y': 2 },
  { 'x': 2, 'y': 4 },
  { 'x': 3, 'y': 6 },
  { 'x': 4, 'y': 8 },
  { 'x': 5, 'y': 10 }
]

You can use Array.map() to easily convert your data. Please take a look at below runnable code and see how it works.

const y = [2, 4, 6, 8, 10];
const x1 = [1, 2, 3, 4, 5];
const x2 = [5, 6, 7, 8, 9];
const x3 = [8, 9, 10, 12, 14];

new Chart('myChart', {
  type: 'line',
  data: {
    datasets: [{
      label: 'A',
      data: y.map((v, i) => ({ x: x1[i], y: v })),
      borderColor: 'rgb(255, 0, 0)',
      backgroundColor: 'rgba(255, 0, 0, 0.2)'
    },
    {
      label: 'B',
      data: y.map((v, i) => ({ x: x2[i], y: v })),
      borderColor: 'rgb(0, 255, 0)',
      backgroundColor: 'rgba(0, 255, 0, 0.2)'
    },
    {
      label: 'C',
      data: y.map((v, i) => ({ x: x3[i], y: v })),
      borderColor: 'rgb(0, 0, 255)',
      backgroundColor: 'rgba(0, 0, 255, 0.2)'
    }]
  },
  options: {
    scales: {
      x: {
        type: 'linear',
        suggestedMin: 1,
        suggestedMax: 14,
        ticks: {
          stepSize: 1
        }
      },
      y: {
        beginAtZero: true
      }
    }
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.js"></script>
<canvas id="myChart" height="80"></canvas>

如何使用Chart.js创建多个X轴数据集标签

倾城花音 2025-02-10 02:10:44

也许为时已晚,但我遇到了同样的问题。我通过为每个环境定义不同的资源来解决这一问题。每个环境也可以具有不同的代码。 的一部分

val environment: String by project

sourceSets {
    val main by getting {
        when (environment) {
            "dev" -> {
                java.srcDirs("src/main/kotlin", "src/main/dev")
                resources.srcDirs("src/main/dev/resources")
            }

            "prod" -> {
                java.srcDirs("src/main/kotlin", "src/main/prod")
                resources.srcDirs("src/main/prod/resources")
            }

            else -> {
                throw Exception("Please provide 'Environment' variable prod or dev")
            }
        }
    }
}

这是我的 build.gradle.ktx

environment=dev

另外,环境参数可以传递给gradle运行,例如:

run -Penvironment=dev

Maybe it's too late but I had the same problem. I solved that by defining different resources for each environment. You can also have different code per environment. Here is a part of my build.gradle.ktx

val environment: String by project

sourceSets {
    val main by getting {
        when (environment) {
            "dev" -> {
                java.srcDirs("src/main/kotlin", "src/main/dev")
                resources.srcDirs("src/main/dev/resources")
            }

            "prod" -> {
                java.srcDirs("src/main/kotlin", "src/main/prod")
                resources.srcDirs("src/main/prod/resources")
            }

            else -> {
                throw Exception("Please provide 'Environment' variable prod or dev")
            }
        }
    }
}

the default environment can be set in gradle.properties file

environment=dev

also the environment parameter can be passed to gradle run eg:

run -Penvironment=dev

使用KTOR构建时,如何将LogBack.xml和LogBack-test.xml分开?

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

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