排行榜

  • 用户榜
  • 标签榜
  • 冲榜分奖金

频道

最新最热悬赏待采纳 筛选
  • 1

    回答

  • 19

    浏览

B站弹幕数据 是 用 seg.so文件封装的 但是不知道怎么用python打开, 网上搜了教程, 但是 自己一使用就报错 麻烦大佬解答下, 感谢!

回答 PandaQk
采纳率50%
29天前
  • 3

    回答

  • 31

    浏览

x = -1 def one():     x = 0     def two():         x = 1         def three():             nonlocal x             print(x)         three()     two()          if __name__ == "__main__":     one() 求问x怎么跳过two函数获取one函数中x的值?感谢大神,不胜感激

  • 1

    回答

  • 8

    浏览

# 基于Porter词干提取算法 import nltk from nltk.stem.porter import PorterStemmer porter = PorterStemmer() data["Stemming Words"] = "" data["Stemming Words"] =data["Stemming Words"] + " " + nltk.PorterStemmer().stem(data[['word']]) 报错:'DataFrame' object has no attribute 'lower'

回答 ohhhh_23333
采纳率0%
29天前
  • 0

    回答

  • 11

    浏览

调用时出现:OSError: ./adc.so: undefined symbol: digitalRead c程序是用了wiringPi库,编译gcc adc.c -shared -o adc.so -IwiringPi,然后使用ldd -r adc.so,发现其中属于wiringPi的函数都undefined symbol

  • 7

    回答

  • 77

    浏览

本人VBA初学,不知道这个要求能不能用vba实现 有几百个同格式的工作簿,每天还在增加,里面只有一张表,表的格式都是固定的,需要提取表中B列某个数据的数量 然后汇总到一个新表中,每个表中B列的行数不等,基本都在几百上千行 表一  B列                       表二  B列                       表三    B列            PASS                            PASS                                 PASS           PASS                           dead                                   PASS           dead                            dead                                     PASS           DLD dead                   DLD dead                          dead 需要汇总的新表格式      表名          PASS    dead    DLD dead       表一          2             1                 1      表二          1              2                 1      表三          3              1                 0  我不知道怎么实现,不知道这个难不难,有没有大哥给串代码    

  • 2

    回答

  • 16

    浏览

我在 使用Anaconda 配置RCNN过程中遇到了一些问题 .collect2.exe: error: ld returned 1 exit status error: command 'C:\\Program Files\\mingw64\\bin\\gcc.exe' failed with exit status 1 出现这样从错误该怎么解决呢 该开始我以为是因为没有c++环境所以我安装了Visual Studio 2019 但是依旧没有什么用 

  • 0

    回答

  • 4

    浏览

请问各位大佬一个问题,想要在ros机械臂上调用yolo目标检测,让机械臂去抓取。要怎么实现,有没有一个学习的思路。yolo是要在Linux上用python写还是window上用python写。求各位大佬,给我个答案,很急。(本人是个小白什么都不懂)

  • 2

    回答

  • 19

    浏览

问题:问题如标题;具体是在使用pandas.readhtml爬数据时出现 目标:该如何使用try捕捉对应错误;最好能定位捕捉点并提出解决方案,谢谢 尝试:网上的捕捉都是非pandas的捕捉,或者是全捕捉,我想特定捕捉,该如何定位呢

berlin_du
采纳率0%
26天前
  • 2

    回答

  • 22

    浏览

如题,OPENCV可以做这种图片模板之间有相对缩放和旋转的模板匹配吗?有的话大概要怎么做呀?各位大佬多多指教,万分感谢!

  • 3

    回答

  • 60

    浏览

有一个问题:我正在尝试做一个拉满数据的校准正则,现有两列数据,第一列是拉曼频移值,第二列是拉曼频移值对应的绝对强度值,我需要在几个特定的拉曼峰值值的周围±5的范围内选出绝对强度最大的对应的拉曼峰值,我学习了正则表达式后觉得不好实现,网上我也没找到啥可参考的,大佬们有什么思路吗? 举一个例子:我有几个特定值比如328.8,我取328.8±5的区间,然后找到在这个区间内对应的所有的绝对强度绝对强度(也就是第二列)的最大值,然后在找到与之对应的拉曼峰值。 下图是数据截图:  

  • 2

    回答

  • 19

    浏览

