RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / user-239675

Yuriy Tigiev's questions

Martin Hope
Yuriy Tigiev
Asked: 2022-09-01 17:21:06 +0000 UTC

带锁的异步 - 功能

  • 0

不太清楚结构 async with lock:对于python。

我需要这样做,以便一次只执行一个函数来处理数据库。也就是说,对数据库有独占访问权。有几个功能可以与基础一起工作。

asyncioscheduler.add_job()按计划运行 N 个函数doWork1, doWork2, doWork3等,这些函数又调用函数与数据库 ( query1, query2, query3) 一起工作。问题是,async with lock 可以帮助限制同时执行一个用于处理数据库的函数吗?如果是这样,怎么做?这个想法是为这个任务使用一个队列,但它是可能的并且lock可以帮助简化实现。

https://docs-python.ru/standart-library/modul-asyncio-python/primitivy-sinhronizatsii-zadach-asyncio/


下面是正在解决的问题的工作伪代码。要求每单位时间只有一个分配的块工作async with lock:,无论正在执行哪个功能strategyBuy或strategySell这些功能的实例有多少正在运行。所有其他块必须“排队”并按顺序处理。一个问题是否可以 async with lock:帮助特定任务的给定实现?在示例的当前结果中,您可以看到条目Bought2.出现了多次,这表明 for 的代码段async with lock:是 strategyBuy并行执行的,这是不可接受的。理论上Bought2.,只有在数据库中没有记录或没有带有side: 'buy'and的记录时才会显示parent_id is null。在第一次运行时,这些条件都是 True(仅适用于第一个条目)。

import random
import asyncio
import aiosqlite as aiosql
from apscheduler.schedulers.asyncio import AsyncIOScheduler
import uuid
import numpy as np

myState = 0


async def dbConnect():

    sqlConn = await aiosql.connect('test.db')

    await sqlConn.execute("""
                        CREATE TABLE IF NOT EXISTS tbl(
                            id TEXT NOT NULL,
                            side TEXT NOT NULL,
                            price NUMERIC NOT NULL,
                            parent_id TEXT NULL,
                            buy_ids TEXT NULL
                        )""")

    return sqlConn


async def check():
    return (random.uniform(0, 1) < 0.05)


async def fetchPrice():
    return random.uniform(0, 1)


async def sell():
    pass


async def getOpenBuyOrders(sqlConn):

    cursor = await sqlConn.execute(
        """SELECT id, price, parent_id
            FROM tbl
            WHERE side='buy'
                AND parent_id IS NULL""")

    return await cursor.fetchall()


async def saveBuyOrder(sqlConn, price):
    buyId = uuid.uuid1()
    await sqlConn.execute(f"INSERT INTO tbl(id, price, side) VALUES (?, ?, 'buy')", (buyId.hex, price))
    await sqlConn.commit()


async def saveSellOrder(sqlConn, price, buyIDs):
    sellId = uuid.uuid1()
    await sqlConn.execute(f"INSERT INTO tbl (id, price, buy_ids, side) VALUES (?, ?, ?, 'sell')", (sellId.hex, price, str(buyIDs)))

    buyIDString = ','.join(['?']*len(buyIDs))
    await sqlConn.execute(f"UPDATE tbl SET parent_id = ? WHERE  id in (?)", (sellId.hex, buyIDString))

    await sqlConn.commit()


async def strategyBuy(sqlConn, i):

    lock = asyncio.Lock()

    if(await check()):

        currentPrice = await fetchPrice()

        async with lock:
            global myState
            myState = myState + 1
            openBuyOrders = await getOpenBuyOrders(sqlConn)
            if(openBuyOrders):
                avgPrice = np.mean([openBuyOrder[1]
                                    for openBuyOrder in openBuyOrders])

                if(avgPrice > (currentPrice * 1.05)):
                    await saveBuyOrder(sqlConn, currentPrice)
                    print(f"Bought1. Task: {i}, myState:{myState}")

            else:
                await saveBuyOrder(sqlConn, currentPrice)
                print(f"Bought2. Task: {i}, myState:{myState}")

    return None


