七禾

文章 评论 浏览 29

七禾 2025-02-21 00:17:30

在上使用。根据子句的顺序中的顺序,它将选择子集的第一个元素。例如:

SELECT distinct on (city.name) -- changed here
  city.name, 
  booking.booking_date as last_booking_date, 
  hotel.id as hotel_id, 
  hotel.photos ->> 0 as hotel_photo
FROM city 
INNER JOIN hotel
    ON city.id = hotel.city_id 
INNER JOIN booking 
    ON booking.hotel_id = hotel.id
WHERE 
    booking.booking_date = (SELECT MAX(booking_date) 
                            FROM booking
                            WHERE hotel_id = hotel.id)
ORDER BY city.name, booking.booking_date DESC; -- changed here

Use DISTINCT ON. It will pick the first element for the subset, according to the ordering in the ORDER BY clause. For example:

SELECT distinct on (city.name) -- changed here
  city.name, 
  booking.booking_date as last_booking_date, 
  hotel.id as hotel_id, 
  hotel.photos ->> 0 as hotel_photo
FROM city 
INNER JOIN hotel
    ON city.id = hotel.city_id 
INNER JOIN booking 
    ON booking.hotel_id = hotel.id
WHERE 
    booking.booking_date = (SELECT MAX(booking_date) 
                            FROM booking
                            WHERE hotel_id = hotel.id)
ORDER BY city.name, booking.booking_date DESC; -- changed here

如何在Postgresql的不同城市获得最新约会

七禾 2025-02-20 18:54:36

Mixins 不再称为 Mixins 在Coption Api 1 中。

但这只是被删除的名称。实际上,它们的功能是该API的面包和黄油。

首先,构图API允许您在其 setup()函数中移动组件的整个逻辑。这主要是全部。
一开始似乎并不是一笔大的交易,但是当您考虑它时,它实际上是因为它允许根据所需的任何标准对代码进行分组,而不一定是组件成员的类型 - 例如:(反应性)<代码>数据,计算方法观看 ers等...

其次,一旦定义了分组标准,可以采用代码使用 usestuff()函数,从其自己的文件中导出并将其导入任意数量的组件。

这些是新的 mixins Composables 。与钩子非常相似。


公平地说,我发现构图API比Mixins API更好。


1 - 从技术上讲,这是不正确的。他们仍然存在以使为向后兼容,但不再推荐它们。组合是前进的路径。

mixins are no longer called mixins in Composition API 1.

But it's only the name that has been dropped. Their functionality is, in fact, the bread and butter of this API.

First of all, Composition API allows you to move the entire logic of a component inside its setup() function. That's, mostly, what it is all about.
Might not seem that big of a deal at first but, when you think about it, it actually is, as it allows grouping code based on whatever criteria you want, not necessarily by the the type of component member - e.g: (reactive) data, computed, methods, watchers, etc...

Secondly, once a grouping criteria has been defined, the code can be taken out of the component, exported from its own file, and imported into any number of components, using a useStuff() function.

These are the new mixins: Composables. Quite similar to React hooks.


In fairness, I find Composition API a better name than Mixins API.


1 - technically, that's not true. They still exist for backwards compatibility, but they're no longer recommended. Composables are the path forward.

我想知道vue3中是否使用了混合蛋白功能

七禾 2025-02-20 09:07:21
db.test.insert({"Time" : new ISODate("2012-01-10") });


db.test.update({ criteria }, { newObj }, upsert, multi);
For example, to update all objects, consider

db.test.update( {}, { $set : { "time" : new ISODate("2012-01-11T03:34:54Z") } }, true, true);
db.test.insert({"Time" : new ISODate("2012-01-10") });


db.test.update({ criteria }, { newObj }, upsert, multi);
For example, to update all objects, consider

db.test.update( {}, { $set : { "time" : new ISODate("2012-01-11T03:34:54Z") } }, true, true);

更新MongoDB中的日期字段

七禾 2025-02-20 04:02:25

您可以这样做:

df.stack().std() 

You can do it this way:

df.stack().std() 

数据帧标准偏差

七禾 2025-02-20 00:39:25

您可以使用pandas方法

