Best Python code snippet using autotest_python
basic_func.py
Source:basic_func.py
1import time2from blinkt import set_clear_on_exit, clear, set_all, show, set_pixel3import status4from functools import wraps5LED_MIN = 06LED_MAX = 77# Blinkt highest and lowest lights8# Length of time in seconds to sleep between status checks9SLEEP_TIME = 0.110# User-callable functions get added to this dict using @expose decorator below11EXPOSED_FUNCTION_DICT = {}12set_clear_on_exit(False)13def expose(f):14 """Decorator used to select which functions can be called"""15 @wraps(f)16 def wrapper(*args, **kwds):17 return f(*args, **kwds)18 EXPOSED_FUNCTION_DICT[f.__name__] = f19 return wrapper20class StatusChangedException(Exception):21 """Raised when status changes during sleep state"""22 pass23def custom_sleep(duration, current_status):24 """custom_sleep to allow to check for change in status while sleeping"""25 count = int(duration / SLEEP_TIME)26 for x in range(0, count + 1):27 time.sleep(SLEEP_TIME)28 new_status = status.get_status(current_status)29 if new_status != current_status:30 raise StatusChangedException(new_status)31def single_led(current_led, r, g, b, brightness):32 """Set color of singe led - base function"""33 if current_led < LED_MIN or current_led > LED_MAX:34 # Check to see if selected light actually exists on Blinkt35 return False36 set_pixel(current_led, r, g, b, brightness)37def trace(current_led, r, g, b, direction):38 """Backwards and forwards animation of lights"""39 clear()40 if direction == "forwards":41 # Three lights on at once, front light is brighter than back light42 single_led(current_led, r, g, b, 0.1)43 single_led(current_led - 1, r, g, b, 0.5)44 single_led(current_led - 2, r, g, b, 1)45 else:46 # Inverts the direction of the three lights47 single_led(current_led, r, g, b, 1)48 single_led(current_led + 1, r, g, b, 0.5)49 single_led(current_led + 2, r, g, b, 0.1)50 show()51def led_line(interval, brightness, led, r, g, b, current_status):52 """Cause the lights to travel in a line53and have brightness close to the normal distribution."""54 if led == 0 or led == 7:55 clear()56 set_pixel(led, r, g, b, (brightness / 20.0))57 show()58 custom_sleep(interval, current_status)59 elif led == 1 or led == 6:60 clear()61 set_pixel(led, r, g, b, (brightness / 10.0))62 show()63 custom_sleep(interval, current_status)64 elif led == 2 or led == 5:65 clear()66 set_pixel(led, r, g, b, (brightness / 5.0))67 show()68 custom_sleep(interval, current_status)69 elif led == 3 or led == 4:70 clear()71 set_pixel(led, r, g, b, brightness)72 show()73 custom_sleep(interval, current_status)74def flashing(r, g, b, number_of_flashes, time_gap, current_status):75 """Make lights to flash"""76 for x in range(number_of_flashes):77 set_all(r, g, b, 1)78 show()79 custom_sleep(time_gap, current_status)80 clear()81 show()82 custom_sleep(time_gap / 1.3, current_status)83def solid_colour(r, g, b, current_status):84 """Show a solid_colour beginning with LED_line animation"""85 custom_sleep(1, current_status)86 for x in range(8):87 led_line(0.08, 1.0, x, r, g, b, current_status)88 for x in range(7, -1, -1):89 led_line(0.08, 1.0, x, r, g, b, current_status)90 clear()91 set_all(r, g, b, 1.0)92 show()93def animation(r, g, b, current_status):94 """Coherent backwards and forwards animation using trace function"""95 custom_sleep(0.5, current_status)96 while True:97 for x in range(-2, 10):98 trace(x, r, g, b, "forwards")99 custom_sleep(0.25, current_status)100 for x in range(7, -3, -1):101 trace(x, r, g, b, "backwards")102 custom_sleep(0.25, current_status)103 flashing(r, g, b, 2, 0.5, current_status)104 set_all(r, g, b, 1)105 show()106 custom_sleep(1.5, current_status)107 clear()108 show()109def custom_alert(r, g, b, current_status):110 """Consistent pulse"""111 clear()112 brightness = 0.0113 direction = True114 running = True115 while running:116 if direction:117 brightness += 0.1118 if brightness >= 0.9:119 direction = False120 else:121 if brightness > 0.15:122 brightness -= 0.1123 else:124 brightness = 0.0125 if brightness <= 0.000001:126 direction = True127 set_all(r, g, b, brightness)128 show()129 if brightness == 0.0:130 custom_sleep(0.3, current_status)131 elif brightness >= 0.9:132 custom_sleep(0.3, current_status)133 else:134 custom_sleep(0.05, current_status)135def get_exposed_function_names():136 return EXPOSED_FUNCTION_DICT.keys()137def is_exposed(unknown_status):138 return unknown_status in EXPOSED_FUNCTION_DICT139def show_status(new_status):140 """Respond to a status"""141 if not is_exposed(new_status):142 raise Exception("Invalid status: {}".format(new_status))143 print("New status: " + new_status)144 # !MAGIC HAPPENS HERE!145 EXPOSED_FUNCTION_DICT[new_status](new_status)146def status_loop(default):147 """Constantly check to see if status has changed"""148 current_status = status.get_status(default)149 new_status = current_status150 while True:151 try:152 if new_status:153 current_status = new_status154 new_status = None155 show_status(current_status)156 custom_sleep(1, current_status)157 except StatusChangedException as e:158 print159 e.message160 new_status = e.message161 except Exception as e:162 print(e)163def callable_statuses():164 callable_statuses_list = []165 for item in EXPOSED_FUNCTION_DICT:166 callable_statuses_list.append(item)...
api_status_view.py
Source:api_status_view.py
1# encoding: utf-82import json3import datetime4import string5from flask import request, g, jsonify6from flask.ext.security import login_required7from myapp.models import User, WeiboList8from myapp import app, db9from myapp.api_app import api_app10from weibo import APIClient11client = APIClient(app_key=app.config['APP_KEY'],12 app_secret=app.config['APP_SECRET'],13 redirect_uri=app.config['CALLBACK_URL'])14@api_app.route('/status/total-number')15@login_required16def get_status_total_number():17 token = json.loads(g.user.token)18 client.set_access_token(token['access_token'], token['expires'])19 statuses = client.statuses.user_timeline.get(count=10, page=1)20 results = {'total_number': statuses['total_number'],21 'count': 100}22 error_results = {'request':'/status/total-number',23 'error_code':-1,24 'error':'error'}25 return jsonify(results)26@api_app.route('/status/update')27@login_required28def update_status():29 page_no = int(request.args.get('page', '1'))30 if page_no < 1:31 page_no = 132 count_per_page = int(request.args.get('count', '80'))33 if count_per_page > 100:34 count_per_page = 10035 user = g.user36 token = json.loads(g.user.token)37 current_user = User.query.filter_by(uid=user.uid).first()38 client.set_access_token(token['access_token'], token['expires'])39 weibo_results = client.statuses.user_timeline.get(count=count_per_page, page=page_no)40 statuses = weibo_results['statuses']41 for status in statuses:42 current_status = WeiboList.query.filter_by(uid=status['id']).first()43 if current_status is None:44 #print "Creating status"45 current_status = WeiboList()46 current_status.uid = status['id']47 current_status.user_uid = status['user']['id']48 current_status.create_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")49 current_status.update_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")50 current_status.status_type = -151 current_status.status_id = status['id']52 created_at = datetime.datetime.strptime(string.replace(status['created_at'], "+0800 ", ""),53 '%a %b %d %H:%M:%S %Y')54 current_status.created_at = created_at.strftime("%Y-%m-%d %H:%M:%S")55 current_status.source = status['source'].encode("utf-8")56 current_status.original_pic = status.get('original_pic', '')57 current_status.bmiddle_pic = status.get('bmiddle_pic', '')58 current_status.thumbnail_pic = status.get('thumbnail_pic', '')59 current_status.geo = json.dumps(status['geo'])60 current_status.retweeted_status = json.dumps(status.get('retweeted_status', ''),61 ensure_ascii=False)62 current_status.reposts_count = status['reposts_count']63 current_status.comments_count = status['comments_count']64 current_status.attitudes_count = status['attitudes_count']65 current_status.visible_type = status['visible'].type66 current_status.pic_urls = json.dumps(status['pic_urls'])67 db.session.add(current_status)68 else:69 #print "Status has been created"70 current_status.update_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")71 current_status.status_type = -172 current_status.original_pic = status.get('original_pic', '')73 current_status.bmiddle_pic = status.get('bmiddle_pic', '')74 current_status.thumbnail_pic = status.get('thumbnail_pic', '')75 current_status.geo = json.dumps(status['geo'])76 current_status.retweeted_status = json.dumps(status.get('retweeted_status', ''),77 ensure_ascii=False)78 current_status.reposts_count = status['reposts_count']79 current_status.comments_count = status['comments_count']80 current_status.attitudes_count = status['attitudes_count']81 current_status.visible_type = status['visible'].type82 current_status.pic_urls = json.dumps(status['pic_urls'])83 current_user.update_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")84 db.session.commit()85 results = {"count": count_per_page,86 "page": page_no,87 "max_id": statuses[0]['id'],88 "since_id": statuses[len(statuses)-1]['id'],89 'total_number': weibo_results['total_number']}...
demo.py
Source:demo.py
1import basic_func2import status3from blinkt import clear, show4import random5@basic_func.expose6def partying(current_status):7 """Lights randomly appear with random colours"""8 previous_led = 89 # Party forever...10 while True:11 for x in range(2):12 led = random.randint(0, 7)13 red = random.randint(0, 255)14 green = random.randint(0, 255)15 blue = random.randint(0, 255)16 while previous_led == led:17 led = random.randint(0, 7)18 basic_func.single_led(led, red, green, blue, 0.5)19 show()20 clear()21 basic_func.custom_sleep(0.05, current_status)22 basic_func.trace(led, red, green, blue, 'forward')23 basic_func.flashing(red, green, blue, 2, 0.1, current_status)24 clear()25@basic_func.expose26def alert(current_status):27 basic_func.custom_alert(255, 0, 0, current_status)28@basic_func.expose29def available(current_status):30 basic_func.solid_colour(0, 255, 0, current_status)31@basic_func.expose32def busy(current_status):33 basic_func.solid_colour(255, 62, 0, current_status)34@basic_func.expose35def disturbable(current_status):36 basic_func.solid_colour(199, 234, 70, current_status)37@basic_func.expose38def brb(current_status):39 basic_func.animation(255, 62, 0, current_status)40@basic_func.expose41def engaged(current_status):42 '''Shows three LEDs moving along'''43 # can't change status if this is selected -- FIXED44 while True:45 for current_led in range(0, 8):46 basic_func.trace(current_led, 0, 0, 255, "forwards")47 # checks for new status48 basic_func.custom_sleep(0.5, current_status)49 # could make it so the bar fills up gradually50@basic_func.expose51def offline(current_status):52 clear()53 basic_func.set_all(0, 0, 0, 0)54 show()55if __name__ == "__main__":56 status.set_statuses(basic_func.callable_statuses())57 status.set_type('blinkt')...
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!!