How to use _is_index method in robotframework-appiumlibrary

Best Python code snippet using robotframework-appiumlibrary_python

Handson.py

Source:Handson.py Github

copy

Full Screen

1import sys2import pandas as pd3from tensorboard import summary4#================================================================5# main()6#================================================================7def main():8 #-------------------------------------------------9 # アンケート回答結果のExcelを作業フォルダにコピー10 #-------------------------------------------------11 file_path_src = r"C:\Users\e13971\Konica Minolta\PythonプログラミングGP - ドキュメント\General\Day1\アンケート\Pythonプログラミング入門_Day1アンケート.xlsx"12 file_path_dsc = r"C:\Users\e13971\Desktop\FY22PythonStudy\FY22Pythonstudy\Pythonプログラミング入門_Day1アンケート.xlsx"13 import shutil14 shutil.copy(file_path_src,file_path_dsc)15 #-------------------------------------------------16 # ファイルからDataFrameにデータを読み込む17 #-------------------------------------------------18 global df_excel_data19 df_excel_data = pd.read_excel(file_path_dsc)20 print("[回答数]{0}".format(len(df_excel_data)))21 print("")22 #------------------------------------------------23 # アンケートの回答結果を集計・表示24 #------------------------------------------------25 #============== Q1 ==============26 q1_question = "【単一選択】下記の選択肢の中でスマホを買うときに最も重視する項目どれですか?[A]"27 q1_row = ["価格", "サイズ", "重さ", "デザイン", "カメラの画質", "画面の解像度"]28 q1_column = ["選択された数"]29 df_q1_result = pd.DataFrame(index=q1_row,columns=q1_column)30 for col_name, col in df_q1_result.iteritems():31 for row_name in col.index:32 df_q1_result.loc[row_name,col_name] = 033 for row_name, row in df_excel_data.iterrows():34 sel = row[q1_question]35 df_q1_result.loc[sel,q1_column[0]] += 136 print("[Q1] "+ q1_question)37 for sel,row in df_q1_result.iterrows():38 print("・{0}:{1}".format(sel,df_q1_result.loc[sel, q1_column[0]]))39 print("")40 #============== Q2 ==============41 q2_question = "【リッカート】下記の季節の好き嫌いを答えて下さい。[B]"42 q2_row = ["真冬[B01]", "春[B02]", "初夏[B03]", "梅雨[B04]", "真夏[B05]", "初秋[B06]", "晩秋[B07]"]43 q2_column = ["大好き", "わりと好き", "どちらでもない", "あまり好きではない", "嫌い"]44 df_q2_result = pd.DataFrame(index=q2_row,columns=q2_column)45 for col_name, col in df_q2_result.iteritems():46 for row_name in col.index:47 df_q2_result.loc[row_name,col_name] = 048 for row_name, row in df_excel_data.iterrows():49 for question in q2_row:50 answer = row[question]51 df_q2_result.at[question,answer] += 152 print("[Q2] "+ q2_question)53 print(df_q2_result)54 print("")55 # #============== Q3 ==============56 q3_question = "【複数選択】下記の選択肢の中でテレビを買うときに重視する項目を選んで下さい(複数選択可)[C]"57 q3_row = ["価格", "音質", "画質", "画面サイズ", "デザイン", "リモコンの使いやすさ", "アフターサービス"]58 q3_column = ["選択された数"]59 df_q3_result = pd.DataFrame(index=q3_row,columns=q3_column)60 for col_name, col in df_q3_result.iteritems():61 for row_name in col.index:62 df_q3_result.loc[row_name,col_name] = 063 for row_name, row in df_excel_data.iterrows():64 for sel in df_q3_result.index:65 if sel in row[q3_question]:66 df_q3_result.loc[sel,q3_column[0]] += 167 print("[Q3] "+ q3_question)68 for sel,row in df_q3_result.iterrows():69 print("・{0}:{1}".format(sel,df_q3_result.loc[sel, q3_column[0]]))70 print("")71 #------------------------------------------------72 # 数値に変換したDataFrameをExcelファイルに出力73 #------------------------------------------------74 summary_file_path = r"C:\Users\e13971\Desktop\FY22PythonStudy\FY22Pythonstudy\アンケート集計.xlsx"75 export_excel(_path = summary_file_path, _df = df_q1_result, _sheet_name = "Q1", _header_fillcol = "66ffcc")76 export_excel(_path = summary_file_path, _df = df_q2_result, _sheet_name = "Q2", _append = True, _header_fillcol = "66ffcc")77 export_excel(_path = summary_file_path, _df = df_q3_result, _sheet_name = "Q3", _append = True, _header_fillcol = "66ffcc")78 #------------------------------------------------79 # 回答者にメールを送信80 #------------------------------------------------81 import win32com.client82 outlook = win32com.client.Dispatch("outlook.Application")83 mail = outlook.CreateItem(0)84 mail.to = "benshuai.guo@konicaminolta.com"85 mail.subject = "アンケート集計結果"86 mail.bodyFormat = 2 #HTML87 mail.body = "アンケート結果を送りします。よろしくお願いします。"88 mail.Attachments.Add(summary_file_path)89 if True:90 mail.display(True)91 else:92 mail.Send()93#================================================================94# [export_excel] DataFrameをExcelへ出力 95# 画像を挿入するときは_wbはNoneでなければならない(_pathで指定する)96#================================================================97def export_excel(_path=None, _df=None, _wb=None, _sheet_name='sheet1', _letter_fmt=None, _append=False, _frz='B2', _auto_flt=True, _auto_sz=False, _header_height=None, _col_width_=[20,20], _header_fmt=None, _header_rot=0, _zoom=100, _heatmap=0, _is_index=True, _index_name='Index', _header_txtcol='000000', _header_fillcol='d9f2f8', _txtwrap=False, _img=None, _group=None):98 import os99 import time100 import openpyxl as px101 from openpyxl.utils import get_column_letter102 from openpyxl.comments import Comment103 time_start = time.perf_counter()104 print('[Exporting Excel file ...] Sheet : "{0}"'.format(_sheet_name))105 106 #-------------------------------------------107 # 初期設定108 #-------------------------------------------109 # Workbook作成110 if _wb == None:111 if _append: # 既存ファイルにシート追加112 try:113 wb = px.load_workbook(_path)114 except:115 _append = False # ファイルが存在しないときは新規作成116 if not _append: # 新規ファイル117 wb = px.Workbook()118 else:119 wb = _wb120 _append = True121 # Worksheet作成122 ws = wb.create_sheet(title=_sheet_name)123 #-------------------------------------------124 # DataFrameをWorksheetに書き込み125 #-------------------------------------------126 if _df is not None:127 #----- 作業用にDataFrameをコピー -----128 df = _df.copy()129 130 # Timestampを文字列に変換(そのままだとエラーになるので)131 list_timestamp_col = list()132 # Timestampのセルが存在する列を探して文字列に変換する133 for col_name, col in df.iteritems():134 for item in col:135 tp = type(item)136 if tp is pd._libs.tslibs.timestamps.Timestamp:137 list_timestamp_col.append(col_name)138 break139 for col in list_timestamp_col:140 df[col] = df[col].astype(str)141 df[col] = df[col].replace('NaT', '')142 143 #----- Excelファイル用フォーマットの作成 -----144 base_font = '游ゴシック'145 from openpyxl.styles.fonts import Font146 from openpyxl.styles import PatternFill147 font_header_row = Font(name=base_font, b=True, sz=10, color=_header_txtcol)148 font_header_col = Font(name=base_font, b=True, sz=10, color=_header_txtcol)149 font_cell = Font(name=base_font, sz=10)150 align_header_row = px.styles.Alignment(horizontal="center", vertical="center", wrapText=True, textRotation=_header_rot)151 align_header_col = px.styles.Alignment(horizontal="center", vertical="center", wrapText=True)152 fill_header_row = PatternFill(patternType='solid', fgColor=_header_fillcol)153 fill_header_col = PatternFill(patternType='solid', fgColor=_header_fillcol)154 155 #----- データ出力 -----156 # DataFrameをWorksheetにExport157 l = df.columns.tolist()158 if _is_index:159 l.insert(0, _index_name) # 行のindexを先頭列に追加160 ws.append(l)161 count = 0162 for i, row in df.iterrows(): # 一行ずつwsに追加していく163 l = row.values.tolist()164 if _is_index:165 l.insert(0, row.name) # 行のindexを先頭列に追加166 ws.append(l)167 count += 1168 print('\r - データコピー {0}/{1}'.format(count, len(df)), end="")169 print('')170 171 #----- Worksheetの書式設定 -----172 # ヘッダー行(既定値)173 for cell in list(ws.rows)[0]:174 cell.font = font_header_row175 cell.alignment = align_header_row176 cell.fill = fill_header_row177 # ヘッダー行(個別)178 if _header_fmt != None:179 list_cell = list(ws.rows)[0]180 for head, fmt in _header_fmt.items():181 try:182 index = list(df.columns).index(head)183 if _is_index:184 index += 1185 cell = list_cell[index]186 except:187 continue188 # rotation189 try:190 rotation = fmt['rotation']191 cell.alignment = px.styles.Alignment(horizontal="center", vertical="center", wrapText=True, textRotation=rotation)192 except:193 pass194 # 文字色195 try:196 text_color = fmt['txtcol']197 cell.font = Font(name=base_font, b=True, sz=10, color=text_color)198 except:199 pass200 # 背景色201 try:202 fill_color = fmt['fillcol']203 cell.fill = PatternFill(patternType='solid', fgColor=fill_color)204 except:205 pass206 # コメント207 try:208 comment = fmt['comment']209 cell.comment = Comment(comment, '')210 except:211 pass212 # 列ごとの書式設定用のリスト作成213 list_dtxt_pat = list()214 list_dfill_pat = list()215 if _header_fmt != None:216 for head, fmt in _header_fmt.items():217 try:218 index = list(df.columns).index(head)219 if _is_index:220 index += 1221 except:222 continue223 # 文字色224 try:225 text_color = fmt['dtxtcol']226 list_dtxt_pat.append([index, Font(name=base_font, sz=10, color=text_color)])227 except:228 pass229 # 背景色230 try:231 dfill_color = fmt['dfillcol']232 list_dfill_pat.append([index, PatternFill(patternType='solid', fgColor=dfill_color)])233 except:234 pass235 # データ行書式設定236 count = 0237 for row in ws.iter_rows(min_row=2): 238 # 書式設定239 for cell in row:240 cell.font = font_cell241 cell.alignment = px.styles.Alignment(wrapText=_txtwrap)242 # 列ごとの書式設定で上書き243 for list_pat in list_dtxt_pat: # 個別設定がある列を順に処理する244 idx = list_pat[0]245 row[idx].font = list_pat[1]246 for list_pat in list_dfill_pat: # 個別設定がある列を順に処理する247 idx = list_pat[0]248 row[idx].fill = list_pat[1]249 # Index列がある場合はIndex用設定250 if _is_index:251 row[0].font = font_header_col # 先頭列のみ太字252 row[0].alignment = align_header_col # 先頭列のみセンタリング253 row[0].fill = fill_header_col # 先頭列の塗りつぶし254 count += 1255 print('\r - 書式設定 {0}/{1}'.format(count, len(df)), end="")256 print('')257 258 #----- セルの文字書式 -----259 if type(_letter_fmt) is dict: # _header_fmtがあれば不要だが互換性のために残してある260 for col in ws.iter_cols():261 col_name = col[0].value262 if col_name in _letter_fmt:263 num_format = _letter_fmt[col_name]264 for cell in col:265 cell.number_format = num_format266 elif type(_letter_fmt) is str:267 for col in ws.iter_cols():268 for cell in col:269 cell.number_format = _letter_fmt270 # 列ごとの個別設定で上書き 271 if _header_fmt != None:272 list_col = list(_header_fmt.keys())273 for col in ws.iter_cols():274 col_name = col[0].value275 if col_name in list_col: # 列書式一覧の辞書にこの列が存在する276 try:277 fmt = _header_fmt[col_name]278 num_format = fmt['dtxtformat']279 for cell in col:280 cell.number_format = num_format281 except:282 pass283 284 # Worksheetの列幅調整285 if _auto_sz: # 自動調整286 for col in ws.columns:287 max_length = 0288 column = col[0].column289 column = get_column_letter(column) # 数字をアルファベットに変換290 cols = col if _header_rot!=90 else col[1:]291 for cell in cols:292 if len(str(cell.value)) > max_length:293 max_length = len(str(cell.value))294 adjusted_width = (max_length + 2) * 1.1295 ws.column_dimensions[column].width = adjusted_width296 else:297 for col in ws.columns:298 column = col[0].column # 列番号を取得299 col_letter = get_column_letter(column) # 列番号を列記号に変換300 width = _col_width_[0] if column == 1 else _col_width_[1] # 列幅301 ws.column_dimensions[col_letter].width = width302 # 列ごとの個別調整303 if _header_fmt != None:304 list_col = list(ws.columns)305 for head, fmt in _header_fmt.items():306 try:307 width = fmt['width']308 index = list(df.columns).index(head)309 if _is_index:310 index += 1311 col = list_col[index]312 column = col[0].column # 列番号を取得313 col_letter = get_column_letter(column) # 列番号を列記号に変換314 ws.column_dimensions[col_letter].width = width315 except:316 pass317 318 # Worksheetの行の高さ調整319 if _header_height != None:320 ws.row_dimensions[1].height = _header_height321 322 # ヒートマップ323 from openpyxl.formatting.rule import ColorScale, FormatObject324 from openpyxl.styles import Color325 if _heatmap == 1: # 赤 → 白 → 青326 first = FormatObject(type='min')327 last = FormatObject(type='max')328 # colors match the format objects:329 colors = [Color('F8696B'), Color('5A8AC6')]330 # a three color scale would extend the sequences331 mid = FormatObject(type='percentile', val=50)332 colors.insert(1, Color('FCFCFF'))333 cs3 = ColorScale(cfvo=[first, mid, last], color=colors)334 # create a rule with the color scale335 from openpyxl.formatting.rule import Rule336 rule = Rule(type='colorScale', colorScale=cs3)337 # 対象範囲を示す文字列を作成338 rg = 'A2:' + get_column_letter(ws.max_column)+str(ws.max_row)339 ws.conditional_formatting.add(rg, rule)340 elif _heatmap == 2: # 白 → 橙 → 赤341 first = FormatObject(type='min')342 last = FormatObject(type='max')343 # colors match the format objects:344 colors = [Color('FFFFFF'), Color('F8696B')]345 # a three color scale would extend the sequences346 mid = FormatObject(type='percentile', val=50)347 colors.insert(1, Color('FFEB84'))348 cs3 = ColorScale(cfvo=[first, mid, last], color=colors)349 # create a rule with the color scale350 from openpyxl.formatting.rule import Rule351 rule = Rule(type='colorScale', colorScale=cs3)352 # 対象範囲を示す文字列を作成353 rg = 'A2:' + get_column_letter(ws.max_column)+str(ws.max_row)354 ws.conditional_formatting.add(rg, rule)355 elif _heatmap == 3: # 赤 → 橙 → 白356 first = FormatObject(type='min')357 last = FormatObject(type='max')358 # colors match the format objects:359 colors = [Color('F8696B'), Color('FFFFFF')]360 # a three color scale would extend the sequences361 mid = FormatObject(type='percentile', val=25)362 colors.insert(1, Color('FFEB84'))363 cs3 = ColorScale(cfvo=[first, mid, last], color=colors)364 # create a rule with the color scale365 from openpyxl.formatting.rule import Rule366 rule = Rule(type='colorScale', colorScale=cs3)367 # 対象範囲を示す文字列を作成368 rg = 'A2:' + get_column_letter(ws.max_column)+str(ws.max_row)369 ws.conditional_formatting.add(rg, rule)370 371 # 枠固定372 if _frz != None:373 ws.freeze_panes = _frz374 # オートフィルタ375 if _auto_flt:376 ws.auto_filter.ref = 'A1:' + get_column_letter(ws.max_column)+'1'377 378 # グループ化([0]開始列名 [1]終了列名 [2]閉じる時True)379 if _group != None:380 for r in _group:381 if r[0] < r[1]:382 ws.column_dimensions.group(get_column_letter(r[0]), get_column_letter(r[1]), hidden=r[2])383 384 # 表示倍率385 ws.sheet_view.zoomScale = _zoom386 387 #-------------------------------------------388 # Worksheetに画像を挿入389 #-------------------------------------------390 if _img != None:391 from openpyxl.drawing.image import Image392 for img in _img:393 fpath = img[0] # 挿入する画像ファイル394 anchor = img[1] # 挿入位置395 px_img = Image(fpath)396 px_img.anchor = anchor397 ws.add_image(px_img)398 399 #-------------------------------------------400 # 最後に不要なシートを削除401 #-------------------------------------------402 if 'Sheet' in wb.sheetnames:403 wb.remove(wb['Sheet'])404 #-------------------------------------------405 # Excelファイルに書き込み406 #-------------------------------------------407 if _path != None:408 print(' - ファイル書き込み...', end='')409 wb.save(_path)410 # 画像ファイル削除411 if _img != None:412 for img in _img:413 is_delete = False # ファイルを削除するか否か414 if len(img) > 2:415 is_delete = img[2]416 if is_delete: # ファイル削除417 os.remove(img[0])418 print ('\n ---> Finished. (処理時間:{0:.3f}[sec])'.format(time.perf_counter() - time_start ))419 420 return wb421if __name__ == "__main__":422 import time423 main_time_start = time.perf_counter()424 main()425 print("\n===> 正常終了 (処理時間:{:.3f}[sec])".format(time.perf_counter()-main_time_start))...