df['color'] = 'green'
df['color'] = df['color'].where(df['Set']=='Z', other='red')
# Replace values where the condition is False

或者

df['color'] = 'red'
df['color'] = df['color'].mask(df['Set']=='Z', other='green')
# Replace values where the condition is True

,您可以使用lambda函数使用方法变换

df['color'] = df['Set'].transform(lambda x: 'green' if x == 'Z' else 'red')

输出:

  Type Set  color
1    A   Z  green
2    B   Z  green
3    B   X    red
4    C   Y    red

性能比较来自@chai:

import pandas as pd
import numpy as np
df = pd.DataFrame({'Type':list('ABBC')*1000000, 'Set':list('ZZXY')*1000000})
 
%timeit df['color1'] = 'red'; df['color1'].where(df['Set']=='Z','green')
%timeit df['color2'] = ['red' if x == 'Z' else 'green' for x in df['Set']]
%timeit df['color3'] = np.where(df['Set']=='Z', 'red', 'green')
%timeit df['color4'] = df.Set.map(lambda x: 'red' if x == 'Z' else 'green')

397 ms ± 101 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
976 ms ± 241 ms per loop
673 ms ± 139 ms per loop
796 ms ± 182 ms per loop

You can use pandas methods where and mask:

df['color'] = 'green'
df['color'] = df['color'].where(df['Set']=='Z', other='red')
# Replace values where the condition is False

or

df['color'] = 'red'
df['color'] = df['color'].mask(df['Set']=='Z', other='green')
# Replace values where the condition is True

Alternatively, you can use the method transform with a lambda function:

df['color'] = df['Set'].transform(lambda x: 'green' if x == 'Z' else 'red')

Output:

  Type Set  color
1    A   Z  green
2    B   Z  green
3    B   X    red
4    C   Y    red

Performance comparison from @chai:

import pandas as pd
import numpy as np
df = pd.DataFrame({'Type':list('ABBC')*1000000, 'Set':list('ZZXY')*1000000})
 
%timeit df['color1'] = 'red'; df['color1'].where(df['Set']=='Z','green')
%timeit df['color2'] = ['red' if x == 'Z' else 'green' for x in df['Set']]
%timeit df['color3'] = np.where(df['Set']=='Z', 'red', 'green')
%timeit df['color4'] = df.Set.map(lambda x: 'red' if x == 'Z' else 'green')

397 ms ± 101 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
976 ms ± 241 ms per loop
673 ms ± 139 ms per loop
796 ms ± 182 ms per loop

如何创建一个新列,其中根据现有列选择值?

七禾 2025-02-19 23:50:17

如果满足条件并且在下一个条上没有条目,则可以取消待定订单。
只需使用 straging.cancel() straging.cancel_all()函数。将其添加到脚本的末尾:

if shortCondition[1] and strategy.position_size == 0 
    strategy.cancel_all()

You can cancel pending orders if the condition is met and there was no entry on the next bar.
Just use strategy.cancel() or strategy.cancel_all() function. Add this to the end of your script:

if shortCondition[1] and strategy.position_size == 0 
    strategy.cancel_all()

策略。输入如果仅在下一个栏中满足条件

七禾 2025-02-18 16:27:19

您正在循环中创建许多桌子。而不是在 .map()主体中输出整个表,而只输出行。将其他所有内容保持在该循环外:

return (
    <div>
        <div>
            <table className='data-table-container'>
                <tr>
                    <th>Customer Name</th>
                    <th>Phone Number</th>
                    <th>Loan Vehicle</th>
                    <th>Time Out</th>
                    <th>Time Due</th>
                </tr>
                {data.map(dat => {
                  return (
                    <tr>
                        <td>{dat.CustomerName}</td>
                        <td>{dat.PhoneNumber}</td>
                        <td>{dat.LoanVehicle}</td>
                        <td>{dat.TimeOut}</td>
                        <td>{dat.TimeDue}</td>
                    </tr>
                  );
                })}
            </table>
        </div>
    </div>
  );

&lt; tbody&gt; elements明确地使其更加清楚自己。

