Best Python code snippet using yandex-tank
pyshell
Source:pyshell
1#! /usr/bin/env python32# -*- coding: utf8 -*-3import argparse4import os5import os.path6import yaml7from enum import Enum8import sys9import io10class NormalColor(Enum):11 black = 012 red = 113 green = 214 yellow = 315 blue = 416 magenta = 517 cyan = 618 white = 719class BrightColor(Enum):20 black = 021 red = 122 green = 223 yellow = 324 blue = 425 magenta = 526 cyan = 627 white = 728ANSI_RESET = '\033[0m'29ANSI_BOLD = '\033[01m'30ANSI_UNDERLINE = '\033[04m'31ANSI_STRIKETHROUGH = '\033[09m'32CONFIGFILE = "~/.pyshell/config.yaml"33ENV = {}34DEFAULTENV = {}35stdout, stderr, stdwarn = [io.StringIO()]*336class InputStream:37 def __init__(self, init=''):38 self.buffer = init.split('\n')39 def write(self, text):40 self.buffer += text.split('\n')41 def readline(self):42 try:43 value, *self.buffer = self.buffer44 except:45 return input()46 return value47 def read(self, length=0):48 if not length:49 value, self.buffer = self.buffer, ''50 return value51 else:52 value, self.buffer = self.buffer[:length], self.buffer[length:]53 return value54def fmtcols(mylist, cols):55 maxwidth = max(map(lambda x: len(x), mylist))56 justifyList = list(map(lambda x: x.ljust(maxwidth), mylist))57 lines = (' '.join(justifyList[i:i+cols]) 58 for i in range(0,len(justifyList),cols))59 return '\n'.join(lines)60stdin = InputStream()61def cd(directory):62 try:63 os.chdir(path(directory))64 except FileNotFoundError:65 err("%s does not exist!" % directory)66 except PermissionError:67 err("You do not have permission to access %s!" % directory)68 except NotADirectoryError:69 err("%s is not a directory!" % directory)70def echo(text):71 out(text)72def println(text, *args):73 out(text % args)74def ls(directory=None):75 if directory is None:76 directory = os.getcwd()77 try:78 out(fmtcols(sorted(os.listdir(directory) + ['.','..']),CONFIG.get('default_columns',2)))79 except FileNotFoundError:80 err("%s does not exist!" % directory)81 except PermissionError:82 err("You do not have permission to access %s!" % directory)83 except NotADirectoryError:84 err("%s is not a directory!" % directory)85 86def cwd():87 out(os.getcwd())88BUILTINS = {89 'cd': cd,90 'echo': echo,91 'println': println,92 'exit': sys.exit,93 'ls': ls,94 'cwd': cwd95}96def out(text, **kwargs):97 print(text, **kwargs)98 stdout.write(text)99def err(text):100 print(text, fg=BrightColor.red, bold=True)101 stderr.write(text)102def warn(text):103 print(text, fg=BrightColor.yellow, bold=True)104 stdwarn.write(text)105def format_ansi(text,fg=None,bg=None,bold=False,underline=False,strikethrough=False):106 if fg is None:107 fg = config_to_color("fg_color")108 if bg is None:109 bg = config_to_color("bg_color")110 pre = color_to_ansi(fg) + color_to_ansi(fg)111 if bold:112 pre += ANSI_BOLD113 if underline:114 pre += ANSI_UNDERLINE115 if strikethrough:116 pre += ANSI_STRIKETHROUGH117 return pre + text + ANSI_RESET118print_def = print119print = lambda *args, fg=None, bg=None, bold=False, underline=False, strikethrough=False, **kwargs: print_def(format_ansi(' '.join(map(str,args)),120 fg=fg,bg=bg,bold=bold,underline=underline,strikethrough=strikethrough),**kwargs)121def color_to_ansi(color,fg=True):122 if fg and isinstance(color,NormalColor):123 return '\033[3%sm' % color.value124 elif not fg and isinstance(color,NormalColor):125 return '\033[4%sm' % color.value126 elif fg and isinstance(color,BrightColor):127 return '\033[9%sm' % color.value128 elif not fg and isinstnace(color,BrightColor):129 return '\033[10%sm' % color.value130def config_to_color(name):131 c = CONFIG[name]132 if c['bright'] == True:133 return BrightColor[c['color']]134 else:135 return NormalColor[c['color']]136def color_to_config(name,color):137 if isinstance(color,BrightColor):138 CONFIG[name] = {'bright': True, 'color': color.value}139 else:140 CONFIG[name] = {'bright': False, 'color': color.value}141def call(options, stdin):142 process = subprocess.run(options,stdin=stdin)143 return process.stdout, process.stderr144def path(path_):145 return os.path.abspath(os.path.expanduser(path_))146def load_config():147 if not os.path.isdir(os.path.dirname(path(CONFIGFILE))):148 os.mkdir(os.path.dirname(path(CONFIGFILE)))149 if not os.path.isfile(path(CONFIGFILE)):150 with open(path(CONFIGFILE),"w") as f:151 f.write(yaml.dump({}))152 with open(path(CONFIGFILE),"r") as f:153 global CONFIG154 CONFIG = yaml.load(f.read())155def save_config():156 with open(os.path.abspath(CONFIGFILE),"w") as f:157 global CONFIG158 f.write(yaml.dump(CONFIG))159def load_env():160 try:161 with open(path(CONFIG['env_file']),'r') as f:162 ENV = yaml.load(f.read())163 except IOError:164 warn("Warning: ENV file does not exist! Writing default ENV variables to file.")165 ENV = DEFAULTENV166 if not os.path.isdir(os.path.dirname(path(CONFIG['env_file']))):167 os.mkdir(os.path.dirname(path(CONFIG['env_file'])))168 with open(path(CONFIG['env_file']),'w') as f:169 f.write(yaml.dump(ENV))170def save_env():171 if not os.path.isdir(os.path.dirname(path(CONFIG['env_file']))):172 os.mkdir(os.path.dirname(path(CONFIG['env_file'])))173 with open(path(CONFIG['env_file']),'w') as f:174 f.write(yaml.dump(ENV))175def split(text, sep, with_escape=True):176 results = []177 curtok = ''178 while len(text):179 char, *text = text180 if char == '\\' and with_escape:181 char, *text = text182 curtok += char183 continue184 elif char in ("'",'"'):185 term = char186 char, *text = text187 if curtok != '':188 results.append(curtok)189 curtok = ''190 while char != term:191 curtok += char192 char, *text = text193 results.append(curtok)194 curtok = ''195 continue196 elif char == sep:197 if curtok != '':198 results.append(curtok)199 curtok = ''200 else:201 curtok += char202 if curtok != '':203 results.append(curtok)204 return results205def username():206 return os.path.split(path("~"))[-1]207def userhome():208 return path("~")209def dynprompt():210 return "("+format_ansi(username(),fg=BrightColor.yellow)+") "+format_ansi(os.getcwd().replace(userhome(),'~'),fg=BrightColor.green)+" >>> "211def sys_command(command, args):212 raise NotImplemented213def execute(command, args):214 if command in BUILTINS:215 BUILTINS[command](*args)216 elif command in DEFINED_FUNCS:217 DEFINED_FUNCS[command](*args)218 else:219 sys_command(command, args)220def do_command():221 command = input(CONFIG.get('prompt',False) or dynprompt())222 command = split(command, CONFIG.get('seperator',False) or ' ', with_escape=CONFIG.get('escaping',False))223 try:224 command, *args = command225 if isinstance(args, str):226 args = (args,)227 except: args = tuple()228 execute(command, args)229def main():230 load_config()231 load_env()232 while True:233 do_command()234 return 0235if __name__ == "__main__":...
data_save.py
Source:data_save.py
1import pandas as pd2import sqlite33import json4import time5# from django.conf import settings6def addEscapeSequences(mystr):7 with_escape = ""8 for pos in range(0, len(mystr)):9 if(mystr[pos] == "'"):10 with_escape = with_escape+"\\"11 with_escape += mystr[pos]12 return with_escape13dataset = pd.read_csv(14 'C:\\Users\\17323\Desktop\Vrundan\SDP Project\MovieRecommendationApp\\MovieOperations\\today1_dataset.csv', encoding="utf-8")15df = pd.DataFrame(dataset)16conn = sqlite3.connect(17 'C:\\Users\\17323\Desktop\Vrundan\SDP Project\MovieRecommendationApp\\db.sqlite3')18cursor = conn.cursor()19start = time.time_ns()20for i, j in df.iterrows():21 # print(i,j['production_companies'])22 # production_companies_json = json.loads(j['production_companies'])23 # production_companies_string = ""24 # for k in range(0, len(production_companies_json)):25 # production_companies_string += production_companies_json[k]['name']+" "26 # print(production_companies_string)27 print(i)28 # insert_query = "insert into MovieOperations_movie(movieTitle,movieDescription,movieKeywords,movieCast,movieDirector,movieProduction,movieRuntime,movieGenre,movieTagline,movieRating) VALUES ('" + addEscapeSequences(j['original_title'])+"','"+addEscapeSequences(j['overview'])+"','"+addEscapeSequences(j['keywords'])+"','"+addEscapeSequences(j['cast'])+"','"+addEscapeSequences(j['director'])+"','" + addEscapeSequences(production_companies_string)+"','"+addEscapeSequences(str(j['runtime']))+"','"+addEscapeSequences(j['genres'])+"','"+addEscapeSequences(j['tagline'])+"','"+"10"+"')"29 # insert_query = "insert into MovieOperations_movie(movieTitle,movieDescription,movieKeywords,movieCast,movieDirector,movieProduction,movieRuntime,movieGenre,movieTagline,movieRating) VALUES ('" + (j['original_title'])+"','"+(j['overview'])+"','"+(j['keywords'])+"','"+(j['cast'])+"','"+(j['director'])+"','" + (production_companies_string)+"','"+(str(j['runtime']))+"','"+(j['genres'])+"','"+(j['tagline'])+"','"+"10"+"')"30 # print(insert_query)31 # print()32 # insert_query1=""33 # for l in range(0,len(insert_query)):34 # if(insert_query[l]=='"' or insert_query[l]=="'"):35 # insert_query1=insert_query1+'\\'36 # insert_query1+=insert_query[l]37 # print(insert_query1)38 # insert_query = "insert into MovieOperations_movie(movieTitle,movieDescription,movieKeywords,movieCast,movieDirector,movieProduction,movieRuntime,movieGenre,movieTagline,movieRating) VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')"39 # (j['original_title'], j['overview'], j['keywords'], j['cast'], j['director'], production_companies_string, str(j['runtime']), j['genres'], j['tagline'], "10")40 # if(i == 36 or i == 37 or i == 58):41 # continue42 # conn.execute(insert_query)43 # cursor.execute(insert_query, (j['original_title'], j['overview'], j['keywords'], j['cast'],j['director'], production_companies_string, str(j['runtime']), j['genres'], j['tagline'], "10"))44 # insert_query="""INSERT INTO MovieOperations_movie(movieTitle,movieDescription,movieKeywords,movieCast,movieDirector,movieProduction,movieRuntime,movieGenre,movieTagline,movieRating,moviePoster) VALUES (?,?,?,?,?,?,?,?,?,?,?)"""45 # movieTitle=j['movieTitle']46 # movieDescription=j['movieDescription']47 # movieKeywords=j['movieKeywords']48 # movieCast=j['movieCast']49 # movieDirector=j['movieDirector']50 # movieProduction=j['movieProduction']51 # movieRuntime=str(j['movieRuntime'])52 # movieGenre=j['movieGenre']53 # movieTagline=j['movieTagline']54 # movieRating="10"55 # moviePoster = j['movieCover']56 # data_tuple=(movieTitle,movieDescription,movieKeywords,movieCast,movieDirector,movieProduction,movieRuntime,movieGenre,movieTagline,movieRating,moviePoster)57 # cursor.execute(insert_query,data_tuple)58 update_query = """Update MovieOperations_movie SET ratecount = ? where movieId = ? """59 movieRating = 160 movieId = j['movieId']61 data_tuple = (movieRating, movieId)62 cursor.execute(update_query, data_tuple)63conn.commit()64end = time.time_ns()...
3.escape.py
Source:3.escape.py
...4def index():5 return '<h1>Hello World!</h1>'6# 使ç¨escape()æHTMLèªæ³ï¼HTMLæ¨ç±¤ä¸æ被ç覽å¨è§£æ7@app.route('/escape')8def with_escape():9 return escape('<h1>With escape()</h1>')10 # return "<h1>Not with escape()</h1>"11 12# æ²æ使ç¨escape()ï¼HTMLæ¨ç±¤æ被ç覽å¨è§£æï¼é¤éå ä¸HTMLèªæ³13@app.route('/not_escape')14def not_with_escape():15 return '<h1>Not With escape()</h1>'16# debug=True(éç¼é段ææç¨ï¼æ£å¼Web Appä¸ææédebug mode)17# 1.æå¨åºç¾é¯èª¤æï¼è®ç¨å¼ç¢¼é¯èª¤è¨æ¯é¡¯ç¤ºå¨ç¶²é ä¸ï¼èä¸æ¯é¡¯ç¤ºç¶²é é¯èª¤çè¨æ¯18# 2.ä¿®æ¹ç¨å¼ç¢¼é æ網é ç°åæï¼æèªåéæ°ååWeb Appï¼èä¸ç¨éæ°æåééååå19if __name__ == '__main__':...
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!!