async def strategySell(sqlConn, i):

    lock = asyncio.Lock()

    if(await check()):

        currentPrice = await fetchPrice()

        async with lock:
            global myState
            myState = myState + 1
            openBuyOrders = await getOpenBuyOrders(sqlConn)

            if(openBuyOrders):
                avgPrice = np.mean([openBuyOrder[1]
                                    for openBuyOrder in openBuyOrders])

                if((avgPrice * 1.05) < currentPrice):

                    buyIDs = [openBuyOrder[0]
                              for openBuyOrder in openBuyOrders]
                    await saveSellOrder(sqlConn, currentPrice, buyIDs)
                    print(f"Sold. Task: {i}, myState:{myState}")

    return None


async def main():

    sqlConn = await dbConnect()

    scheduler = AsyncIOScheduler()

    for i in range(100):
        scheduler.add_job(strategyBuy, 'interval', seconds=10, args=[sqlConn, i],
                          start_date='2000-01-01 00:00:00', timezone='UTC')

        scheduler.add_job(strategySell, 'interval', seconds=10, args=[sqlConn, i],
                          start_date='2000-01-01 00:00:00', timezone='UTC')

    scheduler.start()

if __name__ == "__main__":

    loop = asyncio.new_event_loop()
    task = loop.create_task(main())
    loop.run_forever()

结果

Bought2. Task: 55, myState:15
Bought2. Task: 13, myState:15
Bought2. Task: 80, myState:15
Bought2. Task: 57, myState:15
Bought2. Task: 24, myState:15
Bought2. Task: 44, myState:15
Bought2. Task: 18, myState:15
Bought2. Task: 7, myState:15
Bought2. Task: 49, myState:15
Bought1. Task: 86, myState:19
Bought1. Task: 97, myState:19
python python-3.x
  • 3 个回答
  • 52 Views
Martin Hope
Yuriy Tigiev
Asked: 2022-06-21 03:53:37 +0000 UTC

如何将作为字符串给出的时间从时区转换为 TSQL 中的日期时间?

  • 0

如何将作为字符串给出的时间从时区转换为 TSQL 中的日期时间?

SELECT CONVERT(datetime, '2006-12-12T23:45:12.000-08:00', 127)

Conversion failed when converting date and/or time from character string.
sql
  • 1 个回答
  • 10 Views
Martin Hope
Yuriy Tigiev
Asked: 2022-04-19 15:30:52 +0000 UTC

如何在javascript中实现类级别的事件生成和处理功能?

  • 0

如何在javascript中实现类级别的事件生成和处理功能?

下面的代码不起作用。如何修复它以使其工作?

class MyClass {
    func(){
        this.dispatch("Done");
    }

    addEventListener(){

    }

    dispatch(){
        
    }

}

var m = new MyClass();
m.addEventListener("Done", function(){
    console.log("Done");
});
m.func();
javascript
  • 1 个回答
  • 10 Views
Martin Hope
Yuriy Tigiev
Asked: 2022-02-03 02:08:18 +0000 UTC

DataFrame - 计算窗口内到最近的 Min/Max 元素的偏移量

  • 0

如何计算窗口内从当前元素到 DataFrame 中最近的 Min/Max 元素的偏移量?

import pandas as pd 

df = pd.DataFrame([1,20,3,40,5,60,12,11,12,4], columns=['close'])

print(df)
print(df.rolling(window=3).max())

期望的结果

在此处输入图像描述

python
  • 1 个回答
  • 10 Views
Martin Hope
Yuriy Tigiev
Asked: 2022-01-06 02:46:12 +0000 UTC

在函数中使用 try-except 的最佳实践是什么?

  • 3

在什么情况下你应该在函数中使用块try-except,在什么情况下不推荐或根本不可能使用它们?

捕获和处理异常和错误的最佳方法是什么 - 有或没有块?对开发人员的最佳实践感兴趣。


澄清评论。