Full Screen

Full Screen

test_pandabar.py

Source:test_pandabar.py Github

copy

Full Screen

1import unittest2from numpy import float643from pandasio.pandabar import _PandaBar, _get_panda_bar_info_dtype4from pandasio.exceptions import IdentifierByteRepresentationError5from pandasio.utils.exceptions import NumBytesForStringInvalidError6from pandasio.utils.numpy_utils import NumpyTypeChars7class TestPandaBar(unittest.TestCase):8 def test_panda_bar_info_dtype(self):9 d = _get_panda_bar_info_dtype(4)10 self.assertEqual('identifier', d.descr[0][0])11 self.assertEqual('<U1', d.descr[0][1])12 self.assertEqual('options', d.descr[1][0])13 self.assertEqual('<u2', d.descr[1][1])14 self.assertEqual('bytes_per_point', d.descr[2][0])15 self.assertEqual('|u1', d.descr[2][1])16 self.assertEqual('type_char', d.descr[3][0])17 self.assertEqual('|u1', d.descr[3][1])18 self.assertEqual('bytes_extra_information', d.descr[4][0])19 self.assertEqual('<u4', d.descr[4][1])20 for i in range(0, 32):21 self.assertEqual('def_byte_{}'.format(i + 1), d.descr[5 + i][0])22 self.assertEqual('|u1', d.descr[5 + i][1])23 d = _get_panda_bar_info_dtype(16)24 self.assertEqual('<U4', d.descr[0][1])25 d = _get_panda_bar_info_dtype(32)26 self.assertEqual('<U8', d.descr[0][1])27 # test errors28 with self.assertRaises(NumBytesForStringInvalidError):29 _get_panda_bar_info_dtype(2)30 with self.assertRaises(IdentifierByteRepresentationError):31 _get_panda_bar_info_dtype(0)32 with self.assertRaises(IdentifierByteRepresentationError):33 _get_panda_bar_info_dtype(-1)34 with self.assertRaises(NumBytesForStringInvalidError):35 _get_panda_bar_info_dtype(0.5)36 return37 def test_panda_bar_init_min_params(self):38 p = _PandaBar('data', 8, NumpyTypeChars.FLOAT)39 self.assertEqual('data', p._identifier)40 self.assertEqual(8, p._bytes_per_value)41 self.assertEqual('f', p._type_char)42 self.assertEqual(float64, p._dtype)43 self.assertEqual(False, p._is_index)44 self.assertEqual(None, p._data)45 self.assertEqual(None, p._encoded_data)46 self.assertEqual(None, p._num_points)47 self.assertEqual(True, p._use_compression)48 self.assertEqual(False, p._use_hash_table)49 self.assertEqual(False, p._use_floating_point_rounding)50 self.assertEqual(None, p._compression_dtype)51 self.assertEqual(None, p._compression_mode)52 self.assertEqual(None, p._compression_reference_value)53 self.assertEqual(None, p._compression_reference_value_dtype)54 self.assertEqual(None, p._floating_point_rounding_num_decimals)55 self.assertEqual(0, p._num_bytes_extra_information)56 return57 def test_panda_bar_init_optional_params(self):58 p = _PandaBar('data', 8, NumpyTypeChars.FLOAT, is_index=True)59 self.assertEqual(True, p._is_index)60 self.assertEqual(True, p.is_index())61 p = _PandaBar('data', 8, NumpyTypeChars.FLOAT, num_extra_bytes_required=4)62 self.assertEqual(4, p._num_bytes_extra_information)63 self.assertEqual(4, p.num_extra_bytes_required())64 return65 def test_panda_bar_encode_options(self):66 p = _PandaBar('data', 8, NumpyTypeChars.FLOAT)67 p._use_floating_point_rounding = False68 p._use_hash_table = False69 p._use_compression = False70 p._is_index = False71 self.assertEqual(0, p._encode_options())72 p._use_floating_point_rounding = False73 p._use_hash_table = False74 p._use_compression = False75 p._is_index = True76 self.assertEqual(1, p._encode_options())77 p._use_floating_point_rounding = False78 p._use_hash_table = False79 p._use_compression = True80 p._is_index = False81 self.assertEqual(2, p._encode_options())82 p._use_floating_point_rounding = False83 p._use_hash_table = False84 p._use_compression = True85 p._is_index = True86 self.assertEqual(3, p._encode_options())87 p._use_floating_point_rounding = False88 p._use_hash_table = True89 p._use_compression = False90 p._is_index = False91 self.assertEqual(4, p._encode_options())92 p._use_floating_point_rounding = False93 p._use_hash_table = True94 p._use_compression = False95 p._is_index = True96 self.assertEqual(5, p._encode_options())97 p._use_floating_point_rounding = False98 p._use_hash_table = True99 p._use_compression = True100 p._is_index = False101 self.assertEqual(6, p._encode_options())102 p._use_floating_point_rounding = False103 p._use_hash_table = True104 p._use_compression = True105 p._is_index = True106 self.assertEqual(7, p._encode_options())107 p._use_floating_point_rounding = True108 p._use_hash_table = False109 p._use_compression = False110 p._is_index = False111 self.assertEqual(8, p._encode_options())112 p._use_floating_point_rounding = True113 p._use_hash_table = False114 p._use_compression = False115 p._is_index = True116 self.assertEqual(9, p._encode_options())117 p._use_floating_point_rounding = True118 p._use_hash_table = False119 p._use_compression = True120 p._is_index = False121 self.assertEqual(10, p._encode_options())122 p._use_floating_point_rounding = True123 p._use_hash_table = False124 p._use_compression = True125 p._is_index = True126 self.assertEqual(11, p._encode_options())127 p._use_floating_point_rounding = True128 p._use_hash_table = True129 p._use_compression = False130 p._is_index = False131 self.assertEqual(12, p._encode_options())132 p._use_floating_point_rounding = True133 p._use_hash_table = True134 p._use_compression = False135 p._is_index = True136 self.assertEqual(13, p._encode_options())137 p._use_floating_point_rounding = True138 p._use_hash_table = True139 p._use_compression = True140 p._is_index = False141 self.assertEqual(14, p._encode_options())142 p._use_floating_point_rounding = True143 p._use_hash_table = True144 p._use_compression = True145 p._is_index = True146 self.assertEqual(15, p._encode_options())147 return148 def test_panda_bar_decode_options(self):149 p = _PandaBar('data', 8, NumpyTypeChars.FLOAT)150 p._decode_options(0)151 self.assertFalse(p._use_floating_point_rounding)152 self.assertFalse(p._use_hash_table)153 self.assertFalse(p._use_compression)154 self.assertFalse(p._is_index)155 p._decode_options(1)156 self.assertFalse(p._use_floating_point_rounding)157 self.assertFalse(p._use_hash_table)158 self.assertFalse(p._use_compression)159 self.assertTrue(p._is_index)160 p._decode_options(2)161 self.assertFalse(p._use_floating_point_rounding)162 self.assertFalse(p._use_hash_table)163 self.assertTrue(p._use_compression)164 self.assertFalse(p._is_index)165 p._decode_options(3)166 self.assertFalse(p._use_floating_point_rounding)167 self.assertFalse(p._use_hash_table)168 self.assertTrue(p._use_compression)169 self.assertTrue(p._is_index)170 p._decode_options(4)171 self.assertFalse(p._use_floating_point_rounding)172 self.assertTrue(p._use_hash_table)173 self.assertFalse(p._use_compression)174 self.assertFalse(p._is_index)175 p._decode_options(5)176 self.assertFalse(p._use_floating_point_rounding)177 self.assertTrue(p._use_hash_table)178 self.assertFalse(p._use_compression)179 self.assertTrue(p._is_index)180 p._decode_options(6)181 self.assertFalse(p._use_floating_point_rounding)182 self.assertTrue(p._use_hash_table)183 self.assertTrue(p._use_compression)184 self.assertFalse(p._is_index)185 p._decode_options(7)186 self.assertFalse(p._use_floating_point_rounding)187 self.assertTrue(p._use_hash_table)188 self.assertTrue(p._use_compression)189 self.assertTrue(p._is_index)190 p._decode_options(8)191 self.assertTrue(p._use_floating_point_rounding)192 self.assertFalse(p._use_hash_table)193 self.assertFalse(p._use_compression)194 self.assertFalse(p._is_index)195 p._decode_options(9)196 self.assertTrue(p._use_floating_point_rounding)197 self.assertFalse(p._use_hash_table)198 self.assertFalse(p._use_compression)199 self.assertTrue(p._is_index)200 p._decode_options(10)201 self.assertTrue(p._use_floating_point_rounding)202 self.assertFalse(p._use_hash_table)203 self.assertTrue(p._use_compression)204 self.assertFalse(p._is_index)205 p._decode_options(11)206 self.assertTrue(p._use_floating_point_rounding)207 self.assertFalse(p._use_hash_table)208 self.assertTrue(p._use_compression)209 self.assertTrue(p._is_index)210 p._decode_options(12)211 self.assertTrue(p._use_floating_point_rounding)212 self.assertTrue(p._use_hash_table)213 self.assertFalse(p._use_compression)214 self.assertFalse(p._is_index)215 p._decode_options(13)216 self.assertTrue(p._use_floating_point_rounding)217 self.assertTrue(p._use_hash_table)218 self.assertFalse(p._use_compression)219 self.assertTrue(p._is_index)220 p._decode_options(14)221 self.assertTrue(p._use_floating_point_rounding)222 self.assertTrue(p._use_hash_table)223 self.assertTrue(p._use_compression)224 self.assertFalse(p._is_index)225 p._decode_options(15)226 self.assertTrue(p._use_floating_point_rounding)227 self.assertTrue(p._use_hash_table)228 self.assertTrue(p._use_compression)229 self.assertTrue(p._is_index)230 return231if __name__ == '__main__':...