return (
    <div>
        <div>
            <table className='data-table-container'>
                <thead>
                    <tr>
                        <th>Customer Name</th>
                        <th>Phone Number</th>
                        <th>Loan Vehicle</th>
                        <th>Time Out</th>
                        <th>Time Due</th>
                    </tr>
                </thead>
                <tbody>
                    {data.map(dat => {
                      return (
                        <tr>
                            <td>{dat.CustomerName}</td>
                            <td>{dat.PhoneNumber}</td>
                            <td>{dat.LoanVehicle}</td>
                            <td>{dat.TimeOut}</td>
                            <td>{dat.TimeDue}</td>
                        </tr>
                      );
                    })}
                </tbody>
            </table>
        </div>
    </div>
  );

您可以通过明确分开&lt; thead&gt; and 当没有数据显示时,添加默认的“无记录”行,只是为了获得更多用户体验:

return (
    <div>
        <div>
            <table className='data-table-container'>
                <thead>
                    <tr>
                        <th>Customer Name</th>
                        <th>Phone Number</th>
                        <th>Loan Vehicle</th>
                        <th>Time Out</th>
                        <th>Time Due</th>
                    </tr>
                </thead>
                <tbody>
                    {data.length > 0 ? data.map(dat => {
                      return (
                        <tr>
                            <td>{dat.CustomerName}</td>
                            <td>{dat.PhoneNumber}</td>
                            <td>{dat.LoanVehicle}</td>
                            <td>{dat.TimeOut}</td>
                            <td>{dat.TimeDue}</td>
                        </tr>
                      );
                    }) : <tr><td colspan="5">No records found</td></tr>}
                </tbody>
            </table>
        </div>
    </div>
  );

You're creating many tables, in a loop. Instead of outputting the entire table in the .map() body, only output the rows. Keep everything else static outside of that loop:

return (
    <div>
        <div>
            <table className='data-table-container'>
                <tr>
                    <th>Customer Name</th>
                    <th>Phone Number</th>
                    <th>Loan Vehicle</th>
                    <th>Time Out</th>
                    <th>Time Due</th>
                </tr>
                {data.map(dat => {
                  return (
                    <tr>
                        <td>{dat.CustomerName}</td>
                        <td>{dat.PhoneNumber}</td>
                        <td>{dat.LoanVehicle}</td>
                        <td>{dat.TimeOut}</td>
                        <td>{dat.TimeDue}</td>
                    </tr>
                  );
                })}
            </table>
        </div>
    </div>
  );

You can make it a little more clear for yourself by explicitly separating <thead> and <tbody> elements:

return (
    <div>
        <div>
            <table className='data-table-container'>
                <thead>
                    <tr>
                        <th>Customer Name</th>
                        <th>Phone Number</th>
                        <th>Loan Vehicle</th>
                        <th>Time Out</th>
                        <th>Time Due</th>
                    </tr>
                </thead>
                <tbody>
                    {data.map(dat => {
                      return (
                        <tr>
                            <td>{dat.CustomerName}</td>
                            <td>{dat.PhoneNumber}</td>
                            <td>{dat.LoanVehicle}</td>
                            <td>{dat.TimeOut}</td>
                            <td>{dat.TimeDue}</td>
                        </tr>
                      );
                    })}
                </tbody>
            </table>
        </div>
    </div>
  );

You might even add a default "no records found" row when there's no data to display, just for a bit more user experience:

return (
    <div>
        <div>
            <table className='data-table-container'>
                <thead>
                    <tr>
                        <th>Customer Name</th>
                        <th>Phone Number</th>
                        <th>Loan Vehicle</th>
                        <th>Time Out</th>
                        <th>Time Due</th>
                    </tr>
                </thead>
                <tbody>
                    {data.length > 0 ? data.map(dat => {
                      return (
                        <tr>
                            <td>{dat.CustomerName}</td>
                            <td>{dat.PhoneNumber}</td>
                            <td>{dat.LoanVehicle}</td>
                            <td>{dat.TimeOut}</td>
                            <td>{dat.TimeDue}</td>
                        </tr>
                      );
                    }) : <tr><td colspan="5">No records found</td></tr>}
                </tbody>
            </table>
        </div>
    </div>
  );