我参加了课程,我自己在所有功能中都使用了 try 异常。最近,在使用 deno (JS) 时,一位经验丰富的开发人员告诉我根本不要使用try-catch它,除非在代码的情况下我无法预见所有可能的错误。

try-except在这方面,我有一个问题 -在调用某些库的所有函数中使用的正确性和合理性如何?

带有 try except 的函数代码示例。就异常处理而言,它的正确性和最优性如何?

async def GetPrices(symbol, exchange, limit=10):

    sellPrice = None
    buyPrice = None

    while True:
        try:
            orderBook = await exchange.fetchOrderBook(symbol, limit=limit)
            bidsPrice, bidsAmount = map(list, zip(*orderBook['bids'])) 
            asksPrice, asksAmount = map(list, zip(*orderBook['asks'])) 
            
            buyPrice = np.average(bidsPrice, weights = bidsAmount)
            sellPrice = np.average(asksPrice, weights = asksAmount)
            break

        except ccxt.RequestTimeout as e:
            log.error("Exchange %s  %s  %s", exchange.name, '[' + type(e).__name__ + ']', str(e)[0:200])
            # will retry
        except ccxt.DDoSProtection as e:
            log.error("Exchange %s  %s  %s", exchange.name, '[' + type(e).__name__ + ']', str(e)[0:200])
            # will retry
        except ccxt.ExchangeNotAvailable as e:
            log.error("Exchange %s  %s  %s", exchange.name, '[' + type(e).__name__ + ']', str(e)[0:200])
            # will retry
        except ccxt.ExchangeError as e:
            log.error("Exchange %s  %s  %s", exchange.name, '[' + type(e).__name__ + ']', str(e)[0:200])
            break  # won't retry
        except Exception as e:
            log.error("Exchange %s  %s  %s", exchange.name, '[' + type(e).__name__ + ']', str(e)[0:200])
            break  # won't retry

    return sellPrice, buyPrice
python
  • 1 个回答
  • 10 Views
Martin Hope
Yuriy Tigiev
Asked: 2022-01-02 19:27:22 +0000 UTC

并行启动具有不同参数的预定函数

  • 2

如何在 python > 3.8 中实现计划函数的并行启动,但使用不同的参数,以便脚本不绑定到操作系统的版本?

下面是一个示例配置文件。python 脚本将读取配置,然后根据配置中指定的频率,它应该以并行模式运行具有指定参数的 fnc 函数。例如,如果用户在 config 中指定了参数 1m, 1h, 1d,那么在每天的 00:00:00,具有参数 fnc(timeframe = 1m), fnc(timeframe = 1h), fnc( timeframe = 1d) 应该并行执行。如何以最优化和正确的方式实现给定的功能?

.ini 文件

1m:fnc(timeframe = 1m)
5m:fnc(timeframe = 5m)
1h:fnc(timeframe = 1h)
4h:fnc(timeframe = 4h)
1d:fnc(timeframe = 1d)
1w:fnc(timeframe = 1w)
python
  • 2 个回答
  • 10 Views
Martin Hope
Yuriy Tigiev
Asked: 2021-11-29 15:05:08 +0000 UTC

如何生成几个具有自己唯一ID的连续相同组合并将结果保存在df中?

  • 0

如何使用单行表达式生成多个连续相同的combinations具有自己唯一的相同的id并将结果存储在中df?

我们希望简化并提高执行速度的工作代码示例 col5 列包含生成集的唯一标识符gc

import itertools as iter
import pandas as pd 

gc = iter.combinations(range(1, 7), 4)
df = pd.DataFrame(gc, columns=['col1', 'col2', 'col3', 'col4'])

dfr = pd.DataFrame()
for i in range(1,4):
    dfi = df.copy()
    dfi['col5'] = i
    dfr = pd.concat([dfr, dfi])

dfr = dfr.reset_index().drop(columns='index')
print(dfr)

预期结果

      col1  col2  col3  col4  col5