Full Screen

Full Screen

sensor.py

Source:sensor.py Github

copy

Full Screen

1import logging2from .const import DOMAIN3from homeassistant.const import STATE_UNKNOWN4from homeassistant.helpers.update_coordinator import CoordinatorEntity5_LOGGER = logging.getLogger(__name__)6async def async_setup_platform(hass, config, async_add_devices, discovery_info=None):7 sensors = []8 coordinator = hass.data[DOMAIN]9 for exchange, stocks in discovery_info["stocks"].items():10 for stock in stocks:11 sensors.append(StockSensor(coordinator, exchange + stock))12 async_add_devices(sensors, True)13class StockSensor(CoordinatorEntity):14 def __init__(self, coordinator, stock):15 super().__init__(coordinator)16 self._coordinator = coordinator17 self._stock = stock18 self._unique_id = f"{DOMAIN}.stock_{stock}"19 self.entity_id = self._unique_id20 self._is_index = (stock[0:2] == "sh" and stock[2:5] == "000") or (stock[0:2] == "sz" and stock[2:5] == "399")21 def get_value(self, key):22 if self._coordinator.data is not None and self._coordinator.data.get(self._stock) is not None:23 return self._coordinator.data.get(self._stock).get(key)24 else:25 return STATE_UNKNOWN26 @staticmethod27 def sign(str_val):28 if str_val != STATE_UNKNOWN and float(str_val) != 0 and str_val[0:1] != "-":29 return "+" + str_val30 return str_val31 @property32 def should_poll(self):33 return False34 @property35 def name(self):36 return f"{self.get_value('name')}({self._stock}) [{self.sign(self.get_value('涨跌'))}" \37 f"({self.sign(self.get_value('涨跌(%)'))}%)]"38 @property39 def unique_id(self):40 return self._unique_id41 @property42 def state(self):43 _state = self.get_value('当前价格')44 if _state != STATE_UNKNOWN:45 return float(self.get_value('当前价格'))46 else:47 return _state48 @property49 def extra_state_attributes(self) -> dict:50 ret = {51 "股票代码": self.get_value("股票代码"),52 "当前价格": self.get_value("当前价格"),53 "昨收": self.get_value("昨收"),54 "今开": self.get_value("今开"),55 "成交量": self.get_value("成交量(手)"),56 "外盘": self.get_value("外盘"),57 "内盘": self.get_value("内盘"),58 "涨跌": self.sign(self.get_value("涨跌")),59 "涨跌幅": self.sign(self.get_value("涨跌(%)")) + "%",60 "最高": self.get_value("最高"),61 "最低": self.get_value("最低"),62 "成交额": self.get_value("成交额(万)"),63 "振幅": self.get_value("振幅") + "%",64 }65 if not self._is_index:66 ret.update({67 "卖五(" + self.get_value("卖五") + ")": self.get_value("卖五量(手)"),68 "卖四(" + self.get_value("卖四") + ")": self.get_value("卖四量(手)"),69 "卖三(" + self.get_value("卖三") + ")": self.get_value("卖三量(手)"),70 "卖二(" + self.get_value("卖二") + ")": self.get_value("卖二量(手)"),71 "卖一(" + self.get_value("卖一") + ")": self.get_value("卖一量(手)"),72 "买一(" + self.get_value("买一") + ")": self.get_value("买一量(手)"),73 "买二(" + self.get_value("买二") + ")": self.get_value("买二量(手)"),74 "买三(" + self.get_value("买三") + ")": self.get_value("买三量(手)"),75 "买四(" + self.get_value("买四") + ")": self.get_value("买四量(手)"),76 "买五(" + self.get_value("买五") + ")": self.get_value("买五量(手)"),77 "换手率": self.get_value("换手率") + "%",78 "市盈率": self.get_value("市盈率"),79 "流通市值": self.get_value("流通市值"),80 "总市值": self.get_value("总市值"),81 "市净率": self.get_value("市净率"),82 "量比": self.get_value("量比"),83 "均价": self.get_value("均价"),84 "涨停价": self.get_value("涨停价"),85 "跌停价": self.get_value("跌停价"),86 "委差": self.get_value("委差"),87 "市盈(动)": self.get_value("市盈(动)"),88 "市盈(静)": self.get_value("市盈(静)")89 })90 return ret91 @property92 def unit_of_measurement(self):93 if self._is_index:94 return "点"95 else:96 return "元"97 @property98 def icon(self):...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run robotframework-appiumlibrary automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful