断肠人

文章 评论 浏览 31

断肠人 2025-02-20 18:20:39

代码不是很清楚,但是乍一看,您似乎是通过字符来构建字符,这就是为什么您要看到的输出。取而代之的是,如果您想将单词保留并在必要时将其溢出到下一个字符串,则可以通过单词进行word。一个更有希望的代码将是:

static String[] splitString(String s, int max) {
    String[] words = s.split("\s+");
    List<String> out = new ArrayList<>();
    int numWords = words.length;
    int i = 0;
    while (i <numWords) {
        int len = 0;
        StringBuilder sb = new StringBuilder();
        while (i < numWords && len < max) {
            int wordLength = words[i].length();
            len += (i == numWords-1 ? wordLength : wordLength + 1);//1 for space
            if (len <= max) {
                sb.append(words[i]+ " ");
                i++;
            }
        }
        out.add(sb.toString().trim());
    }
    return out.toArray(new String[] {});
        
}

注意:它可以在您的示例输入中使用,但是您可能需要调整它,以便适用于包含20个字符的长词,等等。

The code is not very clear, but at first glance it seems you are building character by character that is why you are getting the output you see. Instead you go word by word if you want to retain a word and overflow it to next String if necessary. A more promising code would be:

static String[] splitString(String s, int max) {
    String[] words = s.split("\s+");
    List<String> out = new ArrayList<>();
    int numWords = words.length;
    int i = 0;
    while (i <numWords) {
        int len = 0;
        StringBuilder sb = new StringBuilder();
        while (i < numWords && len < max) {
            int wordLength = words[i].length();
            len += (i == numWords-1 ? wordLength : wordLength + 1);//1 for space
            if (len <= max) {
                sb.append(words[i]+ " ");
                i++;
            }
        }
        out.add(sb.toString().trim());
    }
    return out.toArray(new String[] {});
        
}

Note: It works on your example input, but you may need to tweak it so it works for cases like a long word containing more than 20 characters, etc.

将字符串在大小有限的字符串中拆分

断肠人 2025-02-20 17:36:25

转座后,使用:

df.columns = df.iloc [0]

将列标题设置为第一行。

然后使用“ set_axis()”函数为行设置索引。链接了此功能的解释
在这里

After transposing, use:

df.columns = df.iloc[0]

to set column headers to the first row.

Then use the 'set_axis()' function to set indices for your rows. An explanation for this function is linked
here

转置列/行,更改列名和重置索引

断肠人 2025-02-20 12:15:38

所以我遇到了类似的问题。我的问题陈述是 - nest js中的AWS秘密。这必须在实例化其他模块之前完成。示例 - typeorm,JWT模块都需要配置值。

我是怎么实现的?通过构建一个辅助功能,该功能从AWS获取秘密并在过程中持续存在这些

export async function secretLoader(){
  const secretsManager = new SecretsManager({
    region: process.env['AWS_REGION'],
  });
  const secretsIds = [process.env['AWS_SECRET_ID']];

  const commands = secretsIds.map(
    (secretId) =>
      new GetSecretValueCommand({
        SecretId: secretId,
      }),
  );
  const resp = commands.map((command) =>
    secretsManager.send(command),
  );
  const secrets = await Promise.all(resp);
  const response = secrets.reduce((acc, secret) => {
    const sec = JSON.parse(<string>secret.SecretString);
    return {
      ...acc,
      ...sec,
    };
  }, {});
  Object.keys(response).forEach((key) => {
    process.env[key] = response[key];
  });
}

。导入并运行此功能。

import { secretLoader } from './secretLoader';

async function bootstrap() {
  await secretLoader();
  initializeTransactionalContext(); // Initialize cls-hooked
  const app = await NestFactory.create(AppModule);
  const configService: ConfigService = app.get(ConfigService);
  await app.listen(configService.get<number>('PORT') || 3000);
}
bootstrap();

干杯!

PS-
我尝试在“加载”中使用Config Factory方法。但是它不起作用,因为在配置模块之前初始化了一些模块。