使用React.js返回动态表

七禾 2025-02-18 13:16:27

这是您可以避免任何目录问题的方式

const path = require("path");
const multer = require("multer");

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, path.join(__dirname, "../uploads"));
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
    cb(null, file.fieldname + "-" + uniqueSuffix + file.originalname);
  },
});

Here is how you can avoid any directory issues

const path = require("path");
const multer = require("multer");

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, path.join(__dirname, "../uploads"));
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
    cb(null, file.fieldname + "-" + uniqueSuffix + file.originalname);
  },
});

Inoent:没有这样的文件或目录。

七禾 2025-02-18 06:46:10

首先,您可以识别异常值。该代码标识所有远离平均值的标准偏差的值。

outliers = df.loc [(df.value -df.value.mean())。abs()&gt; df.value.std() * 1] .index

然后您可以确定每个组的中位数:

中值= df.groupby('group')['value']。代码>

最后,找到异常值并替换为中位数:

df.loc [utliers,'value'] = mentians.loc [df.loc [outliers,'group'group'']]。to_list()

总共看起来像:

import pandas as pd
index = [0,1,2,3,4,5,6,7,8,9,10,11]
s = pd.Series(['A','A','A','A','A','A','B','B','B','B','B','B'],index= index)
t = pd.Series(['2022-06-28','2022-06-28','2022-06-28','2022-06-27','2022-06-27','2022-06-27',
               '2022-06-28','2022-06-28','2022-06-28','2022-06-27','2022-06-27','2022-06-27'],index= index)
r = pd.Series([1,2,1,2,3,10,2,3,2,3,4,20],index= index)
df = pd.DataFrame(s,columns = ['group'])
df['date'] = t
df['value'] = r
outliers = df.loc[(df.value - df.value.mean()).abs() > df.value.std() * 1].index
medians = df.groupby('group')['value'].median()
df.loc[outliers, 'value'] = medians.loc[df.loc[outliers, 'group']].values

输出:

   group        date  value
0      A  2022-06-28      1
1      A  2022-06-28      2
2      A  2022-06-28      1
3      A  2022-06-27      2
4      A  2022-06-27      3
5      A  2022-06-27      2
6      B  2022-06-28      2
7      B  2022-06-28      3
8      B  2022-06-28      2
9      B  2022-06-27      3
10     B  2022-06-27      4
11     B  2022-06-27      3

First you can identify outliers. This code identifies any values that are greater than one standard deviation away from the mean.

outliers = df.loc[(df.value - df.value.mean()).abs() > df.value.std() * 1].index

Then you can determine the median of each group:

medians = df.groupby('group')['value'].median()

Finally, locate the outliers and replace with the medians:

df.loc[outliers, 'value'] = medians.loc[df.loc[outliers, 'group']].to_list()

All together it looks like:

import pandas as pd
index = [0,1,2,3,4,5,6,7,8,9,10,11]
s = pd.Series(['A','A','A','A','A','A','B','B','B','B','B','B'],index= index)
t = pd.Series(['2022-06-28','2022-06-28','2022-06-28','2022-06-27','2022-06-27','2022-06-27',
               '2022-06-28','2022-06-28','2022-06-28','2022-06-27','2022-06-27','2022-06-27'],index= index)
r = pd.Series([1,2,1,2,3,10,2,3,2,3,4,20],index= index)
df = pd.DataFrame(s,columns = ['group'])
df['date'] = t
df['value'] = r
outliers = df.loc[(df.value - df.value.mean()).abs() > df.value.std() * 1].index
medians = df.groupby('group')['value'].median()
df.loc[outliers, 'value'] = medians.loc[df.loc[outliers, 'group']].values

Output:

   group        date  value
0      A  2022-06-28      1
1      A  2022-06-28      2
2      A  2022-06-28      1
3      A  2022-06-27      2
4      A  2022-06-27      3
5      A  2022-06-27      2
6      B  2022-06-28      2
7      B  2022-06-28      3
8      B  2022-06-28      2
9      B  2022-06-27      3
10     B  2022-06-27      4
11     B  2022-06-27      3

熊猫根据两列的组查找和替换异常值

