Best JavaScript code snippet using playwright-internal
ruleset.py
Source:ruleset.py
1# coding: utf-82import re3import six4from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization5class Ruleset:6 """7 Attributes:8 openapi_types (dict): The key is attribute name9 and the value is attribute type.10 attribute_map (dict): The key is attribute name11 and the value is json key in definition.12 """13 sensitive_list = []14 openapi_types = {15 'project_id': 'str',16 'template_name': 'str',17 'language': 'str',18 'is_default': 'str',19 'rule_ids': 'str',20 'uncheck_ids': 'str',21 'template_id': 'str',22 'custom_attributes': 'list[CustomAttributes]'23 }24 attribute_map = {25 'project_id': 'project_id',26 'template_name': 'template_name',27 'language': 'language',28 'is_default': 'is_default',29 'rule_ids': 'rule_ids',30 'uncheck_ids': 'uncheck_ids',31 'template_id': 'template_id',32 'custom_attributes': 'custom_attributes'33 }34 def __init__(self, project_id=None, template_name=None, language=None, is_default=None, rule_ids=None, uncheck_ids=None, template_id=None, custom_attributes=None):35 """Ruleset36 The model defined in huaweicloud sdk37 :param project_id: 项ç®ID38 :type project_id: str39 :param template_name: æ°è§åéå称40 :type template_name: str41 :param language: è§åéè¯è¨42 :type language: str43 :param is_default: å¦ææåºäºçè§åéåæ¯1ï¼æ²¡æåºäºçè§åéåæ¯044 :type is_default: str45 :param rule_ids: æ°å¯ç¨è§åids46 :type rule_ids: str47 :param uncheck_ids: æ°å
³éè§åid48 :type uncheck_ids: str49 :param template_id: è§åéID50 :type template_id: str51 :param custom_attributes: èªå®ä¹è§ååæ°é¡¹ï¼æ¯æä¿®æ¹è§åéå¼52 :type custom_attributes: list[:class:`huaweicloudsdkcodecheck.v2.CustomAttributes`]53 """54 55 56 self._project_id = None57 self._template_name = None58 self._language = None59 self._is_default = None60 self._rule_ids = None61 self._uncheck_ids = None62 self._template_id = None63 self._custom_attributes = None64 self.discriminator = None65 self.project_id = project_id66 self.template_name = template_name67 self.language = language68 self.is_default = is_default69 self.rule_ids = rule_ids70 if uncheck_ids is not None:71 self.uncheck_ids = uncheck_ids72 if template_id is not None:73 self.template_id = template_id74 if custom_attributes is not None:75 self.custom_attributes = custom_attributes76 @property77 def project_id(self):78 """Gets the project_id of this Ruleset.79 项ç®ID80 :return: The project_id of this Ruleset.81 :rtype: str82 """83 return self._project_id84 @project_id.setter85 def project_id(self, project_id):86 """Sets the project_id of this Ruleset.87 项ç®ID88 :param project_id: The project_id of this Ruleset.89 :type project_id: str90 """91 self._project_id = project_id92 @property93 def template_name(self):94 """Gets the template_name of this Ruleset.95 æ°è§åéå称96 :return: The template_name of this Ruleset.97 :rtype: str98 """99 return self._template_name100 @template_name.setter101 def template_name(self, template_name):102 """Sets the template_name of this Ruleset.103 æ°è§åéå称104 :param template_name: The template_name of this Ruleset.105 :type template_name: str106 """107 self._template_name = template_name108 @property109 def language(self):110 """Gets the language of this Ruleset.111 è§åéè¯è¨112 :return: The language of this Ruleset.113 :rtype: str114 """115 return self._language116 @language.setter117 def language(self, language):118 """Sets the language of this Ruleset.119 è§åéè¯è¨120 :param language: The language of this Ruleset.121 :type language: str122 """123 self._language = language124 @property125 def is_default(self):126 """Gets the is_default of this Ruleset.127 å¦ææåºäºçè§åéåæ¯1ï¼æ²¡æåºäºçè§åéåæ¯0128 :return: The is_default of this Ruleset.129 :rtype: str130 """131 return self._is_default132 @is_default.setter133 def is_default(self, is_default):134 """Sets the is_default of this Ruleset.135 å¦ææåºäºçè§åéåæ¯1ï¼æ²¡æåºäºçè§åéåæ¯0136 :param is_default: The is_default of this Ruleset.137 :type is_default: str138 """139 self._is_default = is_default140 @property141 def rule_ids(self):142 """Gets the rule_ids of this Ruleset.143 æ°å¯ç¨è§åids144 :return: The rule_ids of this Ruleset.145 :rtype: str146 """147 return self._rule_ids148 @rule_ids.setter149 def rule_ids(self, rule_ids):150 """Sets the rule_ids of this Ruleset.151 æ°å¯ç¨è§åids152 :param rule_ids: The rule_ids of this Ruleset.153 :type rule_ids: str154 """155 self._rule_ids = rule_ids156 @property157 def uncheck_ids(self):158 """Gets the uncheck_ids of this Ruleset.159 æ°å
³éè§åid160 :return: The uncheck_ids of this Ruleset.161 :rtype: str162 """163 return self._uncheck_ids164 @uncheck_ids.setter165 def uncheck_ids(self, uncheck_ids):166 """Sets the uncheck_ids of this Ruleset.167 æ°å
³éè§åid168 :param uncheck_ids: The uncheck_ids of this Ruleset.169 :type uncheck_ids: str170 """171 self._uncheck_ids = uncheck_ids172 @property173 def template_id(self):174 """Gets the template_id of this Ruleset.175 è§åéID176 :return: The template_id of this Ruleset.177 :rtype: str178 """179 return self._template_id180 @template_id.setter181 def template_id(self, template_id):182 """Sets the template_id of this Ruleset.183 è§åéID184 :param template_id: The template_id of this Ruleset.185 :type template_id: str186 """187 self._template_id = template_id188 @property189 def custom_attributes(self):190 """Gets the custom_attributes of this Ruleset.191 èªå®ä¹è§ååæ°é¡¹ï¼æ¯æä¿®æ¹è§åéå¼192 :return: The custom_attributes of this Ruleset.193 :rtype: list[:class:`huaweicloudsdkcodecheck.v2.CustomAttributes`]194 """195 return self._custom_attributes196 @custom_attributes.setter197 def custom_attributes(self, custom_attributes):198 """Sets the custom_attributes of this Ruleset.199 èªå®ä¹è§ååæ°é¡¹ï¼æ¯æä¿®æ¹è§åéå¼200 :param custom_attributes: The custom_attributes of this Ruleset.201 :type custom_attributes: list[:class:`huaweicloudsdkcodecheck.v2.CustomAttributes`]202 """203 self._custom_attributes = custom_attributes204 def to_dict(self):205 """Returns the model properties as a dict"""206 result = {}207 for attr, _ in six.iteritems(self.openapi_types):208 value = getattr(self, attr)209 if isinstance(value, list):210 result[attr] = list(map(211 lambda x: x.to_dict() if hasattr(x, "to_dict") else x,212 value213 ))214 elif hasattr(value, "to_dict"):215 result[attr] = value.to_dict()216 elif isinstance(value, dict):217 result[attr] = dict(map(218 lambda item: (item[0], item[1].to_dict())219 if hasattr(item[1], "to_dict") else item,220 value.items()221 ))222 else:223 if attr in self.sensitive_list:224 result[attr] = "****"225 else:226 result[attr] = value227 return result228 def to_str(self):229 """Returns the string representation of the model"""230 import simplejson as json231 if six.PY2:232 import sys233 reload(sys)234 sys.setdefaultencoding("utf-8")235 return json.dumps(sanitize_for_serialization(self), ensure_ascii=False)236 def __repr__(self):237 """For `print`"""238 return self.to_str()239 def __eq__(self, other):240 """Returns true if both objects are equal"""241 if not isinstance(other, Ruleset):242 return False243 return self.__dict__ == other.__dict__244 def __ne__(self, other):245 """Returns true if both objects are not equal"""...
routing_table.py
Source:routing_table.py
1# coding: utf-82import handlers.active_handler as ActiveHandlers3import handlers.common_handler as CommonHandlers4import handlers.game_handler as game_handler5import handlers.live_handler as live_handler6import handlers.login_handler as LoginHandlers7import handlers.user_info_handler as UserInfoHandelers8check_token_dict = {'need_token': True}9uncheck_token_dict = {'need_token': False}10ROUTING_TABLE = [11 (r"/login/sendsms$", LoginHandlers.SendRegisterVerifyCodeHandler, uncheck_token_dict),12 (r"/login/sendpwsms$", LoginHandlers.SendResetPwVerifyCodeHandler, uncheck_token_dict),13 (r"/login/checkcode", LoginHandlers.ValidateSMSCode, uncheck_token_dict),14 (r"/login/register", LoginHandlers.RegisterUser, uncheck_token_dict),15 (r"/login/update", UserInfoHandelers.ModifyUser, check_token_dict),16 (r"/login/gethobby", CommonHandlers.GetHobby, check_token_dict),17 (r"/login/gethobbies", CommonHandlers.GetAllHobbiesHandle, check_token_dict),18 (r"/login/savehobby", UserInfoHandelers.SelectHobby, check_token_dict),19 (r"/login/login", LoginHandlers.UserLoginHandler, uncheck_token_dict),20 (r"/login/logout", LoginHandlers.UserOfflineHandler, check_token_dict),21 (r"/login/wx", LoginHandlers.WeChatUserLoginHandler, uncheck_token_dict),22 (r"/login/resetpw", UserInfoHandelers.ResetPasswordHandler, uncheck_token_dict),23 (r"/login/ver", CommonHandlers.GetAppVersionInfoHandler, uncheck_token_dict),24 (r"/ground/topic/get", ActiveHandlers.GetTopicsHandler, uncheck_token_dict),25 (r"/ground/active/add", ActiveHandlers.CreateActiveHandler, check_token_dict),26 (r"/ground/active/get", ActiveHandlers.GetActivesHandler, uncheck_token_dict),27 (r"/ground/active/delete", ActiveHandlers.DeleteActiveHandler, check_token_dict),28 (r"/ground/active/like", ActiveHandlers.LikeActiveHandler, check_token_dict),29 (r"/ground/active/refresh", ActiveHandlers.GetActiveMutableData, check_token_dict),30 (r"/ground/active/nearby", ActiveHandlers.GetActivesNearbyEpHandler, uncheck_token_dict),31 (r"/ground/active/comment/add", ActiveHandlers.AddCommentHandler, check_token_dict),32 (r"/ground/active/comment/delete", ActiveHandlers.DeleteCommentHandler, check_token_dict),33 (r"/ground/active/comment/get", ActiveHandlers.GetActiveCommentsHandler, check_token_dict),34 (r"/token/pic/upload", CommonHandlers.Get7CowUploadCertificate, check_token_dict),35 (r"/token/pic/download", CommonHandlers.Get7CowDownloadCertificate, check_token_dict),36 (r"/contactus/report", CommonHandlers.ReportHandler, check_token_dict),37 (r"/contactus/feedback", CommonHandlers.SuggestionHandler, check_token_dict),38 (r"/user/getsome", UserInfoHandelers.GetUserInfoHandler, uncheck_token_dict),39 (r"/user/detail", UserInfoHandelers.GetUserDetailHandler, uncheck_token_dict),40 (r"/user/details", UserInfoHandelers.GetUsersDetailHandler, uncheck_token_dict),41 (r"/user/visitors", UserInfoHandelers.GetUserVisitorsHandler, check_token_dict),42 (r"/user/sites", UserInfoHandelers.GetUserLocationHandler, check_token_dict),43 (r"/user/gold", UserInfoHandelers.GetUserGoldHandler, check_token_dict),44 (r"/discovery/users", UserInfoHandelers.GetRecommendUsersHandler, uncheck_token_dict),45 (r'/heartbeat/report', CommonHandlers.ReportHeartbeatHandler, check_token_dict),46]47import handlers.operation_handler as OpHandlers48import handlers.wshandler as ExpHandler49LIVE_TABLE = [50 (r'/live/create', live_handler.CreateLiveHandler, check_token_dict),51 (r'/live/resetpush', live_handler.ResetLivePushAddrHandler, check_token_dict),52 (r'/live/list', live_handler.GetLiveListHandler, uncheck_token_dict),53 # (r'/live/rank', live_handler.LiveFunctionalHandler, check_token_dict),54 (r'/live/detail', live_handler.GetLiveDetailHandler, check_token_dict),55 (r'/live/play', game_handler.GameCtrlHandler, check_token_dict),56 (r'/live/games', game_handler.GetGameListHandler, check_token_dict),57 (r'/live/rank', live_handler.RankHandler, check_token_dict),58 (r'/sock/live', ExpHandler.HostHandler),59 (r'/sock/watch', ExpHandler.WatcherHandler)60]61OP_TABLE = [62 (r"/op/hobby/add", OpHandlers.AddHobbyPageHandler),63 (r"/op/hobby/query", OpHandlers.ShowHobbiesHandler),64 (r"/op/topic/add", OpHandlers.AddTopicHandler),65 (r"/op/topic/update", OpHandlers.UpdateTopicHandler),66 (r"/op/topic/query", OpHandlers.QueryTopicHandler),67 (r"/op/switch/redis", OpHandlers.SwitchRedisHandler),68 (r"/op/appver/set", OpHandlers.ChangeVersionHandler),69 (r"/op/appver/get", OpHandlers.GetVersionHandler),70 (r"/op/user/control", OpHandlers.UserOperationHandler)71]72import pay.pay_handlers as pay_handlers73PAY_TABLE = [74 (r'/pay/cb/wx', pay_handlers.WeinXinCallbackHandler),75 (r'/pay/cb/zfb', pay_handlers.AliPayCallbackHandler),76 (r'/pay/q', pay_handlers.OrderQueryHandler, check_token_dict),77 (r'/pay/do', pay_handlers.PayHandler, check_token_dict),78 (r'/pay/his', pay_handlers.OrdersHandler, check_token_dict),79 (r'/pay/cargo', CommonHandlers.GetCargoConfHandler, check_token_dict)...
scan_domain.py
Source:scan_domain.py
1import os2import sys3import subprocess4import time5import re6import threading7gUncheckDomainFile = 'UncheckDomain.txt'8gNotOccupiedFile = 'NotOccupied.txt'9gAlreadyOccupiedFile = 'AlreadyOccupied.txt'10class ScanDomain:11 def __init__(self):12 self.set_not_occupied_file = 'NotOccupied.txt'13 self.set_already_occupied_file = 'AlreadyOccupied.txt'14 self.set_thread_cnt = 2015 self.not_occupied_fd = None16 self.already_occupied_fd = None17 self.set_uncheck_domain_file = 'UncheckDomain.txt'18 self.lock = threading.Lock()19 self.uncheck_domain_list = list()20 self.quit = False21 self.running_thread_cnt = 022 self.do_init()23 time.sleep(3)24 pass25 def do_init(self):26 self.already_occupied_fd = open(self.set_already_occupied_file, 'a+')27 self.not_occupied_fd = open(self.set_not_occupied_file, 'a+')28 self.get_domain()29 pass30 def add_not_occupied_domain(self, domain):31 self.lock.acquire()32 self.not_occupied_fd.write(domain + '\n')33 self.not_occupied_fd.flush()34 self.lock.release()35 pass36 def add_already_occupied_domain(self, domain):37 self.lock.acquire()38 self.already_occupied_fd.write(domain + '\n')39 self.already_occupied_fd.flush()40 self.lock.release()41 pass42 def add_uncheck_domain(self, domain):43 self.lock.acquire()44 self.uncheck_domain_list.append(domain)45 self.lock.release()46 pass47 def get_domain(self):48 if os.path.exists(self.set_uncheck_domain_file):49 words_file = gUncheckDomainFile50 with open(words_file, 'r') as fd:51 while True:52 line = fd.readline()53 if not line:54 break55 self.uncheck_domain_list.append(line[:-1])56 else:57 words_file = '/usr/share/dict/words'58 with open(words_file, 'r') as fd:59 while True:60 line = fd.readline()61 if not line:62 break63 self.uncheck_domain_list.append(line[:-1] + '.cc')64 print 'Load from [%s] Done, cnt [%d]' % (words_file, len(self.uncheck_domain_list))65 pass66 def get_domain_to_check(self):67 self.lock.acquire()68 if not len(self.uncheck_domain_list):69 ret_domain = None70 else:71 ret_domain = self.uncheck_domain_list.pop()72 self.lock.release()73 return ret_domain74 pass75 def save_uncheck_doman_list(self):76 with open(self.set_uncheck_domain_file, 'w+') as fd:77 for domain in self.uncheck_domain_list:78 fd.write(domain + '\n')79 pass80 def check_domain(self, domain_url):81 command = ['nslookup', domain_url]82 pipe = subprocess.Popen(command, stdout=subprocess.PIPE)83 out = ''84 while True:85 if pipe.poll() is not None:86 break87 time.sleep(0.1)88 out = pipe.stdout.read()89 ret = True90 pattern = 'server can\'t find'91 m = re.search(pattern, out)92 if m:93 print 'Not occupied [%s]' % domain_url94 ret = True95 pattern = 'answer'96 m = re.search(pattern, out)97 if m:98 print 'Already occupied [%s]' % domain_url99 ret = False100 return ret101 pass102 def check_domain_thread(self):103 self.running_thread_cnt += 1104 while True:105 domain = self.get_domain_to_check()106 if not domain:107 break108 ret = self.check_domain(domain)109 if ret:110 self.add_not_occupied_domain(domain)111 else:112 self.add_already_occupied_domain(domain)113 if self.quit:114 self.add_uncheck_domain(domain)115 break116 self.running_thread_cnt -= 1117 def start_scan(self):118 for idx in range(self.set_thread_cnt):119 pro = threading.Thread(target=self.check_domain_thread)120 pro.start()121 while True:122 try:123 time.sleep(5)124 if not len(self.uncheck_domain_list):125 print 'All Done'126 self.save_uncheck_doman_list()127 return128 except KeyboardInterrupt:129 self.quit = True130 while 0 != self.running_thread_cnt:131 print 'Please waiting for thread quit [%d]' % self.running_thread_cnt132 time.sleep(1)133 self.save_uncheck_doman_list()134 print 'Quit Now'135 return136 pass137 def quit(self):138 pass139def do_test():140 scan_handle = ScanDomain()141 scan_handle.start_scan()142 pass143if __name__ == '__main__':...
compare.py
Source:compare.py
1#!/usr/bin/env python2# -*- encoding: utf-8 -*-3'''4@File : compare.py5@Author : Billy Zhou6@Time : 2021/08/227@Desc : None8'''9import sys10from pathlib import Path11cwdPath = Path(__file__).parents[2]12sys.path.append(str(cwdPath))13from src.manager.Logger import logger14log = logger.get_logger(__name__)15import copy16from collections.abc import Mapping17from src.basic.input_check import input_checking_YN18def dict_compare(19 dict_uncheck: dict, dict_refer: dict,20 dict_checked: dict = {}, suffix: str = '[]', lv: int = 0, diff_autoadd=True):21 """Compare two dict and merge the missing part."""22 if not dict_checked:23 log.debug('dict_checked init')24 dict_checked = copy.deepcopy(dict_uncheck)25 sub_lv = lv + 126 suffix = '[]' if lv == 0 else suffix27 if not dict_uncheck:28 # missing part29 if diff_autoadd:30 dict_checked = dict_refer31 else:32 selection = input_checking_YN('dict_uncheck is blank. Fill it with dict_refer?')33 if selection == 'Y':34 print('Filled.')35 dict_checked = dict_refer36 else:37 print('Canceled.')38 else:39 log.debug('dict_checked: {0}'.format(dict_checked))40 # diff with dict_refer base on dict_refer.items()41 for key, value_refer in dict_refer.items():42 suffix_ = "[" + str(key) + "]"43 log.debug("sub_lv: %s", sub_lv)44 log.debug("suffix: %s", suffix)45 log.debug("suffix_: %s", suffix_)46 if not dict_uncheck.get(key):47 # dict_uncheck missing part in dict_refer48 if diff_autoadd:49 dict_checked[key] = dict_refer[key]50 else:51 sub_suffix = suffix + suffix_ if suffix != '[]' else suffix_52 tip_words = 'dict_uncheck{0} is missing. Add it with dict_refer{0}?'.format(sub_suffix)53 selection = input_checking_YN(tip_words)54 if selection == 'Y':55 print('Added.')56 dict_checked[key] = dict_refer[key]57 else:58 print('Canceled.')59 else:60 sub_suffix = suffix + suffix_ if suffix != '[]' else suffix_61 if isinstance(value_refer, Mapping):62 # check deeper for dict type of value_refer63 # value_refer equal to dict_refer[key]64 log.debug("sub_suffix: %s", sub_suffix)65 dict_compare(66 dict_uncheck[key], value_refer, dict_checked[key],67 sub_suffix, sub_lv, diff_autoadd)68 else:69 # check diff part of values between dict_uncheck and dict_refer70 if str(dict_uncheck[key]) != str(dict_refer[key]):71 print('Values diff between dict_uncheck{0} and dict_refer{0}.'.format(sub_suffix))72 print('Value of dict_uncheck{0}: {1}'.format(sub_suffix, dict_uncheck[key]))73 print('Value of dict_refer{0}: {1}'.format(sub_suffix, value_refer))74 tip_words = 'Replace the value of dict_uncheck{0} with dict_refer{0}?'.format(sub_suffix)75 selection = input_checking_YN(tip_words)76 if selection == 'Y':77 print('Replaced.')78 dict_checked[key] = dict_refer[key]79 else:80 print('Canceled.')81 return dict_checked82if __name__ == '__main__':83 d1 = {84 1: {85 2: {86 7: [9]87 },88 6: [7, 8]89 },90 4: [7, 8]91 }92 d2 = {93 1: {94 2: {95 9: [10]96 },97 3: [7, 8]98 },99 2: {100 1: {},101 },102 3: [7, 8],103 4: [5, 6],104 }105 print(dict_compare(d1, d2, diff_autoadd=False))106 print("d1: {0}".format(d1))...
IDFCalWord.py
Source:IDFCalWord.py
1#!/usr/bin/env python2# -*- coding: utf-8 -*-34##########################5# Fuction: 6# Author: Daoming, Wujing, Luojian7# Date: 2012-07-238##########################910import sys, os, string, time11from ctypes import *12from datetime import datetime131415############################ Function Define ###########################16def ReadwordIDF(filepath):17 wordIDF_read = {}18 idffilew = open(filepath, 'r')19 for idfline in idffilew:20 idfline = idfline.replace('\n','').strip()21 word = idfline.split("###")[0].strip()22 #print word.decode('utf8').encode('gbk')23 idfcount = idfline.split("###")[1].strip()24 #print idfcount25 try:26 wordIDF_read[word] = int(idfcount)27 except Exception, e:28 continue29 idffilew.close()30 return wordIDF_read3132def PrintwordIDF(wordIDF, filepath):33 filew = open(filepath, 'w')34 for word in wordIDF:35 filew.write(word)36 filew.write(" ### ")37 filew.write(str(wordIDF[word]))38 filew.write("\n")39 filew.close()4041def run(root, filepath, startDate, endDate):42#------------- UserDict Init -------------------43 wordIDF_read = ReadwordIDF(filepath)44 wordIDF = {}45 userdictPath = "D:\\ICTCLAS\userdict.txt"46 uncheckPath = "D:\\ICTCLAS\uncheck.txt"47 userdictFile = open(userdictPath, 'r')48 uncheckFile = open(uncheckPath, 'r')49 for userdictLine in userdictFile:50 userdictLine = userdictLine.replace('\n','').strip()51 if userdictLine != '':52 try:53 wordIDF[userdictLine] = wordIDF_read[userdictLine]54 except Exception,e:55 wordIDF[userdictLine] = 056 print "Userdict word amount: " + str(len(wordIDF))57 userdictFile.close()58 for uncheckLine in uncheckFile:59 uncheckLine = uncheckLine.replace('\n','').strip()60 try:61 del wordIDF[uncheckLine]62 except Exception, e:63 continue64 print "After Uncheck word amount: " + str(len(wordIDF))65 uncheckFile.close()66 #os.system("pause")6768#------------- WordIDF Calculate -------------------69 doc_num = 070 docindex_num = 071 for root, dirnames, filenames in os.walk(root):72 for filename in filenames:73 doc_num += 174 if doc_num % 1000 == 0:75 print "Word IDF Calculated " + str(doc_num) + " files..."76 if not filename.endswith('.txt'):77 continue78 filedate = datetime.strptime(filename[:8], '%Y%m%d')79 if not (filedate >= startDate and filedate <= endDate):80 continue81 docindex_num += 182 path = os.path.join(root, filename)83# print path84 filew = open(path, 'r') 85#-------- Read Divided File & WordIDF Count----------86 for line in filew:87 for word in line.strip().split(" "):88 word = word.strip()89 try:90 wordIDF[word] = wordIDF[word] + 191 except Exception, e:92 continue93 filew.close()94 print "WordIDF Done..."95 print "Word IDF Added " + str(docindex_num) + " files..."96 97 return wordIDF9899100########################### Main Function ##############################101if __name__ == '__main__':102 if len(sys.argv) < 4:103 print "Usage: <source_data>"104#------------- Variable Define -----------------105 sourcedata = sys.argv[1]106107 startDate = datetime.strptime(sys.argv[2], '%Y%m%d')108 endDate = datetime.strptime(sys.argv[3], '%Y%m%d')109110 if sourcedata == "ç 究æ¥å".decode('utf8').encode('gbk'):111 root = "D:\\DATA\\Lucene\\MBStrategy"112 filepath = "D:\\ICTCLAS\\wordIDFWord_MBStrategy.txt"113 if sourcedata == "è¡ç¥¨è®ºå".decode('utf8').encode('gbk'):114 root = "D:\\DATA\\Lucene\\text"115 filepath = "D:\\ICTCLAS\\wordIDFWord_text.txt"116 if sourcedata == "个è¡æ°é»".decode('utf8').encode('gbk'):117 root = "D:\\DATA\\Lucene\\sinaStockNews"118 filepath = "D:\\ICTCLAS\\wordIDFWord_sinaStockNews.txt"119120 wordIDF = {}121 wordIDF = run(root, filepath, startDate, endDate)122123 PrintwordIDF(wordIDF, filepath)124#------------------- END -----------------------125# os.system("pause")
...
unCheckList2.py
Source:unCheckList2.py
1#!/usr/bin/python2# -*- coding: UTF-8 -*-3from __future__ import print_function4import codecs5import sys6import time7import datetime8import os9def read_chinese_file(filepath):10 f = open(filepath, 'r')11 lines = [line.strip() for line in f]12 for index, ch in enumerate(lines):13 lines[index] = str(ch)14 f.close()15 return lines16def Findaite(message):17 i = 018 for charater in message:19 if charater == '@':20 return i21 i = i+122f = open('Check-inlist.txt', encoding='UTF-8')23check_in_list = [line.strip() for line in f]24for index, ch in enumerate(check_in_list):25 check_in_list[index] = str(ch)26f.close()27# å°å½å¤©æå¡ååå¤å¶å°testfile.txtä¸ï¼è¯»å
¥è¯¥æ件å°checked_names28daka_f = open('testfile.txt', encoding='UTF-8')29checked_names = [line.strip() for line in daka_f]30for index, ch in enumerate(checked_names):31 checked_names[index] = str(ch)32uncheck_list = []33for name in check_in_list:34 # 移é¤å¼å¤´35 extract_name = name36 for index, ch in enumerate(name):37 if ch == "@":38 extract_name = name[index+1:]39 break40 # 移é¤æ«å°¾ç©ºæ ¼41 while len(extract_name) > 1 and extract_name[-1] == " ":42 extract_name = extract_name[:-2]43 found = False44 for checked_name in checked_names:45 if extract_name in checked_name:46 found = True47 break48 if found == False:49 uncheck_list.append(name)50notification = "æ»´æ»´æ»´æå¡æ示ï¼ç°å¨æ¯å京æ¶é´ï¼"51output = "ï¼è¯·ä»¥ä¸æªå®ææå¡çå§å¨å°½éå®ææå¡å¦"52print("\n\n"+notification+time.strftime(53 "%Y-%m-%d %H:%M:%S", time.localtime())+output)54for index, uncheck_name in enumerate(uncheck_list):55 i = Findaite(uncheck_name)56 uncheck_list[index] = uncheck_name[i+1:]57 print('@'+uncheck_list[index])58# new here59# åå
¥å½å¤©æå¡è®°å½ï¼å¤ææ¶é´æ¯å¦æ©äºå½å¤©åäºç¹ï¼å¦ææ©äºï¼åæ¯åä¸å¤©çæå¡60end_check_time = datetime.datetime.strptime(61 str(datetime.datetime.now().date())+'12:00', '%Y-%m-%d%H:%M')62time_now = datetime.datetime.now()63if time_now < end_check_time:64 check_day = time_now - \65 datetime.timedelta(days=1).strftime('%Y-%m-%d')66else:67 check_day = time_now.strftime('%Y-%m-%d')68check_log_f = open('log/'+check_day + ' checked.txt', 'w')69for checked_name in checked_names:70 check_log_f.write(checked_name) # .encode('utf-8')71 check_log_f.write('\n')72check_log_f.close()73uncheck_log_f = open('log/'+check_day + ' unchecked.txt', 'w')74for uncheck_name in uncheck_list:75 uncheck_log_f.write(uncheck_name) # .encode('utf-8')76 uncheck_log_f.write('\n')77uncheck_log_f.close()78# è¾åºæªæå¡åå²è®°å½79uncheck_dict = {}80path = os.getcwd()+'/log'81files = os.listdir(path)82for file in files:83 if 'unchecked' in file:84 names = read_chinese_file(path + '/' + file)85 for name in names:86 if name in uncheck_dict:87 uncheck_dict[name] = uncheck_dict[name] + 188 else:89 uncheck_dict[name] = 190# ææªæå¡æ¬¡æ°æåº91uncheck_thre = len(files) / 4 + 192sorted_pairs = sorted(uncheck_dict.items(), key=lambda kv: kv[1])93print('\n'+"å¤æ¬¡æªæå¡åå")94for pair in sorted_pairs:95 if pair[1] >= uncheck_thre:96 print(pair[0], end=' ')97 print(pair[1], end='')...
ClassePb.py
Source:ClassePb.py
1from PySide6 import QtCore2from src.build.mods.Functions import Functions3class ClassePb:4 def __init__(5 self,6 widget,7 dim_ico,8 DIM_ICO,9 img,10 img_hover,11 img_uncheck,12 img_uncheck_hover,13 img_check,14 img_check_hover,15 img_rgb,16 img_hover_rgb,17 img_uncheck_rgb,18 img_uncheck_hover_rgb,19 img_check_rgb,20 img_check_hover_rgb,21 ):22 self.widget = widget23 self.dim_ico = dim_ico24 self.DIM_ICO = DIM_ICO25 self.img = img26 self.img_hover = img_hover27 self.img_uncheck = img_uncheck28 self.img_uncheck_hover = img_uncheck_hover29 self.img_check = img_check30 self.img_check_hover = img_check_hover31 self.img_rgb = img_rgb32 self.img_hover_rgb = img_hover_rgb33 self.img_uncheck_rgb = img_uncheck_rgb34 self.img_uncheck_hover_rgb = img_uncheck_hover_rgb35 self.img_check_rgb = img_check_rgb36 self.img_check_hover_rgb = img_check_hover_rgb37 def ENT_CHECK(self, event):38 if self.widget.isEnabled():39 if not self.widget.isChecked():40 Functions().SET_ICON_A_SUPPR(wg=self.widget, img=self.img_uncheck_hover + self.img_uncheck_hover_rgb, dim=self.dim_ico)41 else:42 Functions().SET_ICON_A_SUPPR(wg=self.widget, img=self.img_check_hover + self.img_check_hover_rgb, dim=self.dim_ico)43 def LVE_CHECK(self, event):44 if self.widget.isEnabled():45 if not self.widget.isChecked():46 Functions().SET_ICON_A_SUPPR(wg=self.widget, img=self.img_uncheck + self.img_uncheck_rgb, dim=self.dim_ico)47 else:48 Functions().SET_ICON_A_SUPPR(wg=self.widget, img=self.img_check + self.img_check_rgb, dim=self.dim_ico)49 def MP_CHECK(self, event):50 if self.widget.isEnabled():51 if not self.widget.isChecked():52 self.widget.setChecked(True)53 Functions().SET_ICON_A_SUPPR(wg=self.widget, img=self.img_check_hover + self.img_check_hover_rgb, dim=self.dim_ico)54 else:55 self.widget.setChecked(False)56 Functions().SET_ICON_A_SUPPR(wg=self.widget, img=self.img_uncheck_hover + self.img_uncheck_hover_rgb, dim=self.dim_ico)57 def ENT_ICO(self, event):58 if not self.widget.isChecked() and self.widget.isEnabled():59 Functions().SET_ICON_A_SUPPR(wg=self.widget, img=self.img + self.img_hover_rgb, dim=self.dim_ico)60 def LVE_ICO(self, event):61 if not self.widget.isChecked() and self.widget.isEnabled():62 Functions().SET_ICON_A_SUPPR(wg=self.widget, img=self.img + self.img_rgb, dim=self.dim_ico)63 def MP_ICO(self, event):64 if self.widget.isChecked() and self.widget.isEnabled():65 self.widget.setChecked(False)66 Functions().SET_ICON_A_SUPPR(wg=self.widget, img=self.img + self.img_rgb, dim=self.dim_ico)67 elif not self.widget.isChecked() and self.widget.isEnabled():68 self.widget.setChecked(True)69 Functions().SET_ICON_A_SUPPR(wg=self.widget, img=self.img + self.img_hover_rgb, dim=self.dim_ico)70 def ENT_ZOOM(self, event):71 if not self.widget.isChecked() and self.widget.isEnabled():72 self.widget.setIconSize(QtCore.QSize(self.DIM_ICO, self.DIM_ICO))73 def LVE_ZOOM(self, event):74 if not self.widget.isChecked() and self.widget.isEnabled():75 self.widget.setIconSize(QtCore.QSize(self.dim_ico, self.dim_ico))76"""77if self.wg.isEnabled():78 if not self.wg.isChecked():79 pass80 else:81 pass...
unCheckList.py
Source:unCheckList.py
1#!/usr/bin/python2# -*- coding: UTF-8 -*-3from __future__ import print_function4import codecs5import sys6import time7import datetime8import os9from datetime import timedelta, datetime10def read_chinese_file(filepath):11 f = open(filepath, 'r')12 lines = [line.strip() for line in f]13 for index, ch in enumerate(lines):14 lines[index] = str(ch).decode('utf-8')15 f.close()16 return lines17check_in_list = read_chinese_file('Check-inlist.txt')18checked_names = sys.stdin.readlines()19for index, ch in enumerate(checked_names):20 checked_names[index] = str(ch).decode('utf-8')21uncheck_list = []22for name in check_in_list:23 # 移é¤å¼å¤´24 extract_name = name25 for index, ch in enumerate(name):26 if ch == " ":27 extract_name = name[index+1:]28 break29 # 移é¤æ«å°¾ç©ºæ ¼30 while len(extract_name) > 1 and extract_name[-1] == " ":31 extract_name = extract_name[:-2]32 found = False33 for checked_name in checked_names:34 if extract_name in checked_name:35 found = True36 break37 if found == False:38 uncheck_list.append(extract_name)39notification = "æ»´æ»´æ»´æå¡æ示ï¼ç°å¨æ¯å京æ¶é´ï¼"40output = "ï¼è¯·ä»¥ä¸æªå®ææå¡çå§å¨å°½éå®ææå¡å¦"41print("\n\n"+notification.decode('utf-8')+time.strftime(42 "%Y-%m-%d %H:%M:%S", time.localtime())+output.decode('utf-8'))43for uncheck_name in uncheck_list:44 print('@'+uncheck_name)45# åå
¥å½å¤©æå¡è®°å½ï¼å¤ææ¶é´æ¯å¦æ©äºå½å¤©ä¸ååç¹ï¼å¦ææ©äºï¼åæ¯åä¸å¤©çæå¡46end_check_time = datetime.strptime(47 str(datetime.now().date())+'16:00', '%Y-%m-%d%H:%M')48time_now = datetime.now()49if time_now < end_check_time:50 check_day = (datetime.today() + timedelta(-1)).strftime('%Y-%m-%d')51else:52 check_day = time_now.strftime('%Y-%m-%d')53check_log_f = open('log/'+check_day + ' checked.txt', 'w')54for checked_name in checked_names:55 check_log_f.write(checked_name.encode('utf-8'))56check_log_f.close()57uncheck_log_f = open('log/'+check_day + ' unchecked.txt', 'w')58for uncheck_name in uncheck_list:59 uncheck_log_f.write(uncheck_name.encode('utf-8'))60 uncheck_log_f.write('\n')61uncheck_log_f.close()62# è¾åºæªæå¡åå²è®°å½63uncheck_dict = {}64path = os.getcwd()+'/log'65files = os.listdir(path)66for file in files:67 if 'unchecked' in file:68 names = read_chinese_file(path + '/' + file)69 for name in names:70 if name in uncheck_dict:71 uncheck_dict[name] = uncheck_dict[name] + 172 else:73 uncheck_dict[name] = 174# ææªæå¡æ¬¡æ°æåº75uncheck_thre = len(files)/4 + 176sorted_pairs = sorted(uncheck_dict.items(), key=lambda kv: kv[1])77print('\n'+"å¤æ¬¡æªæå¡åå".decode('utf-8'))78for pair in sorted_pairs:79 if pair[1] >= uncheck_thre:80 print(pair[0], end=' ')81 print(pair[1], end='')...
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({ headless: false });4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.fill('input[aria-label="Search"]', 'Playwright');7 await page.keyboard.press('Enter');8 await page.waitForSelector('text=Playwright');9 await page.click('text=Playwright');10 await page.waitForTimeout(3000);11 await page.click('text=Docs');12 await page.waitForTimeout(3000);13 await page.click('text=API');14 await page.waitForTimeout(3000);15 await page.click('text=Page');16 await page.waitForTimeout(3000);17 await page.click('text=uncheck');18 await page.waitForTimeout(3000);19 await page.click('text=Parameters');20 await page.waitForTimeout(3000);21 await page.click('text=selector');22 await page.waitForTimeout(3000);23 await page.click('text=Returns');24 await page.waitForTimeout(3000);25 await page.click('text=Promise<void>');26 await page.waitForTimeout(3000);27 await page.click('text=Example');28 await page.waitForTimeout(3000);29 await page.click('text=Uncheck the checkbox');30 await page.waitForTimeout(3000);31 await page.click('text=See below for a full example.');32 await page.waitForTimeout(3000);33 await page.click('text=uncheck');34 await page.waitForTimeout(3000);35 await page.waitForTimeout(3000);36 await page.waitForTimeout(3000);37 await page.click('text=await page.uncheck(\'input[name="newsletter"]\');');38 await page.waitForTimeout(3000);39 await page.click('text=await page.uncheck(\'input[type="checkbox"]\');');40 await page.waitForTimeout(3000);41 await page.click('text=await page.uncheck(\'input:enabled\');');42 await page.waitForTimeout(3000);43 await page.click('text=await
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({ headless: false });4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.uncheck('input[name="q"]');7 await browser.close();8})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const page = await browser.newPage();5 await page.check('input[placeholder="What needs to be done?"]');6 await page.uncheck('input[placeholder="What needs to be done?"]');7 await browser.close();8})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const [response] = await Promise.all([7 page.waitForResponse('**/json'),8 ]);9 const cookies = await page.context().cookies();10 console.log(cookies);11 await browser.close();12})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const page = await browser.newPage();5 await page.uncheck('#someCheckbox');6 await browser.close();7})();8## 3. `page.waitForSelector(selector[, options])`9await page.waitForSelector('#searchform');10await page.waitForSelector('#searchform', { hidden: true });11await page.waitForSelector('#searchform', { state: 'detached' });12## 4. `page.waitForXPath(xpath[, options])`
Using AI Code Generation
1const { chromium } = require('playwright');2const assert = require('assert');3(async () => {4 const browser = await chromium.launch({headless: false, slowMo: 50});5 const context = await browser.newContext();6 const page = await context.newPage();7 const checkbox = await page.$('#checkboxes input:nth-of-type(1)');8 await checkbox.uncheck();9 const checked = await checkbox.isChecked();10 assert.equal(checked, false);11 await browser.close();12})();13const { chromium } = require('playwright');14const assert = require('assert');15(async () => {16 const browser = await chromium.launch({headless: false, slowMo: 50});17 const context = await browser.newContext();18 const page = await context.newPage();19 const checkbox = await page.$('#checkboxes input:nth-of-type(1)');20 await checkbox.check();21 const checked = await checkbox.isChecked();22 assert.equal(checked, true);23 await browser.close();24})();25const { chromium } = require('playwright');26const assert = require('assert');27(async () => {28 const browser = await chromium.launch({headless: false, slowMo: 50});29 const context = await browser.newContext();30 const page = await context.newPage();31 const dropdown = await page.$('#dropdown');32 await dropdown.selectOption('Option 2');33 const selectedOption = await page.$eval('#dropdown', dropdown => dropdown.value);34 assert.equal(selectedOption, '2');35 await browser.close();36})();37const { chromium } = require('playwright');38const assert = require('assert');39(async () => {
Using AI Code Generation
1const { test, expect } = require('@playwright/test');2test('test', async ({ page }) => {3 await page.click('text=Get started');4 await page.uncheck('input[name="newsletter"]');5 await page.click('text=Get started');6 await page.click('text=Get started');7 await page.uncheck('input[name="newsletter"]');8 await page.click('text=Get started');9});
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.check('input[type="checkbox"]');7 await page.uncheck('input[type="checkbox"]');8 await browser.close();9})();10const playwright = require('playwright');11(async () => {12 const browser = await playwright.chromium.launch();13 const context = await browser.newContext();14 const page = await context.newPage();15 await page.check('input[type="checkbox"]');16 await page.uncheck('input[type="checkbox"]');17 await browser.close();18})();19const playwright = require('playwright');20(async () => {21 const browser = await playwright.chromium.launch();22 const context = await browser.newContext();23 const page = await context.newPage();24 await page.check('input[type="checkbox"]');25 await page.uncheck('input[type="checkbox"]');26 await browser.close();27})();28const playwright = require('playwright');29(async () => {30 const browser = await playwright.chromium.launch();31 const context = await browser.newContext();32 const page = await context.newPage();33 await page.check('input[type="checkbox"]');34 await page.uncheck('input[type="checkbox"]');35 await browser.close();36})();37const playwright = require('playwright');38(async () => {39 const browser = await playwright.chromium.launch();40 const context = await browser.newContext();41 const page = await context.newPage();42 await page.check('input[type="checkbox"]');43 await page.uncheck('input
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!