So I faced a similar problem. My problem Statement was - Load AWS Secrets in Nest JS. This had to be done before any other module is instantiated. Example - TypeORM, JWT Module both required config values.

How I achieved it? By building a helper function which fetches secrets from AWS and persists those values in process.env

export async function secretLoader(){
  const secretsManager = new SecretsManager({
    region: process.env['AWS_REGION'],
  });
  const secretsIds = [process.env['AWS_SECRET_ID']];

  const commands = secretsIds.map(
    (secretId) =>
      new GetSecretValueCommand({
        SecretId: secretId,
      }),
  );
  const resp = commands.map((command) =>
    secretsManager.send(command),
  );
  const secrets = await Promise.all(resp);
  const response = secrets.reduce((acc, secret) => {
    const sec = JSON.parse(<string>secret.SecretString);
    return {
      ...acc,
      ...sec,
    };
  }, {});
  Object.keys(response).forEach((key) => {
    process.env[key] = response[key];
  });
}

You just need to set 2 properties in env files - 'AWS_REGION' and 'AWS_SECRET_ID'

Next, in the main.ts file. Import and Run this function.

import { secretLoader } from './secretLoader';

async function bootstrap() {
  await secretLoader();
  initializeTransactionalContext(); // Initialize cls-hooked
  const app = await NestFactory.create(AppModule);
  const configService: ConfigService = app.get(ConfigService);
  await app.listen(configService.get<number>('PORT') || 3000);
}
bootstrap();

Cheers!

PS -
I tried using config factory method in 'load'. But it doesn't work since some modules initialised before config module.

如何基于Async Config创建Nestjs模块?

断肠人 2025-02-20 12:01:13
d = {0:'c', 1:'d', 2:'e', 3: 'f'}
x, y, z = (0, 1, 3)
print [v for (k,v) in d.items() if x==k or y==k or z==k]
d = {0:'c', 1:'d', 2:'e', 3: 'f'}
x, y, z = (0, 1, 3)
print [v for (k,v) in d.items() if x==k or y==k or z==k]

断肠人 2025-02-20 09:20:39

为什么无论如何都基本上要循环三遍?

entries = []

with open('insurance.csv',newline='') as insurance_csv:
    for row in csv.DictReader(insurance_csv):
        entries.append([row["smoker"], row["charges"]])

我们无法猜测您的预期输出应该是什么; ziping两个列表应在每个列表中加入的行中创建一个列表,因此这就是该代码的作用。如果您想要一个字典或字典列表,则可能要以不同的方式组合每个输入行中的数据,但是代码否则应该或多或少。

要阐明这一点,如果您的输入为,

id,smoker,charges
1,no,123
2,no,567
3,yes,987

则输出将是

[["no", 123],
 ["no", 567],
 ["yes", 987]]

Why are you looping three times over basically the input anyway?

entries = []

with open('insurance.csv',newline='') as insurance_csv:
    for row in csv.DictReader(insurance_csv):
        entries.append([row["smoker"], row["charges"]])

We can't guess what your expected output should be; zipping two lists should create one list with the rows in each list joined up, so that's what this code does. If you want a dictionary instead, or a list of dictionaries, you'll probably want to combine the data from each input row differently, but the code should otherwise be more or less this.

To spell this out, if your input is

id,smoker,charges
1,no,123
2,no,567
3,yes,987

then the output will be

[["no", 123],
 ["no", 567],
 ["yes", 987]]

由zip()创建的字典仅包含两个记录,而不是1000&#x2b;

断肠人 2025-02-20 05:00:31

您可以使用

$('.buttons').on('click', 'button', function(){
    // your magic goes here
});

,或者

$('.buttons').delegate('button', 'click', function() {
    // your magic goes here
});

这两种方法是等效的,但具有不同的参数顺序。

请参阅: jquery委托活动

you could use

$('.buttons').on('click', 'button', function(){
    // your magic goes here
});