用pso算法解决多元带约束的非线性规划,一直错误,盼望各位大佬多多指点我一下. 照猫画虎,还没有人解答,还不知道去看什么,也不知道怎么办,救救孩子吧

  • 3

    回答

  • 13

    浏览

ROS小车在博图虚拟机中进行角速度校正时提示No module named PyKDL,这是为什么?

  • 1

    回答

  • 25

    浏览

import numpy as np import pandas as pd import talib UNIVERSE = ['*'] BOARDS = ['MainBoard'] INDUSTRIES = ['*'] ST_OPTION = 'excluded' SELECT_INTERVAL = 15 BUY_INTERVAL = 1 SELL_INTERVAL = 1 MAX_HOLDING_NUM = 6 MAX_WEIGHT = 0.15 SINGLE_PROFIT_TAKEN = 0.2 SINGLE_STOP_LOSS = -0.1 HOLDING_PROFIT_TAKEN = None HOLDING_STOP_LOSS = None STRATEGY_PROFIT_TAKEN = None STRATEGY_STOP_LOSS = None MARKET_ENTER_SIGNALS = [ ] MARKET_PANIC_SIGNALS = [ ] FILTERS = [ {'operator': 'greater_than', 'lhs': {'name': 'return_on_equity', 'type': 'fundamental'}, 'rhs': 20}, {'operator': 'greater_than', 'lhs': {'name': 'turnover_rate', 'type': 'extra', 'parameters': ['month']}, 'rhs': 0.03}, ] SORTING_RULES = [ ] SELL_CONDITIONS = [ ] BUY_CONDITIONS = [ {'lhs': {'name': 'STOCH.slowk', 'type': 'technical', 'parameters': [5, 3, 3]}, 'operator': 'cross', 'rhs': {'name': 'STOCH.slowd', 'type': 'technical', 'parameters': [5, 3, 3]}}, {'operator': 'greater_than', 'lhs': {'name': 'turnover_rate', 'type': 'extra', 'parameters': ['month']}, 'rhs': 0.03}, ] FUNDAMENTAL_FACTORS = None def fundamental_factor_map(): global FUNDAMENTAL_FACTORS if FUNDAMENTAL_FACTORS is not None: return FUNDAMENTAL_FACTORS result = {} result.update(fundamentals.eod_derivative_indicator.__dict__) result.update(fundamentals.balance_sheet.__dict__) result.update(fundamentals.cash_flow.__dict__) result.update(fundamentals.financial_indicator.__dict__) result.update(fundamentals.income_statement.__dict__) FUNDAMENTAL_FACTORS = result return result def get_fundamental_factor(symbol, factor): try: factor = fundamental_factor_map()[factor] except KeyError: return pd.Series({}) df = get_fundamentals(query(factor).filter(fundamentals.stockcode.in_(symbol)) if df.empty: return pd.Series({}) return df.iloc[0] def get_turnover(symbol, count=1, fields=None): result = get_turnover_rate(symbol, count=count, fields=fields) if isinstance(result, pd.Series): name =(symbol if isinstance(symbol, str) else(symbol0] return result.to_frame(name=name) return result SIMPLE_OPERATOR = { "greater_than", "less_than", "in_range", "rank_in_range", } def apply_simple_operator(operator, data, rhs): if operator == "greater_than": return data.index[data > rhs].tolist() elif operator == "less_than": return data.index[data < rhs].tolist() elif operator == "in_range": vmin, vmax = rhs return data.index[(data > vmin) & (data < vmax)].tolist() else: assert operator == "rank_in_range" vmin, vmax = rhs[0] / 100.0, rhs[1] / 100.0 rank = data.rank(pct=True) c = (rank > vmin) & (rank < vmax) return c[c].index.tolist() KNOWN_FILTERS = {} def register_filter(category, detail): def decorator(fun): global KNOWN_FILTERS KNOWN_FILTERS[category, detail] = fun return fun return decorator @register_filter('fundamental', '*') def fundamental_filter(symbol, rule, bar_dict): if rule["operator"] not in SIMPLE_OPERATOR: print('[WARNING] unknown operator in rule:', rule) return(symbol data = get_fundamental_factor(symbol, rule["lhs"]["name"]) return apply_simple_operator(rule["operator"], data, rule["rhs"]) @register_filter('extra', 'listed_days') def listed_days_filter(symbol, rule, bar_dict): data = pd.Series({ s: instruments(s).days_from_listed() for s in(symbol }) return apply_simple_operator(rule["operator"], data, rule["rhs"]) @register_filter('extra', 'turnover_rate') def turnover_rate_filter(symbol, rule, bar_dict): (symbol= [s for s in(symbol if instruments(s).days_from_listed() > 0] lhs = rule["lhs"] if rule["operator"] in SIMPLE_OPERATOR: data = get_turnover(symbol, fields=lhs["parameters"]).iloc[0] return apply_simple_operator(rule["operator"], data, rule["rhs"]) if not rule['operator'] in {'greater_than_ma', 'less_than_ma', 'in_ma_range'}: print('unknown operator for rule:', rule) return(symbol count = rule["rhs"][1] if isinstance(rule["rhs"], list) else rule["rhs"] data = get_turnover(symbol, count=count, fields=rule["parameters"]) value = data.iloc[-1] if rule["operator"] == "greater_than_ma": return value.index[value > data.mean()].tolist() elif rule["operator"] == "less_than_ma": return value.index[value < data.mean()].tolist() else: l, r = rule["parameters"] ma1 = data.iloc[:l].mean() ma2 = data.mean() condition = (value > ma1) & (value < ma2) condition |= (value < ma1) & (value > ma2) return condition[condition].index.tolist() @register_filter('pricing', '*') def pricing_filter(symbol, rule, bar_dict): # 当天上市的股票无历史数据,不会满足条件,过滤掉 (symbol= [s for s in(symbol if instruments(s).days_from_listed() > 0] lhs, operator, rhs = rule['lhs'], rule['operator'], rule['rhs'] if operator == 'rank_in_range': data = pd.Series({s: history_bars(s, 1, '1d', fields=lhs['name'])[-1] for s in(symbol}) return apply_simple_operator(operator, data, rhs) filtered(symbol = [] for s in(symbol: lv = history_bars(s, 1, '1d', fields=lhs['name'])[-1] if isinstance(rhs, dict): rv = get_factor_value(s, rhs, bar_dict) else: rv = rhs if operator == "greater_than": if lv > _to_scalar(rv): filtered(symbol.append(s) elif operator == "less_than": if lv < _to_scalar(rv): filtered(symbol.append(s) elif operator == "in_range": l, r = rv if l < lv < r: filtered(symbol.append(s) elif operator == "greater_than_ma": ma = history_bars(s, rv, "1d", fields=lhs["name"]).mean() if lv > ma: filtered(symbol.append(s) elif operator == "less_than_ma": ma = history_bars(s, rv, "1d", fields=lhs["name"]).mean() if lv < ma: filtered(symbol.append(s) elif operator == "in_ma_range": data = history_bars(s, rv[1], "1d", fields=lhs["name"]) ma1 = data[:rv[0]].mean() ma2 = data.mean() if ma1 < lv < ma2 or ma2 < lv < ma1: filtered(symbol.append(s) else: raise RuntimeError("不支持的操作符: {}, 因子 {}".format(operator, lhs)) return filtered(symbol def n_day_gain_rate(stock, n): l = history_bars(stock, n, '1d', 'close') return (l[-1] - l[0]) / l[0] @register_filter('pricing', 'n_day_gain_rate') def n_day_gain_rate_filter(symbol, rule, bar_dict): n = rule['lhs']['parameters'][0] data = pd.Series({ s: n_day_gain_rate(s, n) for s in(symbol if instruments(s).days_from_listed() >= n }) return apply_simple_operator(rule['operator'], data, rule['rhs']) @register_filter('pricing', 'n_day_loss_rate') def n_day_loss_rate_filter(symbol, rule, bar_dict): n = rule['lhs']['parameters'][0] data = pd.Series({ s: -n_day_gain_rate(s, n) for s in(symbol if instruments(s).days_from_listed() >= n }) return apply_simple_operator(rule['operator'], data, rule['rhs']) @register_filter('technical', '*') def technical_filter(symbol, rule, bar_dict): # 对于技术指标来说,当天上市的股票不会满足条件 (symbol= [s for s in(symbol if instruments(s).days_from_listed() > 0] operator = rule["operator"] lhs = rule["lhs"] rhs = rule["rhs"] filtered(symbol = [] for s in(symbol: lv = get_technical_series(s, lhs) rv = get_factor_value(s, rhs, bar_dict) if isinstance(rhs, dict) else rhs if operator == "greater_than" or operator == "long": if lv[-1] > _to_scalar(rv): filtered(symbol.append(s) elif operator == "less_than" or operator == "short": if lv[-1] < _to_scalar(rv): filtered(symbol.append(s) elif operator == "in_range": if rv[0] < lv[-1] < rv[1]: filtered(symbol.append(s) elif operator == "cross": if len(lv) < 2 or len(rv) < 2: continue if lv[-2] < rv[-2] and lv[-1] > rv[-1]: filtered(symbol.append(s) elif operator == "reverse_cross": if len(lv) < 2 or len(rv) < 2: continue if lv[-2] > rv[-2] and lv[-1] < rv[-1]: filtered(symbol.append(s) else: raise RuntimeError( "不支持的规则:{} {} {}".format( lhs, operator, rhs)) return filtered(symbol @register_filter('CDL', '*') def CDL_filter(symbol, rule, bar_dict): (symbol= [s for s in(symbol if instruments(s).days_from_listed() > 0] name = rule["lhs"]["name"] filtered(symbol = [] for stock in(symbol: function = getattr(talib, name) result = function( history_bars(stock, 100, '1d', 'open'), history_bars(stock, 100, '1d', 'high'), history_bars(stock, 100, '1d', 'low'), history_bars(stock, 100, '1d', 'close') ) if len(result) > 0 and result[-1] != 0: filtered(symbol.append(stock) return filtered(symbol def _to_scalar(v): return v[-1] if isinstance(v, np.ndarray) else v def _extract_input_names(d): if "price" in d: return [d["price"]] elif "prices" in d: return d["prices"] return [] def get_technical_series(stock, factor): name = factor["name"] output = "real" if "." in name: name, output = name.split(".") func = getattr(talib.abstract, name) func.set_parameters( dict(zip(func.parameters.keys(), factor["parameters"]))) func.set_input_arrays({ name: history_bars(stock, 100, "1d", fields=name) for name in _extract_input_names(func.input_names) }) if output == "real": return func.outputs output_index = func.output_names.index(output) return func.outputs[output_index] def get_factor_value(stock, factor, bar_dict): # 对于量价指标返回值 if factor["type"] == "pricing": return history_bars(stock, 1, '1d', fields=factor['name'])[-1] # 对于技术指标返回 series return get_technical_series(stock, factor) RULE_SCORE = { 'fundamental': 0, 'extra': 1, 'pricing': 2, 'technical': 3, 'CDL': 4, } def filter_for(rule): lhs = rule['lhs'] try: return KNOWN_FILTERS[lhs['type'], lhs['name']] except KeyError: return KNOWN_FILTERS[lhs['type'], '*'] def apply_filters(symbol, filters, bar_dict): filters = sorted(filters, key=lambda r: RULE_SCORE[r['lhs']['type']]) for rule in filters: if not(symbol: return [] f = filter_for(rule) (symbol= f(symbol, rule, bar_dict) return(symbol def market_panic(rules, bar_dict): for r in rules: index, rule = r['index'], r['rule'] f = filter_for(rule) result = f([index], rule, bar_dict) if result: return True return False def market_enter(rules, bar_dict): for r in rules: index, rule = r['index'], r['rule'] f = filter_for(rule) result = f([index], rule, bar_dict) if not result: return False return True def sort(symbol, rules, bar_dict): if len(symbol <= 1: return(symbol if not rules: return sorted(symbol result = pd.Series(data=0.0, index(symbol) for rule in rules: factor = rule["factor"] if factor["type"] == "fundamental": data = get_fundamental_factor(symbol, factor["name"]) elif factor["type"] == "pricing": data = pd.Series({s: getattr(bar_dict[s], factor["name"]) for s in(symbol}) elif factor["type"] == "extra": if factor["name"] == "listed_days": data = pd.Series({s: instruments(s).days_from_listed() for s in(symbol}) else: data = get_turnover(symbol, fields=factor["parameters"]).iloc[0] else: data = pd.Series({s: (get_technical_series(s, factor)[-1] if instruments(s).days_from_listed() > 0 else np.nan) for s in(symbol}) na_option = "bottom" if rule["ascending"] else "top" result += data.rank(method="average", ascending=rule['ascending'], na_option=na_option, pct=True) (symbol= result.sort_values().index.tolist() return(symbol def _ensure_list(v): return [] if v is None else v def get_universe(universe, industries, boards, st_option): (symbol= set() if universe != ["*"]: for index in universe: (symbolupdate(_ensure_list(index_components(index))) else: (symbolupdate(all_instruments("CS").order_book_id) if industries != ["*"]: (symbolof_industries = set() for ind in industries: (symbolof_industries.update(_ensure_list(shenwan_industry(ind))) (symbolintersection_update(symbolof_industries) if boards != ["*"]: (symbol= {s for s in(symbol if instruments(s).board_type in boards} if st_option == "only": (symbol= {s for s in(symbol if is_st_stock(s)} elif st_option == "excluded": (symbol= {s for s in(symbol if not is_st_stock(s)} return list(symbol def sell_out_all(portfolio): for order_book_id, position in portfolio.positions.items(): if position.quantity > 0: order_target_value(order_book_id, 0) def init(context): context.count = -1 context.strategy_stop = False context.day_stop = False context.market_panic = False context.pool = [] run_weekly(func=rebalance_first_part, date_rule=1) run_weekly(func=rebalance_second_part, date_rule=2) def before_trading(context): context.count += 1 context.day_stop = False context.market_panic = False def handle_bar(context, bar_dict): if context.strategy_stop or context.day_stop or context.market_panic: sell_out_all(context.portfolio) return if MARKET_PANIC_SIGNALS and market_panic(MARKET_PANIC_SIGNALS, bar_dict): print('大盘止损触发') context.market_panic = True sell_out_all(context.portfolio) return if (HOLDING_PROFIT_TAKEN is not None or HOLDING_STOP_LOSS is not None or STRATEGY_PROFIT_TAKEN is not None or STRATEGY_STOP_LOSS is not None): total_returns = context.portfolio.total_returns fired = False if ((STRATEGY_PROFIT_TAKEN is not None and STRATEGY_PROFIT_TAKEN < total_returns) or (STRATEGY_STOP_LOSS is not None and STRATEGY_STOP_LOSS > total_returns)): fired = True context.strategy_stop = True if ((HOLDING_PROFIT_TAKEN is not None and HOLDING_PROFIT_TAKEN < total_returns) or (HOLDING_STOP_LOSS is not None and HOLDING_STOP_LOSS > total_returns)): fired = True context.day_stop = True if fired: sell_out_all(context.portfolio) return if SINGLE_STOP_LOSS is None and SINGLE_PROFIT_TAKEN is None: return for order_book_id, position in context.portfolio.positions.items(): if position.quantity == 0: continue profit = bar_dict[order_book_id].last / position.avg_price - 1 if SINGLE_PROFIT_TAKEN is not None and SINGLE_PROFIT_TAKEN < profit: print('止盈卖出:', order_book_id, position.quantity) order_target_value(order_book_id, 0) elif SINGLE_STOP_LOSS is not None and SINGLE_STOP_LOSS > profit: print('止损卖出:', order_book_id, position.quantity) order_target_value(order_book_id, 0) def rebalance_first_part(context, bar_dict): if context.strategy_stop: return if context.count % SELECT_INTERVAL == 0: (symbol= get_universe(UNIVERSE, INDUSTRIES, BOARDS, ST_OPTION) filtered = apply_filters(symbol, FILTERS, bar_dict) context.pool = filtered if MARKET_PANIC_SIGNALS and market_panic(MARKET_PANIC_SIGNALS, bar_dict): context.market_panic = True sell_out_all(context.portfolio) return if context.count % SELL_INTERVAL == 0: need_adjust = [] max_position_value = None if MAX_WEIGHT is not None: max_position_value = context.portfolio.total_value * MAX_WEIGHT need_adjust = [s for s, position in context.portfolio.positions.items() if position.market_value > max_position_value] if SELL_CONDITIONS: (symbol= [s for s, position in context.portfolio.positions.items() if position.quantity > 0] sell_list = apply_filters(symbol, SELL_CONDITIONS, bar_dict) for s in sell_list: order_target_value(s, 0) if s in need_adjust: need_adjust.remove(s) for s in need_adjust: order_target_value(s, max_position_value) def rebalance_second_part(context, bar_dict): if (context.count % BUY_INTERVAL != 0 or context.strategy_stop or context.day_stop or context.market_panic): return holdings = [s for s, position in context.portfolio.positions.items() if position.quantity > 0] if len(holdings) >= MAX_HOLDING_NUM: print('持仓数已达到限制,不再买入') return (symbol= [s for s in context.pool if not is_suspended(s)] (symbol= apply_filters(symbol, BUY_CONDITIONS, bar_dict) if not(symbol: return (symbol= [s for s in(symbol if bar_dict[s].last < bar_dict[s].limit_up] sorted(symbol = sort(symbol, SORTING_RULES, bar_dict) buy_list = sorted(symbol:MAX_HOLDING_NUM-len(holdings)] if not buy_list: return target_value = context.stock_account.cash * 0.99 / len(buy_list) if MAX_WEIGHT is not None: max_position_value = context.portfolio.total_value * MAX_WEIGHT target_value = min(target_value, max_position_value) for s in buy_list: order_target_value(s, target_value)  

  • 2

    回答

  • 31

    浏览

先说说游戏规则: 有3堆牌,每堆分别3张,5张,7张。每次只能从一堆中取牌,至少1张,最多全取。 双方轮流拿牌,最后拿光牌的获胜。(也可以约定:最后拿光牌的输) 如果对应的3堆牌,分别是a张,b张,c张,该如何取牌呢? 有研究过算法的吗?

  • 5

    回答

  • 21

    浏览

计算机原理实现原码转补码并加减超前加乘法运算,并带有可视化窗体

  • 2

    回答

  • 24

    浏览

如题,刚接触多进程,想比较一下多进程/线程的优势, 于是就在windows下创建n个txt文件来比较一下时间, 但是发现普通循环遍历操作的时间最短,这是什么原因?是我多进程、线程使用的有问题吗? 多进程: def for_mkd(n): path = "D:\\Pycharm\\workspace\\线程进程相关\\for\\" + str(n) + ".txt" # print(path) with open(path, 'w') as fp: fp.write("0") def main(): # print("主进程执行中>>> pid={0} time={1}".format(os.getpid(),time.ctime(time.time()) * 1000)) print("主进程执行中>>> pid={0} time={1}".format(os.getpid(),time.time() * 1000)) ps = [] # 创建子进程实例 T1 = time.time() * 1000 for i in range(20000): p = Process(target=for_mkd,name="mkdir"+str(i),args=(i,)) # ps.append(p) # 开启进程 p.start() # print(ps) # 阻塞进程 # for i in range(2000): # ps[i].join() # print("主进程终止") T2 = time.time() * 1000 print(T2 - T1) 多线程: import threading import time exitFlag = 0 class myThread (threading.Thread): def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter def run(self): print("开始线程:{0},{1}".format(self.name,time.time() * 1000)) mkdir(self.name, self.counter) print("退出线程:{0},{1}".format(self.name,time.time() * 1000)) def mkdir(threadName, counter): for i in range(counter): if exitFlag: threadName.exit() path = "D:\\Pycharm\\workspace\\线程进程相关\\thr\\" + str(counter) + ".txt" with open(path, 'w') as fp: fp.write("0") counter -= 1 t1 = time.time() * 1000 # 创建新线程 for i in range(1, 2000): thread = myThread(i,"Thread" + str(i), i) # 开启新线程 thread.start() thread.join(10) print("退出主线程") t2 = time.time() * 1000 print("cha is {0}".format(t2 - t1)) 普通遍历操作: def for_mkd(n): path = "D:\\Pycharm\\workspace\\线程进程相关\\for\\" + str(n) + ".txt" print(path) with open(path, 'w') as fp: fp.write("0") def main(): t1 = time.time() * 1000 print("begin at {0}".format(time.time() * 1000)) for i in range(20000): for_mkd(i) print("end at {0}".format(time.time() * 1000)) t2 = time.time() * 1000 print("cha is {0}".format(t2 - t1))  

  • 4

    回答

  • 28

    浏览

报错如下 Traceback (most recent call last):   File "E:/pythonProject3/8/8.1.py", line 23, in <module>     stu = Student('张三', 20, '10001')   File "E:/pythonProject3/8/8.1.py", line 14, in __init__     super().__init__(name, age) TypeError: object.__init__() takes exactly one argument (the instance to initialize) 代码如下 class Person(object):     def __init__(self, name, age):         self.name = name         self.age = age     def info(self):         print(self.name, self.age) class Student:     def __init__(self, name, age, stu_no):         super().__init__(name, age)         self.stu_no = stu_no class Teacher:     def __init__(self, name, age, year):         super().__init__(name, age)         self.year = year stu = Student('张三', 20, '10001') teacher = Teacher('李四', 34, 10) stu.info() 在输入stu.info的时候显示没有这个类,不知道是因为什么原因导致没有继承到子类

  • 5

    回答

  • 35

    浏览

import numpy as np import pandas as pd from pandas import Series from pandas import DataFrame from pandas import read_excel df=pd.read_excel(r'C:\Users\zhaod\Desktop\hw-ch02(1).xlsx',sheet_name="Sheet1") df1 = pd.DataFrame( df.values.T,index=df.columns, columns=df.index) #DataFrame转置 df2=df1.fillna(0) #0值代替空值 df3=df2.replace({' ':0}) #0值代替空格值 df4=df3.drop(['酶种类']) #去掉一行全为字符串的行 print(df4.corr()) #求相关系数 求出来以后,显示为 Empty DataFrame Columns: [] Index: []  

  • 1

    回答

  • 28

    浏览

树莓派的5V接了pca9685驱动板的输出VCC(就是方头),驱动板烧焦味,如何检测树莓派是否烧坏和驱动板是否烧坏?

redbox.top
采纳率60%
16天前
  • 5

    回答

  • 26

    浏览

协同过滤中,基于物品与基于用户的混合模式思想是什么? 怎样用电影数据集来实现这一算法?

  • 0

    回答

  • 31

    浏览

环境现在是: python                          3.8 wxPython                        4.0.7.post2 robotframework-ride             2.0b2.dev3 robotframework                  4.0.1 PyPubSub                        3.3.0 在执行python ride.py时报错信息,无法修改信息。因为之前之前参照了图1和图2修改过。已经打开过ride但是edit版本问题无法修改。才升级的,但是现在又报错无法执行报错:AttributeError: module 'pubsub.pub' has no attribute 'Topic'。我看评论只要升完级都可以用robot的 图1 图2   现在文件内容是这样的

回答 scsc1202
采纳率100%
16天前
  • 1

    回答

  • 16

    浏览

Python 与Autocad 开发时,建立好面域后,拉伸面域生成实体时程序报错:the python instance can noe be converted to a COM object. 即 regionObj 数据格式不正确,不知道要怎么修改。求大神解决,谢谢。 import pythoncom, math import win32com.client wincad = win32com.client.Dispatch("AutoCAD.Application") doc = wincad.ActiveDocument doc.Utility.Prompt("Hello! Autocad from pywin32com.\n") msp = doc.ModelSpace print(doc.Name) def vtpnt(x, y, z=0): return win32com.client.VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_R8, (x, y, z)) def vtobj(obj): return win32com.client.VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_DISPATCH, obj) def vtfloat(lst): return win32com.client.VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_R8, lst) def vtVariant(list): ### """列表转化为变体""" return win32com.client.VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_VARIANT, list) ## 创建直线 center, radius = vtpnt(0, 0, 0), 50;startAngle,endAngle=0,math.pi circleObj = msp.AddCircle(center, radius) print('type(circleObj)',type(circleObj)) curve=[];regionObj=[] curve.append(msp.AddArc(center, radius, startAngle, endAngle)) curve.append(msp.Addline(vtfloat(curve[0].startPoint), vtfloat(curve[0].endPoint))) ## 创建面域 regionObj.append(msp.AddRegion(vtobj(curve))) ## 定义拉伸 height = 200;taperAngle = 0 solidObj = msp.AddExtrudedSolid(vtVariant(regionObj), height, taperAngle)  

  • 2

    回答

  • 16

    浏览

需要学习哪些知识才能做出来,学了python和c语言能写出来吗

  • 4

    回答

  • 32

    浏览

START RequestId:72e459e1-8ec6-4afb-b5e1-c49a8c85b145 ERROR RequestId:72e459e1-8ec6-4afb-b5e1-c49a8c85b145 Result:{"errorCode":-1,"errorMessage":"Traceback (most recent call last):\n  File \"/var/runtime/python3/bootstrap.py\", line 133, in init_handler\n    func_handler = get_func_handler(file.rsplit(\".\", 1)[0], func)\n  File \"/var/runtime/python3/bootstrap.py\", line 160, in get_func_handler\n    return getattr(mod, fname)\nAttributeError: module 'index' has no attribute 'main_handler'","statusCode":443} END RequestId:72e459e1-8ec6-4afb-b5e1-c49a8c85b145 Report RequestId:72e459e1-8ec6-4afb-b5e1-c49a8c85b145 Duration:0ms Memory:256MB MemUsage:0.000000MB

  • 3

    回答

  • 17

    浏览

最近使用python locust对项目一个接口进行压测,由于被测接口使用的token进行用户凭证验证,大体实施思路是先请求登录接口获取响应头中的token,再将token拼接到被测接口的请求头中请求被测接口,实际运行时会有大概10%-20%的失败请求,初步验证是由于locuts模拟的token无效导致。 1.代码实现:    login方法和被测接口实现方法都属于继承了TaskSet的类下 1获取token方法 def login(self): pw = '*****' md = hashlib.md5() md.update(pw.encode('utf-8')) pwd5 = md.hexdigest() url = "http://******:*****/login/login" payload = json.dumps({ "code": "****", "password": pwd5, "username": "****" }) headers = { 'Content-Type': 'application/json' } response = requests.request('post',url, headers=headers, data=payload) return response.headers['x-auth-token'] 2.locust请求被测接口实现 token = self.login() head={ 'x-auth-token': token, 'Content-Type': 'application/json' } with self.client.post("/被测接口",headers= head,json=body,catch_response = True) as response: code=response.json().get("code") key=response.json().get("key") request_header=response.request.headers print("{0}--->:{1}".format(key,request_header),end="\n\n") if code != 200 and key!= "SUCCESS": response.failure("未成功请求响应码:%dkey值:%s"%(code,key)) 由于被测接口对用户凭证验证成功或失败响应码都是200,所以通过if函数对响应体中的code值和key值进行判断,从而断言请求是否成功,响应中的code值不为200与key值不为SUCCESS直接将请求打为失败请求。print函数打印出响应体中的key值与请求头帮助验证。 2. 结果   设置20个虚拟用户每秒启动5个(其实不管怎么设置),运行都会有将近20%的请求是失败请求 将控制台中print函数中的打印信息中响应key值为"NOT_LOGIN"的请求头中的token取出使用postman验证,code值依然为401,说明断言没问题 对比:   与jmeter比较正则提取出来的token,每次请求用的都是同一个token,但不会出现失败请求。   结论:  初步验证认为locust会去模拟第一次拿到的token,但模拟的带token的请求通过后端验证率并不高,不知是locust内部对token处理机制的缺陷还是本人实现的错误。希望高人指教,谢谢!