七禾 2025-02-17 00:57:41

如果需要,每行的最大唯一值,对于每个类别而不是最大值,仅限上一行使用:

s = df[["lvl1", "lvl2", "lvl3"]].nunique(axis=1)
#if need test number of non missing values use count
#s = df[["lvl1", "lvl2", "lvl3"]].count(axis=1)

df = df[~s.duplicated(keep='last') | s.eq(s.max())]
print (df)
  lvl1 lvl2 lvl3  value
2   aa   xx   ww      7
3   aa   xx   qq     22
6   bb   yy   rr     18
7   bb   zz  NaN     47
8   cc  NaN  NaN     10
9   aa   sa   jj      2

If need filter rows by maximum unique values per rows and for each category not maximum only last row use:

s = df[["lvl1", "lvl2", "lvl3"]].nunique(axis=1)
#if need test number of non missing values use count
#s = df[["lvl1", "lvl2", "lvl3"]].count(axis=1)

df = df[~s.duplicated(keep='last') | s.eq(s.max())]
print (df)
  lvl1 lvl2 lvl3  value
2   aa   xx   ww      7
3   aa   xx   qq     22
6   bb   yy   rr     18
7   bb   zz  NaN     47
8   cc  NaN  NaN     10
9   aa   sa   jj      2

过滤数据框以获取树结构的叶子

七禾 2025-02-16 20:55:17

一个人可以指定令牌,但还必须指定访问密钥和秘密密钥:

s3 = fs.S3FileSystem(access_key="", 
                     secret_key="",
                     session_token="")

一个人还必须实现一些方法来解析〜/.aws/cordentials文件以获取访问这些值或每次手动执行

one can specify a token, but must also specify access key and secret key :

s3 = fs.S3FileSystem(access_key="", 
                     secret_key="",
                     session_token="")

one would also have to implement some method to parse the ~/.aws/credentials file to get access to these values or do it manually each time

将AWS配置文件与FS S3Filesystem一起使用

七禾 2025-02-16 14:15:26

我在用户名和文档上传时面临着相同的问题,然后在控制台侧给出了此错误

"Test.js:102 
POST http://localhost:1337/api/jobs-forms 400 (Bad Request)
dispatchXhrRequest @ xhr.js:258
xhr @ xhr.js:49
dispatch request @ dispatchRequest.js:51
_request @ Axios.js:170
request @ Axios.js:40
httpMethod @ Axios.js:209
wrap @ bind.js:5
handleSubmit @ Test.js:102
await in handleSubmit (async)
callCallback @ react-dom.development.js:4164
invokeGuardedCallbackDev @ react-dom.development.js:4213
invokeGuardedCallback @ react-dom.development.js:4277
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:4291
executeDispatch @ react-dom.development.js:9041
processDispatchQueueItemsInOrder @ react-dom.development.js:9073
processDispatchQueue @ react-dom.development.js:9086
dispatchEventsForPlugins @ react-dom.development.js:9097
(anonymous) @ react-dom.development.js:9288
batchedUpdates$1 @ react-dom.development.js:26140
batchedUpdates @ react-dom.development.js:3991
dispatchEventForPluginEventSystem @ react-dom.development.js:9287
dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay @ react-dom.development.js:6465
dispatchEvent @ react-dom.development.js:6457
dispatchDiscreteEvent @ react-dom.development.js:6430
Show 22 more frames
Show less
Test.js:113 Error: AxiosError {message: 'Request failed with status code 400', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}"

I am facing the same issues at the time userName and document upload then given this error on console side but document upload on strapi dashboard in media library