0      1     2     3     4     1
1      1     2     3     5     1
2      1     2     3     6     1
3      1     2     4     5     1
4      1     2     4     6     1
5      1     2     5     6     1
6      1     3     4     5     1
7      1     3     4     6     1
8      1     3     5     6     1
9      1     4     5     6     1
10     2     3     4     5     1
11     2     3     4     6     1
12     2     3     5     6     1
13     2     4     5     6     1
14     3     4     5     6     1
15     1     2     3     4     2
16     1     2     3     5     2
17     1     2     3     6     2
18     1     2     4     5     2
19     1     2     4     6     2
20     1     2     5     6     2
21     1     3     4     5     2
22     1     3     4     6     2
23     1     3     5     6     2
24     1     4     5     6     2
25     2     3     4     5     2
26     2     3     4     6     2
27     2     3     5     6     2
28     2     4     5     6     2
29     3     4     5     6     2
30     1     2     3     4     3
31     1     2     3     5     3
32     1     2     3     6     3
33     1     2     4     5     3
34     1     2     4     6     3
35     1     2     5     6     3
36     1     3     4     5     3
37     1     3     4     6     3
38     1     3     5     6     3
39     1     4     5     6     3
40     2     3     4     5     3
41     2     3     4     6     3
42     2     3     5     6     3
43     2     4     5     6     3
44     3     4     5     6     3
python
  • 1 个回答
  • 10 Views
Martin Hope
Yuriy Tigiev
Asked: 2021-11-28 21:00:46 +0000 UTC

如何快速计算表格中每一行排序元素的差值的算术平均数、几何平均数和调和平均数?

  • 2

如何快速高效地计算一亿行表中每行排序元素差的算术、几何和调和平均值?

如果一行的两个元素之间的差为零,则必须将零替换为 1 才能计算平均值。

下面是代码。仅计数有效,ndf['r1']但由于apply. 我不知道如何快速计算几何和调和平均值。

import pandas as pd
import math

lst = [[1,23,45],[20,30,10],[60,15,2]]

df = pd.DataFrame(lst, columns = ['col1', 'col2', 'col3']) 
print(df)
ndf = pd.DataFrame()


ndf['r1'] = df.apply(lambda x: pd.Series(list(x.sort_values())),axis=1).diff(axis=1).iloc[:,1:].mean(axis=1)
#ndf['r2'] = (10 ** df.apply(lambda x: x.sort_values(),axis=1).diff(axis=1).iloc[:,1:].applymap(math.log10).sum(axis=1)) ** (1/len(columns)) 
#ndf['r3'] = len(df.columns)/( (1/df.diff(axis=1).iloc[:,1:]).sum(axis=1) )

print(ndf)
python
  • 1 个回答
  • 10 Views
Martin Hope
Yuriy Tigiev
Asked: 2021-11-14 02:41:54 +0000 UTC

如何将 Ubuntu 20.04 LTS 中的键盘布局切换设置为 Alt+Shift?

  • 2

如何将 Ubuntu 20.04 LTS 中的键盘布局切换设置为 Alt+Shift ?

ubuntu
  • 1 个回答
  • 10 Views
Martin Hope
Yuriy Tigiev
Asked: 2021-11-11 14:09:44 +0000 UTC

如何安装和配置 tensorflow 库以在具有 AMD GPU 和 Intel CPU 的 Windows 10 下的 python 3.8 中工作?

  • 0

如何安装和配置 tensorflow 库以在具有 AMD GPU 和 Intel CPU 的 Windows 10 下的 python 3.8 中工作?


在python 3.8下没有找到解决方案但是找到了3.6版本

https://docs.microsoft.com/en-us/windows/win32/direct3d12/gpu-tensorflow-windows?fbclid=IwAR2iMvnpc-yEMlpb9fHv6bjUgxEDbCPqp69rPk6MI5vZIl_voKQUFMu3nZg

python
  • 1 个回答
  • 10 Views
Martin Hope
Yuriy Tigiev
Asked: 2021-11-10 16:06:39 +0000 UTC

统计DataFrame列中非空值的个数,使用单行表达式将结果保存到同一张表中

  • 1

如何使用单行表达式计算列中非空值的数量,并将结果写入相同的列而不是非空值?

import pandas as pd 
import numpy as np 
import matplotlib.pyplot as plt
import seaborn as sns


sns.set()

d = {
     7:{"c1":5, "c2":8, "c3":10},
     5:{"c1":1, "c2":7, "c3":10}, 
     4:{"c1":1, "c2":6, "c3":8}, 
     3:{"c1":4, "c2":7, "c3":9},
     2:{"c1":3, "c2":5, "c3":6},
     1:{"c1":2, "c2":7, "c3":9}
    }

df = pd.DataFrame(d).T
r = (df
     .stack()
     .reset_index(name="col")
     .assign(x=1)
     .pivot_table(index="level_0", columns="col", values="x")
     .reindex(range(1,11), axis=1)
     .fillna(0)
     .astype("int8")
     .rename_axis(None)
     .rename_axis(None, axis=1))

print(r)

当前结果

   1  2  3  4  5  6  7  8  9  10
1  0  1  0  0  0  0  1  0  1   0
2  0  0  1  0  1  1  0  0  0   0
3  0  0  0  1  0  0  1  0  1   0
4  1  0  0  0  0  1  0  1  0   0
5  1  0  0  0  0  0  1  0  0   1
7  0  0  0  0  1  0  0  1  0   1

预期结果

   1  2  3  4  5  6  7  8  9  10
1  0  1  0  0  0  0  3  0  2   0
2  0  0  1  0  2  2  0  0  0   0
3  0  0  0  1  0  0  3  0  2   0
4  2  0  0  0  0  2  0  2  0   0
5  2  0  0  0  0  0  3  0  0   2
7  0  0  0  0  2  0  0  2  0   2
python
  • 1 个回答
  • 10 Views
Martin Hope
Yuriy Tigiev
Asked: 2021-11-06 03:09:43 +0000 UTC

seaborn如何将DataFrame值显示为阴影表?(海运)

  • 4

seaborn如何将DataFrame值显示为阴影表?

x 轴显示来自 DataFrame.values 范围的 c1、c2、c3 列的可能值

y 轴以降序显示记录的索引号 df.index

对于每一行(记录),其值在列 c1、c2、c3 中给出的正方形被涂上。

import pandas as pd 
import numpy as np 
import matplotlib.pyplot as plt
import seaborn as sns


sns.set()

d = {5:{"c1":1, "c2":7, "c3":10}, 4:{"c1":1, "c2":6, "c3":8}, 3:{"c1":4, "c2":7, "c3":9}}
df = pd.DataFrame(d).T


sns.relplot(data=df.T)
plt.show()

print(df)


   c1  c2  c3
5   1   7  10
4   1   6   8
3   4   7   9

预期结果。除了颜色之外,表格的格式必须与示例中的相同。

在此处输入图像描述

python
  • 2 个回答
  • 10 Views
Martin Hope
Yuriy Tigiev
Asked: 2020-08-01 13:57:47 +0000 UTC

大表的左连接查询优化 (mssql)

  • 0

如何优化以下查询?表中的记录数 > 1400 万。

此处提供了 7 月 1 日至 3 日期间“XVG/BTC”、“XRP/BTC”、“XMR/BTC”的初始数据示例

CREATE VIEW [dbo].[v_agg_day_trades] WITH SCHEMABINDING
AS
SELECT 
        LEFT(a.pair, CHARINDEX('/', a.pair)-1) Base,
        SUBSTRING(a.pair, CHARINDEX('/', a.pair)+1, 20) Quote,      
        a.pair as Pair,
        CAST(a.dt AS DATE) [date], 
        ROUND(AVG(100 * (CASE WHEN a.price > b.price THEN a.price / b.price - 1 WHEN a.price < b.price THEN b.price / a.price - 1 ELSE null END )), 8) PriceStep, 
        ROUND(MIN(a.price), 8) MinPrice,
        ROUND(MAX(a.price), 8) MaxPrice,
        ROUND(AVG(a.price), 8) AvgPrice,
        SUM(a.amount) BaseDayVolume,
        AVG(a.amount) BaseAvgVolume,
        MIN(a.amount) BaseMinVolume,
        MAX(a.amount) BaseMaxVolume,
        SUM(a.cost) QuoteDayVolume,
        AVG(a.cost) QuoteAvgVolume,
        MIN(a.cost) QuoteMinVolume,
        MAX(a.cost) QuoteMaxVolume,
        COUNT(*) Transactions