or

$('.buttons').delegate('button', 'click', function() {
    // your magic goes here
});

these two methods are equivalent but have a different order of parameters.

see: jQuery Delegate Event

事件绑定在动态创建的元素上?

断肠人 2025-02-20 03:39:19

首先,我不建议您在此时使用CSSVARSPROVIDER,除非您正在尝试尝试并知道自己在做什么。 CSSVARSPROVIDER仍然是实验性和不稳定的。改用themeprovider

至于最初的问题,您应该创建一个主题,并将其传递给cssvarsprovider
IE

const theme = extendTheme({
    // customize your theme, if needed
});

// ...

<CssVarsProvider theme={theme}>
    // ...
</CssVarsProvider>

First of all, I don't recommend you use CssVarsProvider at this point unless you are experimenting with stuff and know what you are doing. CssVarsProvider is still experimental and unstable. Take a look at ThemeProvider instead.

As for your original question, you are supposed to create a theme and pass it to CssVarsProvider.
i.e.

const theme = extendTheme({
    // customize your theme, if needed
});

// ...

<CssVarsProvider theme={theme}>
    // ...
</CssVarsProvider>

MUI警报未接收的TypeError:无法读取未定义的属性(Reading&#x27; Light&#x27;)

断肠人 2025-02-19 15:07:13
private fun setIntroScreenButtonListeners()
{
    introScreenLayoutBinding.SensorsBTN.setOnClickListener {
        switchToMainScreen()
    }

    introScreenLayoutBinding.MapBTN.setOnClickListener {
        onPause()
        switchToMapFragment()
   

}
}

private fun periodicStorageOfData()
{
    var handler = Handler()
    var runnableCode : Runnable = object : Runnable
    {
        override fun run() {
            GlobalScope.launch(Dispatchers.IO) {
                storeAllDataToSQlDatabase()
            }
            handler.postDelayed(this, 1000)
        }

    }
    handler.post(runnableCode)
}

    //fragment transaction method
    private fun switchToMapFragment()
    {
        sensorAppRunning = false
        mapFragment = MapFragment.newInstance()
//        locationMapFragment = LocationMapFragment()
        supportFragmentManager.beginTransaction().replace(introScreenLayoutBinding.fragmentFrameLayout.id , mapFragment).commit()
    }
private fun setIntroScreenButtonListeners()
{
    introScreenLayoutBinding.SensorsBTN.setOnClickListener {
        switchToMainScreen()
    }

    introScreenLayoutBinding.MapBTN.setOnClickListener {
        onPause()
        switchToMapFragment()
   

}
}

private fun periodicStorageOfData()
{
    var handler = Handler()
    var runnableCode : Runnable = object : Runnable
    {
        override fun run() {
            GlobalScope.launch(Dispatchers.IO) {
                storeAllDataToSQlDatabase()
            }
            handler.postDelayed(this, 1000)
        }

    }
    handler.post(runnableCode)
}

    //fragment transaction method
    private fun switchToMapFragment()
    {
        sensorAppRunning = false
        mapFragment = MapFragment.newInstance()
//        locationMapFragment = LocationMapFragment()
        supportFragmentManager.beginTransaction().replace(introScreenLayoutBinding.fragmentFrameLayout.id , mapFragment).commit()
    }

Android App在后台运行一段时间时切换到上一个屏幕

断肠人 2025-02-18 17:05:19

FCM令牌是基于应用程序,其捆绑ID和设备生成的,这就是为什么每个设备的唯一应用程序的独特之处。

The FCM token is generated based on the app , its bundle id and device thats why its unique for each devices for same app.

flutter firebasessemessing令牌

断肠人 2025-02-17 16:36:50

目前,我还在使用Django-Axes来进行自定义Views.py登录页面。我所做的是在我的登录函数中包括Decorator @AXES_DISPATCH。对于settings.py,请确保将axes_username_form_field配置为用户凭证字段。对于我的,我正在使用“电子邮件”。因此,应将其更改为axes_username_form_field ='电子邮件'

from axes.decorators import axes_dispatch

views.py

@axes_dispatch
def user_login(request):
...

settings.py
AXES_USERNAME_FORM_FIELD='email'

Currently I am also using django-axes for custom views.py login page. What I did was to include decorator @axes_dispatch on my login function. For Settings.py, ensure that AXES_USERNAME_FORM_FIELD is configured to your user credential field. For mine, im using 'email'. So its should be changed to AXES_USERNAME_FORM_FIELD='email'.

from axes.decorators import axes_dispatch

views.py

@axes_dispatch
def user_login(request):
...

settings.py
AXES_USERNAME_FORM_FIELD='email'

Django-Axes错误:&#x27;设置&#x27;对象没有属性。 。

断肠人 2025-02-17 04:28:14

Martijn接受的答案是简单而有效的,但没有以下文本文件:

  • utf-8编码包含非英语字符(这是Python 3中的文本文件的默认编码
  • 文件末尾的newline字符(这是vimgedit)的默认

值角色,到目前为止提供的答案都无法正常工作。

以下是一个示例,可以解决这两个问题,这也允许从文件末尾删除多个字符:

import os


def truncate_utf8_chars(filename, count, ignore_newlines=True):
    """
    Truncates last `count` characters of a text file encoded in UTF-8.
    :param filename: The path to the text file to read
    :param count: Number of UTF-8 characters to remove from the end of the file
    :param ignore_newlines: Set to true, if the newline character at the end of the file should be ignored
    """
    with open(filename, 'rb+') as f:
        last_char = None

        size = os.fstat(f.fileno()).st_size

        offset = 1
        chars = 0
        while offset <= size:
            f.seek(-offset, os.SEEK_END)
            b = ord(f.read(1))

            if ignore_newlines:
                if b == 0x0D or b == 0x0A:
                    offset += 1
                    continue

            if b & 0b10000000 == 0 or b & 0b11000000 == 0b11000000:
                # This is the first byte of a UTF8 character
                chars += 1
                if chars == count:
                    # When `count` number of characters have been found, move current position back
                    # with one byte (to include the byte just checked) and truncate the file
                    f.seek(-1, os.SEEK_CUR)
                    f.truncate()
                    return
            offset += 1

如何工作:

  • 仅读取UTF-8编码的文本文件的最后几个字节,以二进制模式读取
  • 字节ittes the bytes 的UTF -8字符的开始
  • 向后,找到一个字符(与newline不同)

,返回作为文本文件示例文本文件中的最后一个字符 - bg.txt

Здравей свят

如何要使用:

filename = 'bg.txt'
print('Before truncate:', open(filename).read())
truncate_utf8_chars(filename, 1)
print('After truncate:', open(filename).read())

输出:

Before truncate: Здравей свят
After truncate: Здравей свя

它可以与UTF-8和ASCII编码文件一起使用。

Accepted answer of Martijn is simple and kind of works, but does not account for text files with:

  • UTF-8 encoding containing non-English characters (which is the default encoding for text files in Python 3)
  • one newline character at the end of the file (which is the default in Linux editors like vim or gedit)

If the text file contains non-English characters, neither of the answers provided so far would work.

What follows is an example, that solves both problems, which also allows removing more than one character from the end of the file:

import os


def truncate_utf8_chars(filename, count, ignore_newlines=True):
    """
    Truncates last `count` characters of a text file encoded in UTF-8.
    :param filename: The path to the text file to read
    :param count: Number of UTF-8 characters to remove from the end of the file
    :param ignore_newlines: Set to true, if the newline character at the end of the file should be ignored
    """
    with open(filename, 'rb+') as f:
        last_char = None

        size = os.fstat(f.fileno()).st_size

        offset = 1
        chars = 0
        while offset <= size:
            f.seek(-offset, os.SEEK_END)
            b = ord(f.read(1))

            if ignore_newlines:
                if b == 0x0D or b == 0x0A:
                    offset += 1
                    continue

            if b & 0b10000000 == 0 or b & 0b11000000 == 0b11000000:
                # This is the first byte of a UTF8 character
                chars += 1
                if chars == count:
                    # When `count` number of characters have been found, move current position back
                    # with one byte (to include the byte just checked) and truncate the file
                    f.seek(-1, os.SEEK_CUR)
                    f.truncate()
                    return
            offset += 1

How it works:

  • Reads only the last few bytes of a UTF-8 encoded text file in binary mode
  • Iterates the bytes backwards, looking for the start of a UTF-8 character
  • Once a character (different from a newline) is found, return that as the last character in the text file

Sample text file - bg.txt:

Здравей свят

How to use:

filename = 'bg.txt'
print('Before truncate:', open(filename).read())
truncate_utf8_chars(filename, 1)
print('After truncate:', open(filename).read())

Outputs:

Before truncate: Здравей свят
After truncate: Здравей свя

This works with both UTF-8 and ASCII encoded files.

删除文件中的最后一个字符

断肠人 2025-02-17 03:25:06

内置模板标签 >做你想要的。

{% regroup projects by status as status_list %}
{% for status in status_list %}
<h2>Project of status {{ status.grouper }}</h2>
<ul>
  {% for project in status.list %}
     <li>{{ project.name }}</li>
  {% endfor %}
</ul>
{% endfor %}

The builtin template tag regroup does what you want.

{% regroup projects by status as status_list %}
{% for status in status_list %}
<h2>Project of status {{ status.grouper }}</h2>
<ul>
  {% for project in status.list %}
     <li>{{ project.name }}</li>
  {% endfor %}
</ul>
{% endfor %}

将模板除以节的最佳方法? (多个查询循环?)(django)

断肠人 2025-02-17 01:35:45
  • 要获取对象检测模型的混淆矩阵,您必须找到预测的联合(iou)的交集。

  • iou被定义为地面真相面具与预测面具之间的交点区域,除以两者之间的联合面积。

  • 基于计算的i,您必须定义一个阈值才能获得真正的正面,假阳性,真为负,假阴性。

    有关更多详细信息,请参阅此 link 。谢谢!

  • To get the confusion matrix for the object detection model you have to find the Intersection over union(IoU) for the predictions.

  • IoU is defined as the area of intersection between ground truth mask and predicted mask divided by the area of the union between the two.

  • Based on the calculated IoU you have to define a threshold to get the True positive, False positive, True negative, False negative.

    For more details please refer to this link. Thank You!

如何使用TensorFlow对象检测API从评估模型的评估中获得准确性?

断肠人 2025-02-16 21:04:41

好吧,我想要的是将今天的日期转换为a mysql> mysql 友好的日期字符串,如2012 -06-23,并将该字符串用作我的一个查询中的参数。我发现的简单解决方案是:

var today = new Date().toISOString().slice(0, 10);

请记住,以上解决方案确实不考虑您的时区偏移。

您可以考虑使用此功能:

function toJSONLocal (date) {
    var local = new Date(date);
    local.setMinutes(date.getMinutes() - date.getTimezoneOffset());
    return local.toJSON().slice(0, 10);
}

如果您在一天的开始/结束时执行此代码,这将为您提供正确的日期。

var date = new Date();

function toLocal(date) {
  var local = new Date(date);
  local.setMinutes(date.getMinutes() - date.getTimezoneOffset());
  return local.toJSON();
}

function toJSONLocal(date) {
  var local = new Date(date);
  local.setMinutes(date.getMinutes() - date.getTimezoneOffset());
  return local.toJSON().slice(0, 10);
}

// check out your devtools console
console.log(date.toJSON());
console.log(date.toISOString());
console.log(toLocal(date));

console.log(toJSONLocal(date));

  • noreferrer
  • “ “ rel =“ noreferrer”> date.date.tojson
  • “ https://deverveer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/date/date/date/date/tojson /Developer.mozilla.org/en-us/docs/web/javascript/reference/reference/global_objects/string/slice/slice“ rel =“ noreferrer”> string.slice.slice
  • 外部示例

Well, what I wanted was to convert today's date to a MySQL friendly date string like 2012-06-23, and to use that string as a parameter in one of my queries. The simple solution I've found is this:

var today = new Date().toISOString().slice(0, 10);

Keep in mind that the above solution does not take into account your timezone offset.

You might consider using this function instead:

function toJSONLocal (date) {
    var local = new Date(date);
    local.setMinutes(date.getMinutes() - date.getTimezoneOffset());
    return local.toJSON().slice(0, 10);
}

This will give you the correct date in case you are executing this code around the start/end of the day.

var date = new Date();

function toLocal(date) {
  var local = new Date(date);
  local.setMinutes(date.getMinutes() - date.getTimezoneOffset());
  return local.toJSON();
}

function toJSONLocal(date) {
  var local = new Date(date);
  local.setMinutes(date.getMinutes() - date.getTimezoneOffset());
  return local.toJSON().slice(0, 10);
}

// check out your devtools console
console.log(date.toJSON());
console.log(date.toISOString());
console.log(toLocal(date));

console.log(toJSONLocal(date));

如何在JavaScript中格式化日期?

断肠人 2025-02-16 05:12:26

您需要在WordPress侧写代码,function.php

可以通过将以下代码添加到function.php(将另一个键添加到响应中,称为htmlcontent),将以下代码添加到function.php中返回API的响应中,添加另一个键

add_action( 'rest_api_init', function () {
   register_rest_field('page', 'htmlcontent', array(
      'get_callback'    => 'page_do_shortcodes',
      'update_callback' => null,
      'schema'          => null,
   ));
});

function page_do_shortcodes( $object, $field_name, $request ) {
   WPBMap::addAllMappedShortcodes();
   global $post;
   $post = get_post ($object['id']);
   $output['rendered'] = apply_filters( 'the_content', $post->post_content );
   return $output;
}

例如,您 重写从API返回的原始密钥,content键:(

注意:上面显示的代码唯一更改是传递给regession_rest_field的第二个参数功能

add_action( 'rest_api_init', function () {
   register_rest_field('page', 'content', array(
      'get_callback'    => 'page_do_shortcodes',
      'update_callback' => null,
      'schema'          => null,
   ));
});

function page_do_shortcodes( $object, $field_name, $request ) {
   WPBMap::addAllMappedShortcodes();
   global $post;
   $post = get_post ($object['id']);
   $output['rendered'] = apply_filters( 'the_content', $post->post_content );
   return $output;
}

You need to write code on the WordPress side, function.php.

For example, you can add another key to the response that returns from the call to the API by adding the following code to function.php (adding another key to the response called htmlcontent):

add_action( 'rest_api_init', function () {
   register_rest_field('page', 'htmlcontent', array(
      'get_callback'    => 'page_do_shortcodes',
      'update_callback' => null,
      'schema'          => null,
   ));
});

function page_do_shortcodes( $object, $field_name, $request ) {
   WPBMap::addAllMappedShortcodes();
   global $post;
   $post = get_post ($object['id']);
   $output['rendered'] = apply_filters( 'the_content', $post->post_content );
   return $output;
}

Alternatively, you can rewrite the original key that comes back from api, the content key :

(Note: The only change from the code shown above is the second parameter passed to the register_rest_field function)

add_action( 'rest_api_init', function () {
   register_rest_field('page', 'content', array(
      'get_callback'    => 'page_do_shortcodes',
      'update_callback' => null,
      'schema'          => null,
   ));
});

function page_do_shortcodes( $object, $field_name, $request ) {
   WPBMap::addAllMappedShortcodes();
   global $post;
   $post = get_post ($object['id']);
   $output['rendered'] = apply_filters( 'the_content', $post->post_content );
   return $output;
}

WordPress“ REST API” WPBackery Page Builder和Ionic

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

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