"Test.js:102 
POST http://localhost:1337/api/jobs-forms 400 (Bad Request)
dispatchXhrRequest @ xhr.js:258
xhr @ xhr.js:49
dispatch request @ dispatchRequest.js:51
_request @ Axios.js:170
request @ Axios.js:40
httpMethod @ Axios.js:209
wrap @ bind.js:5
handleSubmit @ Test.js:102
await in handleSubmit (async)
callCallback @ react-dom.development.js:4164
invokeGuardedCallbackDev @ react-dom.development.js:4213
invokeGuardedCallback @ react-dom.development.js:4277
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:4291
executeDispatch @ react-dom.development.js:9041
processDispatchQueueItemsInOrder @ react-dom.development.js:9073
processDispatchQueue @ react-dom.development.js:9086
dispatchEventsForPlugins @ react-dom.development.js:9097
(anonymous) @ react-dom.development.js:9288
batchedUpdates$1 @ react-dom.development.js:26140
batchedUpdates @ react-dom.development.js:3991
dispatchEventForPluginEventSystem @ react-dom.development.js:9287
dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay @ react-dom.development.js:6465
dispatchEvent @ react-dom.development.js:6457
dispatchDiscreteEvent @ react-dom.development.js:6430
Show 22 more frames
Show less
Test.js:113 Error: AxiosError {message: 'Request failed with status code 400', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}"

将图像与ReactJ中的strapi API链接到内容

七禾 2025-02-16 06:12:07

新的C ++标准有两个部分:语言功能和标准库组件。

正如您的意思是 新标准,语言本身的变化(例如,范围)几乎没有问题(有时在具有较新的标准语言功能的第三方图书馆标题中存在冲突)。

但是标准库...

每个编译器版本都具有C ++标准库的实现(libstdc ++带有gcc,libc ++带有clang,ms C ++标准库,带有VC ++,...同样在某些情况下,您可以使用其他标准库的实现,而不是提供的编译器。您应该关心的是将较旧的标准库实施与更新的库链接起来。

第三方库与您的代码之间可能发生的冲突是链接到该第三方库的标准库(和其他库)。

New C++ standards are come in two parts: language features and standard library components.

As you mean by new standard, changes in language itself (e.g. ranged-for) there's almost no problem (sometimes conflicts are exists in 3rd party library headers with newer standard language features).

But standard library...

Each compiler version comes with an implementation of C++ standard library (libstdc++ with gcc, libc++ with clang, MS C++ standard library with VC++,...) and exactly one implementaion, not many implementation for each standard version. Also in some cases you may use other implementation of standard library than compiler provided. What you should care is linking an older standard library implementation with a newer one.

The conflict that could occur between 3rd party libraries and your code is the standard library (and other libraries) that links to that 3rd party libraries.

链接C&#x2B; 17,c&#x2b;&#x2b;&#x2B; 14和11对象是安全的

七禾 2025-02-16 01:04:01

您可以使用dataframe构造函数,然后 groupby.agg

df = pd.DataFrame(res1_, columns=['docid', 'setid'])
group = df['docid'].ne(df['docid'].shift()).cumsum()
df = df.groupby(group.values).agg({'docid': 'first', 'setid': list})

输出:

  docid   setid
1    z1  [1, 2]
2    x1     [1]
3    x2     [1]
4    x1     [3]
5    z1     [1]

You can use the DataFrame constructor, then GroupBy.agg:

df = pd.DataFrame(res1_, columns=['docid', 'setid'])
group = df['docid'].ne(df['docid'].shift()).cumsum()
df = df.groupby(group.values).agg({'docid': 'first', 'setid': list})

output:

  docid   setid
1    z1  [1, 2]
2    x1     [1]
3    x2     [1]
4    x1     [3]
5    z1     [1]

将元组转换为数据框中的分组行,而无需更改顺序

七禾 2025-02-15 06:18:31

需要检查的某些内容:您是否还有其他内容覆盖 node.node 中的节点版本?根据 https://render.com/docs/node-version .Node 值将被

  1. node_version 环境变量
  2. a .node-version file 文件文件 file a repo
  3. a .nvmrc 。 >文件在您的存储库的根部。

另外,当您在渲染上部署时,您是否将节点选择为环境

这是我创建的一个小测试,以验证奇数节点版本编号在渲染上起作用,并验证 preplaceAll()在节点v17.4.0中起作用。

代码(也 https://github.com/crcastle/test-replaceall < /a>)

server.js

const http = require('http')


const requestListener = function (req, res) {
  const orig = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';

  const monkey = orig.replaceAll('dog', 'monkey');
  // expected output: "The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really lazy?"
  
  // global flag required when calling replaceAll with regex
  const regex = /Dog/ig;
  const ferret = orig.replaceAll(regex, 'ferret');
  // expected output: "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?"

  const version = process.version;

  res.writeHead(200);
  res.end(`Original: ${orig}\nMonkey: ${monkey}\nFerret: ${ferret}\nI am Node version ${version}`);
};

const HOST = "0.0.0.0";
const PORT = process.env.PORT || 10000;
const server = http.createServer(requestListener);
server.listen(PORT, HOST, () => {
  console.log(`Server is listening on http://${HOST}:${PORT}`);
});

package.json

{
  "name": "test-replaceall",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "engines": {
    "node": "17.4.0"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

output (也临时部署到 https://test-replaceall.onrender.com

Original: The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?
Monkey: The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really lazy?
Ferret: The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?
I am Node version v17.4.0

构建和部署日志

Jun 15 04:07:08 PM  ==> Cloning from https://github.com/crcastle/test-replaceall...
Jun 15 04:07:09 PM ==> Checking out commit 17972cbecfdeafc0eb1c4a09cad07400ab5c8bc1 in branch main
Jun 15 04:07:25 PM ==> Detected Node version 17.4.0
Jun 15 04:07:26 PM ==> Running build command 'npm i'...
Jun 15 04:07:27 PM up to date, audited 1 package in 297ms
Jun 15 04:07:27 PM found 0 vulnerabilities
Jun 15 04:07:43 PM ==> Uploading build...
Jun 15 04:07:49 PM ==> Build successful

Some things to check: Do you maybe have something else overriding the Node version set in engines.node? According to https://render.com/docs/node-version, the engines.node value will be overridden by

  1. A NODE_VERSION environment variable
  2. A .node-version file at the root of your repo
  3. A .nvmrc file at the root of your repo.

Also, when you deploy on Render, are you selecting Node as the Environment?

Here's a small test deploy to Render I created to verify that odd Node version numbers work on Render and also to verify that replaceAll() works in Node v17.4.0.

Code (also at https://github.com/crcastle/test-replaceall)

server.js:

const http = require('http')


const requestListener = function (req, res) {
  const orig = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';

  const monkey = orig.replaceAll('dog', 'monkey');
  // expected output: "The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really lazy?"
  
  // global flag required when calling replaceAll with regex
  const regex = /Dog/ig;
  const ferret = orig.replaceAll(regex, 'ferret');
  // expected output: "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?"

  const version = process.version;

  res.writeHead(200);
  res.end(`Original: ${orig}\nMonkey: ${monkey}\nFerret: ${ferret}\nI am Node version ${version}`);
};

const HOST = "0.0.0.0";
const PORT = process.env.PORT || 10000;
const server = http.createServer(requestListener);
server.listen(PORT, HOST, () => {
  console.log(`Server is listening on http://${HOST}:${PORT}`);
});

package.json:

{
  "name": "test-replaceall",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "engines": {
    "node": "17.4.0"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Output (also temporarily deployed to https://test-replaceall.onrender.com)

Original: The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?
Monkey: The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really lazy?
Ferret: The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?
I am Node version v17.4.0

Build and deploy log

Jun 15 04:07:08 PM  ==> Cloning from https://github.com/crcastle/test-replaceall...
Jun 15 04:07:09 PM  ==> Checking out commit 17972cbecfdeafc0eb1c4a09cad07400ab5c8bc1 in branch main
Jun 15 04:07:25 PM  ==> Detected Node version 17.4.0
Jun 15 04:07:26 PM  ==> Running build command 'npm i'...
Jun 15 04:07:27 PM  up to date, audited 1 package in 297ms
Jun 15 04:07:27 PM  found 0 vulnerabilities
Jun 15 04:07:43 PM  ==> Uploading build...
Jun 15 04:07:49 PM  ==> Build successful ????
Jun 15 04:07:49 PM  ==> Deploying...
Jun 15 04:08:25 PM  ==> Detected Node version 17.4.0
Jun 15 04:08:25 PM  ==> Starting service with 'node server.js'
Jun 15 04:08:25 PM  Server is listening on http://0.0.0.0:10000

部署到render.com服务器时

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

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