FROM dbo.trades a WITH(NOLOCK, NOWAIT) LEFT HASH JOIN dbo.trades b WITH(NOLOCK, NOWAIT) ON a.pair = b.pair AND a.tid + 1 = b.tid  AND a.side != b.side
GROUP BY 
        LEFT(a.pair, CHARINDEX('/', a.pair)-1),
        SUBSTRING(a.pair, CHARINDEX('/', a.pair)+1, 20),        
        a.pair, 
        cast(a.dt as date)

GO

CREATE TABLE [dbo].[trades](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [pair] [nvarchar](20) NOT NULL,
    [dt] [datetime2](7) NOT NULL,
    [ts] [bigint] NOT NULL,
    [tid] [int] NOT NULL,
    [side] [nvarchar](20) NOT NULL,
    [price] [float] NULL,
    [amount] [float] NULL,
    [cost] [float] NULL,
    [fee] [float] NULL
) ON [PRIMARY]
GO


USE [tb5]
GO

SET ANSI_PADDING ON
GO

/****** Object:  Index [ClusteredIndex-20200729-004955]    Script Date: 8/1/2020 09:54:42 ******/
CREATE CLUSTERED INDEX [ClusteredIndex-20200729-004955] ON [dbo].[trades]
(
    [pair] ASC,
    [ts] ASC,
    [tid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO

在此处输入图像描述

sql-server
  • 1 个回答
  • 10 Views
Martin Hope
Yuriy Tigiev
Asked: 2020-07-15 00:47:50 +0000 UTC

将唯一值快速批量插入到 mariadb 表中

  • 0

如何正确实现将唯一记录快速批量插入到 mariadb 表中?我想避免插入循环并按字段(对、数据时间、操作、价格)检查现有记录。

例如表table1有记录

pair, datatetime, action, price 
eth/btc, 2020-01-01 20:30:10, sell, 0.1

需要做批量插入

eth/btc, 2020-01-01 20:30:10, sell, 0.1 (не вставлять, пропустить поскольку есть запись в table1)
ltc/btc, 2020-02-01 20:35:10, buy, 0.5
eth/btc, 2020-01-01 21:30:10, buy, 0.1
ltc/btc, 2020-02-01 20:35:10, buy, 0.5 (не вставлять, пропустить поскольку запись в table1 появиться при ставке 2 записи)

预期结果

pair, datatetime, action, price 
eth/btc, 2020-01-01 20:30:10, sell, 0.1
ltc/btc, 2020-02-01 20:35:10, buy, 0.5
eth/btc, 2020-01-01 21:30:10, buy, 0.1
python
  • 2 个回答
  • 10 Views
Martin Hope
Yuriy Tigiev
Asked: 2020-04-24 03:27:34 +0000 UTC

如何在控制台中统计和显示 asyncio.gather() 中正在运行的协程的数量

  • 0

coroutine如何在控制台中统计和显示工作的人数asyncio.gather()?

您需要定期在控制台中显示有多少正在coroutines运行。

            tasks = ( self.FetchOHCL(pair, 7*12, '2h', False, 3, 60) for pair in pairs)
            results = await aio.gather(*tasks, return_exceptions=True)
python-3.x
  • 2 个回答
  • 10 Views
Martin Hope
Yuriy Tigiev
Asked: 2020-03-03 17:41:50 +0000 UTC

Map、reduce、pandas 代码优化

  • 1

以下是需要针对性能进行优化的工作代码。

任务描述:在生成的组合列表(df)中,需要找到满足条件的组合:

1) 对于 listNumbers 的每个组合 - 必须匹配 df 中每行 2 到 3 个项目。

2) 对于 df 中的每一行,必须满足条件 1) 对于 listNumbers 中的至少一个组合

