Best Python code snippet using toolium_python
bfe_webjournal_article_body.py
Source:bfe_webjournal_article_body.py
1#!/usr/bin/env python2# -*- coding: utf-8 -*-3## This file is part of Invenio.4## Copyright (C) 2009, 2010, 2011 CERN.5##6## Invenio is free software; you can redistribute it and/or7## modify it under the terms of the GNU General Public License as8## published by the Free Software Foundation; either version 2 of the9## License, or (at your option) any later version.10##11## Invenio is distributed in the hope that it will be useful, but12## WITHOUT ANY WARRANTY; without even the implied warranty of13## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU14## General Public License for more details.15##16## You should have received a copy of the GNU General Public License17## along with Invenio; if not, write to the Free Software Foundation, Inc.,18## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.19"""20WebJournal Element - display article body. Also has support for old21CERN Bulletin articles.22"""23import re24import types25from invenio.htmlutils import HTMLWasher26from invenio.messages import gettext_set_language27from invenio.urlutils import create_html_mailto28from invenio.config import CFG_CERN_SITE29from invenio.webjournal_utils import parse_url_string30from invenio.bibformat_elements import bfe_fulltext31def format_element(bfo, separator='<br/>'):32 """33 Display article body34 @param separator: separator between each body35 """36 # Retrieve context (journal, issue and category) from URI37 args = parse_url_string(bfo.user_info['uri'])38 ln = args["ln"]39 _ = gettext_set_language(ln)40 if ln == "fr":41 article = bfo.fields('590__b')42 if not article or \43 (len(article) == 1 and \44 (article[0].strip() in ['', '<br />', '<!--HTML--><br />'])):45 article = bfo.fields('520__b')46 else:47 article = bfo.fields('520__b')48 if not article or \49 (len(article) == 1 and \50 (article[0].strip() in ['', '<br />', '<!--HTML--><br />'])):51 article = bfo.fields('590__b')52 if not CFG_CERN_SITE or \53 not bfo.field('980__a').startswith('BULLETIN'):54 return separator.join(article)55 ################################################################56 # CERN Bulletin-specific code #57 ################################################################58 # We need a compatibility layer for old CERN Bulletin59 # articles. Identify them and process them if needed.60 is_old_cern_bulletin_article = False61 if bfo.field('980__a').startswith('BULLETIN'):62 try:63 year = int(bfo.fields('260__c')[0])64 except IndexError:65 year = 200066 if year < 2009 or \67 (bfo.field('980__a').startswith('BULLETINSTAFF') and \68 ("CERN EDS" in bfo.field('595__a'))):69 is_old_cern_bulletin_article = True70 header_out = ''71 if not is_old_cern_bulletin_article:72 # Return the same as any other journal article73 return separator.join(article)74 # Old CERN articles75 if year < 2007 or bfo.field('980__a').startswith('BULLETINSTAFF'):76 # Really old CERN articles77 if len(article) > 0:78 # CERN-only: old CERN Bulletin articles79 return __backward_compatible_HTML(article[0]) + \80 (bfo.field('980__a').startswith('BULLETINSTAFF') and \81 ('<br/><br/>' + bfe_fulltext.format_element(bfo, style="", show_icons='yes')) \82 or '')83 else:84 return ''85 # Not-so-old CERN articles follow:86 # 2. prepare regex's for the elements87 #=====================================================88 from invenio.webjournal_utils import \89 image_pattern, \90 para_pattern, \91 header_pattern92 page_elements = {}93 # 3. get the header (either from marc xml or regex)94 #=====================================================95 if bfo.lang == "fr":96 header = bfo.field('590__a')97 if header == '':98 header = bfo.field('520__a')99 else:100 header = bfo.field('520__a')101 if header == '':102 header = bfo.field('590__a')103 if not header:104 try:105 header_obj = re.search(header_pattern, article[0])106 header_text = header_obj.group("header")107 except:108 header_text = ""109 else:110 header_text = header111 washer = HTMLWasher()112 header_text_clean = washer.wash(html_buffer=header_text,113 allowed_tag_whitelist=['a'],114 allowed_attribute_whitelist=['href'])115 header_out = '<p class="articleHeader">' + header_text_clean + '</p>'116 # strip out all empty p tags and the header117 try:118 article = article[0].replace("<p/>", "")119 article = article.replace(header_text, "")120 article = article.replace(header_text_clean, "")121 except IndexError:122 article = ""123 image_iter = image_pattern.finditer(article)124 difference_from_original = 0125 for image in image_iter:126 page_elements[image.start()] = {"link" : image.group("hyperlink"),127 "image" : image.group("image"),128 "caption" : image.group("caption")}129 # make sure we delete the image from the article (else might be used twice)130 start_index = image.span()[0] - difference_from_original131 end_index = image.span()[1] - difference_from_original132 article = article.replace(article[start_index:end_index], "")133 difference_from_original += image.span()[1] - image.span()[0]134 # replace <center> by <p><center>135 article = article.replace("<center>", "<p><center>")136 article = article.replace("</center>", "</center></p>")137 para_iter = para_pattern.finditer(article)138 for paragraph in para_iter:139 page_elements[paragraph.start()] = paragraph.group("paragraph")140 # TODO: find a way to do this inline in the dict141 ordered_keys = page_elements.keys()142 ordered_keys.sort()143 article_out = ""144 left_right_lever = True145 did_you_know_box = False146 for key in ordered_keys:147 if type(page_elements[key]) == types.DictType:148 if left_right_lever == True:149 article_out += '<div class="phrwithcaption"><div class="imageScale">'150 else:151 article_out += '<div class="phlwithcaption"><div class="imageScale">'152 if page_elements[key]["link"] != None:153 article_out += '<a href="' + page_elements[key]["link"] + '">'154 article_out += '<img class="featureImageScaleHolder" src="' + \155 page_elements[key]["image"] + '" border="0" />' + \156 '</a>' + \157 '</div>'158 if page_elements[key]["caption"] != None:159 article_out += '<p>' + page_elements[key]["caption"] + \160 '</p>'161 article_out += '</div>'162 elif type(page_elements[key]) == types.StringType:163 left_right_lever = not left_right_lever164 if (page_elements[key].lower().find("did you know") != -1) or \165 (page_elements[key].lower().find("le saviez-vous ?") != -1):166 did_you_know_box = True167 continue168 if did_you_know_box == True:169 did_you_know_box = False170 article_out += __did_you_know_box(page_elements[key],171 left_right_lever,172 bfo.lang)173 continue174 article_out += '<p>'175 article_out += page_elements[key]176 article_out += '</p>'177 return header_out + article_out178def escape_values(bfo):179 """180 Called by BibFormat in order to check if output of this element181 should be escaped.182 """183 return 0184def __did_you_know_box(content, left_right_lever, ln):185 """186 Formats a did you know box187 """188 _ = gettext_set_language(ln)189 box_out = ""190 box_out += '<div class="phlwithcaption">'191 box_out += '<h3 style="margin-top:0px;border-bottom:0px;" class="active">%s</h3>' % _("Did you know?")192 box_out += '<p>%s</p>' % content193 box_out += '</div>'194 return box_out195def __backward_compatible_HTML(article):196 """197 Basically only by-passing the HTML.198 Add HTML treating to old articles here.199 """200 return article201def __add_publish_buttons(title, header, uri, ln):202 """203 Prints digg, delicious, etc button204 """205 publish_area = '<ul class="publish">'206 publish_area += __add_email_button(title, uri, ln)207 publish_area += __add_digg_button(title, header)208 publish_area += __add_reddit_button(title, uri)209 publish_area += __add_delicious_button(title, uri)210 publish_area += '</ul>'211 return publish_area212def __add_email_button(title, uri, ln):213 """214 adds an email this article button, providing a standard subject text,215 title and a link to the article.216 """217 _ = gettext_set_language(ln)218 email_button = '<li id="mail">'219 email_body = _('''Hi,220Have a look at the following article:221<%(url)s>''') % uri222 email_button += create_html_mailto('',223 subject=title,224 body=email_body,225 link_label=_("Send this article"))226 email_button += '</li>'227 return email_button228def __add_reddit_button(title, url):229 """230 adds a button for reddit (www.reddit.com) publishing and adds url and231 title automatically to the setup.232 """233 reddit_setup = '<script>reddit_url=\'%s\'</script>' % url234 reddit_setup += '<script>reddit_title=\'%s\'</script>' % title235 reddit_button = '<li id="reddit">%s%s</li>' % (reddit_setup,236 '<script language="javascript" src="http://reddit.com/button.js?t=1"></script>')237 return reddit_button238def __add_delicious_button(title, url):239 """240 Sends the link with title to del.icio.us (www.del.icio.us)241 """242 delicious_button = '<li id="delicious">'243 delicious_button += '<a href="http://del.icio.us/post?url=%s&title=%s" target="_blank">Post to del.icio.us</a>' % (url,244 title)245 delicious_button += '</li>'246 return delicious_button247def __add_digg_button(title, header):248 """249 provides the setup for the digg button look&feel aswell as automatically250 filled content.251 """252 digg_setup = '<script type="text/javascript">\n'253 digg_setup += 'digg_skin = \'compact\';\n'254 digg_setup += 'digg_window = \'new\';\n'255 digg_setup += 'digg_title = \'%s\';\n' % title256 digg_setup += 'digg_bodytext = \'%s\';\n' % header257 digg_setup += '</script>\n'258 digg_button = '<li id="digg">%s<script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script></li>' % digg_setup...
method.py
Source:method.py
1from page.studentPage import studentPage, log, Keys2import commons.page_elements as page_elements3import time4import random56# from lxml import etree789class Method(studentPage):10 '''æ¹æ³ç±»'''1112 def __init(self, live_id):13 studentPage.__init__(self, live_id)1415 def ansChoiceQ(self, rightAns="A", ansnum=4, isright=True, ishalfright=False):16 """ä½çéæ©é¢17 @rightAns æ£ç¡®çæ¡ str å¯ä¼ å¤ä½è¡¨ç¤ºå¤é 空表示为æ票é¢18 @ansnum çæ¡é项19 @isright æ¯å¦å
¨å¯¹20 @ishalfright æ¯å¦å对21 """22 ans = ["A", "B", "C", "D", "E", "F", "G", "H"]23 ans = ans[:ansnum]24 rightAns = rightAns.upper()25 if not self.is_elements_visibility(page_elements.vote.page_css, by="css"):26 log.info("æªåºç°éæ©é¢é¢æ¿")27 return28 ans_btn = page_elements.vote.ans_btn29 submit_btn = page_elements.vote.submit_btn30 close_btn = page_elements.vote.close_btn31 if not rightAns:32 anyAns = random.choice(ans)33 self.do_click(ans_btn.format(anyAns))34 elif len(rightAns) == 1:35 ans.remove(rightAns)36 wrongAns = random.choice(ans)37 if isright:38 self.do_click(ans_btn.format(rightAns))39 else:40 self.do_click(ans_btn.format(wrongAns))41 else:42 if isright:43 self.do_click(ans_btn.format(rightAns[0]))44 if not ishalfright:45 for i in rightAns[1:]:46 self.do_click(ans_btn.format(i))47 else:48 for i in rightAns:49 ans.remove(i)50 wrongAns = random.choice(ans)51 self.do_click(ans_btn.format(wrongAns))52 self.do_click(submit_btn)53 if self.is_elements_visibility(close_btn):54 self.do_click(close_btn)55 else:56 return5758 def ansVenusQ(self, rightAns="A", ansnum=4, isright=True, ishalfright=False):59 """ä½çVenusé¢60 @rightAns æ£ç¡®çæ¡ å¯ä¼ list/str list为å¤é¢ strå¯ä¼ å¤ä½è¡¨ç¤ºå¤é61 @ansnum çæ¡é项62 @isright æ¯å¦å
¨å¯¹63 @ishalfright æ¯å¦å对64 """65 if self.classType != 1:66 log.info("课åæä¸æ¯æ")67 return68 ans = ["A", "B", "C", "D", "E", "F", "G", "H"]69 ans = ans[:ansnum]70 rightAns = rightAns.upper()71 if not self.is_elements_visibility(page_elements.venus.page, by="css"):72 log.info("æªåºç°venusçé¢é¢æ¿")73 return74 ans_btn = page_elements.venus.ans_btn75 submit_btn = page_elements.venus.submit_btn76 close_btn = page_elements.venus.close_btn7778 def _doAns(rightAns, ans):79 if len(rightAns) == 1:80 ans.remove(rightAns)81 wrongAns = random.choice(ans)82 if isright:83 self.do_click(ans_btn.format(rightAns))84 else:85 self.do_click(ans_btn.format(wrongAns))86 else:87 if isright:88 self.do_click(ans_btn.format(rightAns[0]))89 if not ishalfright:90 for i in rightAns[1:]:91 self.do_click(ans_btn.format(i))92 else:93 for i in rightAns:94 ans.remove(i)95 wrongAns = random.choice(ans)96 self.do_click(ans_btn.format(wrongAns))97 self.do_click(submit_btn)98 time.sleep(3)99100 if isinstance(rightAns, str):101 _doAns(rightAns, ans)102 else:103 for index in rightAns:104 _doAns(index, ans)105 self.driver.switch_to.default_content()106 if self.is_elements_visibility(close_btn):107 self.do_click(close_btn)108 else:109 return110111 def ansAudioQ(self):112 """ä½çè¯é³é¢"""113 if self.is_elements_visibility(page_elements.audio.page):114 self.do_click(page_elements.audio.ans_btn, by="css")115 time.sleep(3)116 self.do_click(page_elements.audio.ans_btn, by="css")117 time.sleep(1)118 self.do_click(page_elements.audio.close_btn)119 else:120 log.info("æªåºç°è¯é³é¢çé¢é¢æ¿")121 return122123 def closeMVPbutton(self):124 """å
³éMVPå¼¹çª"""125 if self.is_elements_visibility(page_elements.vote.mvp_page):126 self.do_click(page_elements.vote.mvp_close_btn)127128 def sendChat(self, txt):129 """åéè天130 @txt ä¿¡æ¯str131 @classType 课ç¨ç±»å 1/2 ä¸åå±/å°ç课132 """133 num = 0 if self.classType == 2 else 1134 self.move_by_coordinate(50, 50)135 self.do_click(page_elements.chat.nomal_chat_label, num=num)136 self.input_text(txt, page_elements.chat.nomal_chat_label, num=num)137 self.input_text(138 Keys.ENTER, page_elements.chat.nomal_chat_label, nedclear=False, num=num)139140 @property141 def isfullScreen(self):142 if self.classType == 2:143 lable = self.find_element_test(page_elements.livetype.title)144 lable = lable.get_attribute("class")145 if lable == page_elements.livetype.smallclass_live_fullscreen:146 log.info("å½å为å
¨å±")147 return True148 else:149 log.info("å½å为éå
¨å±")150 return False151152 def toggleScreen(self):153 """åæ¢å
¨å±/éå
¨å±"""154 if self.classType == 2:155 if self.isfullScreen:156 self.move_by_coordinate(50, 50)157 self.do_click(page_elements.togglescreen.change_btn, by="css")158 log.info("åæ¢æå")159160 def openRankingList(self, ranklistType=1):161 """æå¼æè¡æ¦162 @ranklistType æå¼æµ·æ/çé¢æ¦ 1/2163 """164 if self.classType == 2:165 if self.isfullScreen:166 self.move_by_coordinate(50, 50)167 self.do_click(168 page_elements.rangkinglist.small_class_rank_btn, by="css")169 if ranklistType == 2:170 self.do_click(page_elements.rangkinglist.ans_rank_btn)171172 @property173 def hasChangeFrame(self):174 if self.classType == 2:175 if self.is_elements_visibility(page_elements.listencarefully.page, by="css"):176 self.do_click(page_elements.listencarefully.btn, by='css')177 return True178 return False179180 @property181 def isChatClose(self):182 """å
³éè天æé®ç¶æ"""183 if self.isfullScreen:184 self.move_by_coordinate(50, 50)185 if self.is_elements_exist(page_elements.chat.close_btn, by="css"):186 return False187 if self.is_elements_exist(page_elements.chat.open_btn, by="css"):188 return True189 log.info("æªæ¾å°æ§ä»¶")190191 def changeChatStatus(self):192 """æ¹åè天æé®ç¶æ"""193 if self.isChatClose:194 self.do_click(page_elements.chat.open_btn, by="css")195 log.info("å
³éè天æå")196 else:197 self.do_click(page_elements.chat.close_btn, by="css")198 log.info("æå¼è天æå")199200 def sendEmoticon(self, emoteType=1):201 """åé表æ
202 @emoteType 表æ
ç±»å 1/2/3/6 1/2/ok/666203 """204 dic = {1: "1", 2: "2", 3: "OK", 6: "666"}205 if self.classType == 2:206 if self.isfullScreen:207 self.move_by_coordinate(50, 50)208 self.do_click(page_elements.emotion.smallclass_emote_btn, by="css")209 body_html = self.find_element_test(210 page_elements.livetype.smallclass_body_center)211 body_html.find_element_by_css_selector(212 page_elements.emotion.container).find_element_by_xpath(page_elements.emotion.btn.format(dic[emoteType])).click()213214 def changeLines(self):215 """åæ¢çº¿è·¯"""216 if self.classType == 2:217 if self.isfullScreen:218 self.move_by_coordinate(50, 50)219 body_html = self.find_element_test(220 page_elements.livetype.smallclass_body_center)221 body_html.find_element_by_css_selector(222 page_elements.changelines.menu_btn).click()223 res = body_html.find_element_by_css_selector(224 page_elements.changelines.menu_ele)225 choiceline = res.find_element_by_css_selector(226 page_elements.changelines.choice_line).text227 log.info("å½å线路:" + choiceline)228 res1 = res.find_elements_by_xpath(229 page_elements.changelines.lines_xpath.format("线路"))230 Linelist = [i.text for i in res1 if i.text]231 log.info(Linelist)232 Linelist.remove(choiceline)233 changeline = random.choice(Linelist)234 log.info("åæ¢çº¿è·¯:" + changeline)235 res.find_element_by_xpath(236 page_elements.changelines.lines_xpath.format(changeline)).click()237238239if __name__ == "__main__":240 # 5f64227c4d04ca1e49f4055b ä¸åå±241 # 5f6960ad4d04ca1e49f4073b å°ç课242 stu = Method(live_id="5f714ee253ffbd39c9e6e10c")243 # num=input("请éæ©æ¬æ¬¡æ§è¡çå¦çæ°: ")244 num = 2245 num = int(num)246 stu.openstudentend(num)247 print("X" * 80)248 # stu.sendChat("123")249 # stu.sendEmoticon()250 # stu.ansVenusQ()251 # stu.toggleScreen()252 # time.sleep(1)253 # stu.isChatClose254 # stu.toggleScreen()
...
MongoDB_Store.py
Source:MongoDB_Store.py
1# coding: utf-823from pymongo import MongoClient4from openpyxl import load_workbook5import os, pprint, json678client = MongoClient()9db = client.standardDatabase1011def MongoDB_Store_Write(filepath):12 '''13 :filepath: absolute path of base data(".xlsx" or ".txt")14 '''15 for root, dir, files in os.walk(filepath):16 for filename in files:17 if ".txt" in filename:18 with open(root + "/" + filename, "r") as f:19 list_page_elements = []20 page_elements = [e.strip("\n") for e in f.readline().split(",")]21 for i in f.readlines():22 list_page_elements.append([j.strip("\n") for j in i.split(",")])23 for row in list_page_elements:24 dict_page_elements = {}25 for k,v in zip(page_elements,row):26 dict_page_elements[k]=float(v)27 post = {"standard_name":filename.split(",")[0],28 "pages":filename.split(",")[1],29 "page_title": filename.split(",")[2].rstrip(".txt"),30 "standard_data":dict_page_elements31 }32 db.standards.insert_one(post)33 elif ".xlsx" in filename:34 wb = load_workbook(root + "/" + filename)35 ws = wb.active36 list_page_elements = []37 for row in ws.iter_rows(min_row=1,max_row=1,values_only=True):38 page_elements = row39 for else_row in ws.iter_rows(min_row=2,values_only=True):40 list_page_elements.append(else_row)41 for row in list_page_elements:42 dict_page_elements = {}43 for k,v in zip(page_elements,row):44 dict_page_elements[k]=float(v)45 post = {"standard_name":filename.split(",")[0],46 "pages":filename.split(",")[1],47 "page_title": filename.split(",")[2].rstrip(".xlsx"),48 "standard_data":dict_page_elements49 }50 db.standards.insert_one(post)51 52def Json_Store_Write(filepath):53 '''54 :filepath: absolute path of base data(".xlsx" or ".txt")55 '''56 for root, dir, files in os.walk(filepath):57 for filename in files:58 if ".txt" in filename:59 list_page_elements = []60 with open(root + "/" + filename, "r") as f:61 page_elements = [e.strip("\n") for e in f.readline().split(",")]62 for i in f.readlines():63 list_page_elements.append([j.strip("\n") for j in i.split(",")])64 for row_content in list_page_elements:65 dict_page_elements = {}66 for k,v in zip(page_elements,row_content):67 dict_page_elements[k]=float(str(v).replace(" ",""))68 post = {"standard_name":filename.split(",")[0],69 "pages":filename.split(",")[1],70 "page_title": filename.split(",")[2].rstrip(".txt"),71 "standard_data":dict_page_elements72 }73 with open(root + "/" + "standarddata.json",'a+') as json_file:74 json.dump(post, json_file)75 elif ".xlsx" in filename:76 wb = load_workbook(root + "/" + filename)77 ws = wb.active78 list_page_elements = []79 for row in ws.iter_rows(min_row=1,max_row=1,values_only=True):80 page_elements = row81 for else_row in ws.iter_rows(min_row=2,values_only=True):82 list_page_elements.append(else_row)83 for row in list_page_elements:84 dict_page_elements = {}85 for k,v in zip(page_elements,row):86 dict_page_elements[k]=float(str(v).replace(" ",""))87 post = {"standard_name":filename.split(",")[0],88 "pages":filename.split(",")[1],89 "page_title": filename.split(",")[2].rstrip(".xlsx"),90 "standard_data":dict_page_elements91 }92 with open(root + "/" + "standarddata.json",'a+') as json_file:93 json.dump(post, json_file)949596if __name__ == "__main__":97 filepath = input("请è¾å
¥åå§æ°æ®æ件ç»å¯¹è·¯å¾: ")
...
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!