import pandas as pd
import numpy as np
import itertools as iter
import math as mt
import timeit
from functools import reduce


listNumbers = [[1,2,3,4,5], [2,3,5,6,7]]

df = pd.DataFrame(iter.combinations(range(1, 8), 5))
print(df)

containsMap = list(map(lambda x: df.isin(x).sum(1).between(2,3), listNumbers)) 

containsReduce = reduce(lambda f, x: f | x, containsMap)

print(df[containsReduce])

初始生成列表

    0  1  2  3  4
0   1  2  3  4  5
1   1  2  3  4  6
2   1  2  3  4  7
3   1  2  3  5  6
4   1  2  3  5  7
5   1  2  3  6  7
6   1  2  4  5  6
7   1  2  4  5  7
8   1  2  4  6  7
9   1  2  5  6  7
10  1  3  4  5  6
11  1  3  4  5  7
12  1  3  4  6  7
13  1  3  5  6  7
14  1  4  5  6  7
15  2  3  4  5  6
16  2  3  4  5  7
17  2  3  4  6  7
18  2  3  5  6  7
19  2  4  5  6  7
20  3  4  5  6  7

最终筛选列表

    0  1  2  3  4
0   1  2  3  4  5
1   1  2  3  4  6
2   1  2  3  4  7
5   1  2  3  6  7
6   1  2  4  5  6
7   1  2  4  5  7
8   1  2  4  6  7
9   1  2  5  6  7
10  1  3  4  5  6
11  1  3  4  5  7
12  1  3  4  6  7
13  1  3  5  6  7
14  1  4  5  6  7
17  2  3  4  6  7
18  2  3  5  6  7
19  2  4  5  6  7
20  3  4  5  6  7

在实际任务中,df中的组合数为range(1, 101),listNumbers中的条目数约为20。

python
  • 1 个回答
  • 10 Views
Martin Hope
Yuriy Tigiev
Asked: 2020-02-28 18:59:34 +0000 UTC

在 centos 7 上为 openresty/nginx 设置 logrotate

  • 0

centos 7下需要为openresty/nginx配置logrotate。

我已经准备好配置,但是不正确。00:00,当前本地 access.log 日志被重置为零,但不会生成前一天的新日志文件。

openresty/nginx 在nobody 下运行

问题是如何解决前一天日志形成的问题。

/usr/local/openresty/nginx/logs/*log {
    create 0644 nobody nobody
    daily
    rotate 365
    missingok
    notifempty
    sharedscripts
    postrotate
    dateext
    postrotate
            [ ! -f /var/run/nginx.pid ] || kill -USR1 `cat /var/run/nginx.pid`
    endscript
}

权利

ls -l
total 40
drwx------. 2 nobody nobody 4096 Feb 20 14:32 client_body_temp
drwxr-xr-x. 2 root   root   4096 Mar  4 10:16 conf
drwx------. 2 nobody nobody 4096 Feb 20 14:32 fastcgi_temp
drwxr-xr-x. 2 root   root   4096 Feb 20 14:15 html
drwxr-xr-x. 2 nobody nobody 4096 Mar  4 10:28 logs
drwx------. 2 nobody nobody 4096 Feb 20 14:32 proxy_temp
drwxr-xr-x. 2 root   root   4096 Feb 20 14:15 sbin
drwx------. 2 nobody nobody 4096 Feb 20 14:32 scgi_temp
drwxr-xr-x. 2 root   root   4096 Feb 20 14:15 tapset
drwx------. 2 nobody nobody 4096 Feb 20 14:32 uwsgi_temp

ls -l
total 94928
-rw-r--r--. 1 nobody nobody 67091841 Mar  4 10:35 access.log
-rw-r--r--. 1 nobody nobody 30100415 Mar  4 10:34 error.log
-rw-r--r--. 1 root   root          6 Mar  4 10:28 nginx.pid
-rw-r--r--. 1 nobody nobody        0 Feb 25 14:44 test_access.log

流程

root     30438  0.0  0.0  37348  1608 ?        Ss   10:28   0:00 nginx: master process /usr/local/openresty/nginx/sbin/nginx
nobody   30439  0.0  0.0  39908  3288 ?        S    10:28   0:00 nginx: worker process
root     30591  0.0  0.0 112712   960 pts/1    S+   10:36   0:00 grep --color=auto nginx

PS 问题已解决。考虑到 Danil 的评论更新了配置,还修复了路径中 logrotate.d/nginx 文件中的错字 - /log/ /usr/local/openresty/nginx/logs/*log 中缺少字母 s

nginx
  • 1 个回答
  • 10 Views
Martin Hope
Yuriy Tigiev
Asked: 2020-02-02 16:34:37 +0000 UTC

如何正确地从函数返回参数列表并使用它

  • 0

有一个函数可以返回参数列表。这些参数存储在 lstVar 变量中。lstVar 中的变量值通过列表中所需变量的序号访问。一切正常,但并不方便,因为 func1 一直在开发中,您必须在 lstVar 列表中添加、删除或更改变量的顺序。因此,您需要记住更改代码中的序列号以获取所需变量的值。问题是什么是解决浊音问题的更简单、更漂亮的方法。我正在考虑使用字典而不是列表来通过变量名而不是索引获取数据。也许有一个更漂亮的解决方案,它并不意味着绑定到返回数据列表中的变量顺序。

def func1():
    return [val1, val2, .... val30]

lstVar = func1()
var3 = lstVar[2]
python
  • 1 个回答
  • 10 Views
Martin Hope
Yuriy Tigiev
Asked: 2020-01-04 00:43:32 +0000 UTC

如何检查另一个 python 脚本是否从 python 3.x 脚本运行?

  • 1

如何检查另一个 python 脚本是否从 python 3.x 脚本运行?

有两个脚本sript1.py和script2.py。有必要从脚本script1.py检查script2.py是否在同一台计算机上工作。

该解决方案应该在任何操作系统下工作。

python
  • 2 个回答
  • 10 Views
Martin Hope
Yuriy Tigiev
Asked: 2020-10-28 03:13:39 +0000 UTC

使用 throw 处理用户错误有多正确?

  • 2

使用 throw 处理用户错误有多正确?下面是工作代码,但我不确定它在风格上是否正确。如果在数据库中找不到用户,则会生成带有文本和错误代码的 throw,该代码在函数本身的 catch 级别被拦截,从中再次调用 throw,然后记录并从app.js 的函数。

async function login(req, res) {
  try {

    const db = req.app.db;

    params = { email: req.body.email, isDeleted: false }
    doc = await db.users.findOne(params);

    if (!doc) {
      const msg = `User ${req.body.email} not found.`;
      throw new Error(msg, 404);
    }

    const resultComparePassword = await bcrypt.compare(req.body.password, doc.password);

    if (!resultComparePassword) {
      const msg = 'Invalid password';
      throw new Error(msg, 401);
    };

    const token = jwt.sign(
      {
        id: doc._id,
        email: doc.email,
        role: doc.role
      },
      process.env.JWT_KEY,
      {
        expiresIn: "1h"
      }
    );

    const msg = {
      token: token
    };
    return res.status(200).json(msg);

  } catch (ex) {
      throw new Error(ex);
  }
};

app.js 代码

app.use((req, res, next) => {
    const error = new Error('Not Found');
    error.status = 404;
    next(error);
});

app.use((err, req, res, next) => {
    console.error(err.stack);
    next(err);
});

app.use((error, req, res, next) => {
    res.status(error.status || 500);
    res.json({
        error: {
            code: error.code,
            message: error.message
        }
    })
});
node.js
  • 1 个回答
  • 10 Views

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5