How to use print_fails method in stestr

Best Python code snippet using stestr_python

hopper.py

Source:hopper.py Github

copy

Full Screen

1import numpy as np2import random3import queue4import math5from scipy.integrate import ode, odeint6### LOW LEVEL ROBOT FUNCTIONS ###7class Constants:8 def __init__(self, config = None):9 if config is None:10 # self.k = 2800 # Spring Constant, N/m11 self.L = 0.5 # length of leg in flight12 self.Lf = 0.3 # length of unsprung part of leg13 self.g = -9.814 self.m = 7 # kg15 self.k = 320016 self.u = 117 self.Lk0 = 0.2 # length of uncompressed spring18 self.Cd = 0.519 self.eps = 1e-220 else:21 self.L = config["L"]22 self.Lf = config["Lf"]23 self.Lk0 = config["Lk0"]24 self.g = config["g"]25 self.m = config["m"]26 self.k = config["k"]27 self.Cd = config["Cd"]28 self.eps = config["eps"]29 self.u = 1 # deprecated, now friction is part of the heightmap30class CassieConstants:31 def __init__(self):32 self.L = 0.7 # length of leg in flight33 self.Lf = 0.5 # length of unsprung part of leg34 self.g = -9.835 self.m = 10 # kg, torso mass36 self.k = 4000 # seems like a decent approximation to Cassie's urdf? 37 self.u = 1 # friction (material-dependent)38 self.Lk0 = 0.2 # length of uncompressed spring39 self.eps = 1e-240def sample_terrain_func(x):41 terrain_disc = {0:0, 0.3:0, 0.6:0.1, 0.9:0.2, 1.2:-0.5, 1.5:0.3, 1.8:0.3, 2.1:0.2, 2.4:0.3, 2.7: 0, 3.0: 0.2}42 tmp = round(x, 2) * 10043 tmp = (tmp + (30 - tmp % 30))/10044# discretized to 30 cm steps"45 if tmp < 0 or tmp >= 3.3:46 return 047 return terrain_disc[tmp]48def default_terrain_func(x):49 return 050'''51flight state vector:52 x[0]: CoM x (m)53 x[1]: CoM y (m)54 x[2]: CoM x velocity (m/s)55 x[3]: CoM y velocity (m/s)56 x[4]: angular velocity (rad/s)57 x[5]: leg angle wrt negative x-axis58'''59def flightStep(x, u, tstep):60 com_x_next = x[0] + tstep * x[2]61 com_y_next = x[1] + tstep * x[3] + 0.5*constants.g*(tstep**2)62 x_vel_next = x[2] # x velocity does not change in flight63 y_vel_next = x[3] + constants.g * tstep # y velocity decreases by acceleration, which is g64 w_next = x[4]65 foot_angle_next = u66 x_next = [com_x_next, com_y_next, x_vel_next, y_vel_next, w_next, foot_angle_next]67 return x_next68# calculates leg angle as a function of the current flight state and desired CoM velocity69def legAnglePControl(x_flight, x_vel_des, k, Kp, tst = 0.18):70 x_vel_cur = x_flight[2]71 xs_dot = k*(x_vel_cur + x_vel_des)/272 # xs_dot = (x_vel_cur + x_vel_des)/273 leg_fd = - (xs_dot * tst)/2 + Kp * (x_vel_des - x_vel_cur)74 leg_angle = np.arccos(leg_fd/constants.L)75 return leg_angle76### SIMULATION UTILITIES ###77sim_codes = {"SUCCESS":0, "SPRING_BOTTOM_OUT":-1, "FRICTION_CONE":-2, "A*_NO_PATH":-3, "BODY_CRASH":-4, "FOOT_CRASH":-5, "TOO_MANY_STEPS":-6}78sim_codes_rev = dict(map(reversed, sim_codes.items()))79constants = Constants()80# Wrapper class for low level functions 81class Hopper:82 def __init__(self, constants):83 self.constants = constants84 85 def flightToStance(self, x):86 Lb_init = self.constants.L87 # x_diff = x[0] - foot_pos[0]88 # y_diff = x[1] - foot_pos[1]89 # Lb_init = np.sqrt(x_diff**2 + y_diff**2)90 a_init = x[5] 91 a_d_init = (-np.sin(a_init) * x[2] + np.cos(a_init) * x[3])/Lb_init92 Lb_d_init = np.cos(a_init) * x[2] + np.sin(a_init) * x[3]93 stance_vec = [a_init, a_d_init, Lb_init, Lb_d_init]94 # print("converted stance energy", stancePhaseEnergy(stance_vec))95 return stance_vec96 # converts final stance state to initial flight state on takeoff97 def stanceToFlight(self, x_stance, foot_pos):98 # print("input stance energy", stancePhaseEnergy(x_stance))99 xb = foot_pos[0] + np.cos(x_stance[0]) * x_stance[2]100 yb = foot_pos[1] + np.sin(x_stance[0]) * x_stance[2]101 xb_d = np.cos(x_stance[0]) * x_stance[3] - np.sin(x_stance[0]) * x_stance[1] * x_stance[2]102 yb_d = np.sin(x_stance[0]) * x_stance[3] + np.cos(x_stance[0]) * x_stance[1] * x_stance[2]103 flight_vec = [xb, yb, xb_d, yb_d, 0, x_stance[0]]104 # print("converted flight energy:", flightPhaseEnergy(flight_vec))105 return flight_vec106 def flightDynamics(self, t, x):107 derivs = [x[2], x[3], 0, 0, 0, 0]108 derivs[2] = 0109 derivs[3] = constants.g110 return derivs111 def stanceDynamics(self, t, x):112 a = x[0]113 a_d = x[1]114 Lb = x[2]115 Lb_d = x[3]116 derivs = [a_d, 0, Lb_d, 0]117 a_dd = (-2 * Lb_d * a_d - np.abs(constants.g) * np.cos(a))/Lb118 Lb_dd = -constants.k/constants.m * (Lb - constants.Lf - constants.Lk0) - np.abs(constants.g) * np.sin(a) + Lb*(a_d**2)119 derivs[1] = a_dd120 derivs[3] = Lb_dd121 return derivs122 '''123 Makes sure we are within friction cone bounds and spring hasn't bottomed-out.124 '''125 def checkStanceFailure(self, x_stance, foot_pos,126 terrain_func, terrain_normal_func=None,127 u = None, debug = True):128 if x_stance[2] < self.constants.Lf - 0.05:129 if debug:130 print("Spring bottom-ed out:", x_stance[2])131 return sim_codes["SPRING_BOTTOM_OUT"]132 133 if terrain_normal_func is not None and u is not None:134 normal = terrain_normal_func(foot_pos[0])135 forward_limit = normal - np.arctan(u)136 rear_limit = normal + np.arctan(u)137 if x_stance[0] < forward_limit:138 if debug:139 print("Forward Friction cone violation!: leg_angle", x_stance[0], "limit = ", forward_limit)140 return sim_codes["FRICTION_CONE"]141 if x_stance[0] > rear_limit:142 if debug:143 print("Rear Friction cone violation!: leg_angle", x_stance[0], "limit = ", rear_limit)144 return sim_codes["FRICTION_CONE"]145 body_pos = self.getBodyXYInStance(x_stance, foot_pos)146 147 # This indicates a collision with a wall148 if terrain_func(body_pos[0]) > body_pos[1]:149 if debug:150 print("Collision with wall in stance! Body y", body_pos[1], " < terrain y", terrain_func(body_pos[0]))151 return sim_codes["BODY_CRASH"]152 return sim_codes["SUCCESS"]153 '''154 Checks if the body or foot collides with any terrain features155 - terrain_func is a function that maps x coord to y coord156 '''157 def checkFlightCollision(self, x_flight, terrain_func, debug = False):158 body_x = x_flight[0]159 body_y = x_flight[1]160 foot_pos = self.getFootXYInFlight(x_flight)161 if terrain_func(body_x) > body_y:162 if debug:163 print("body collision in flight phase!")164 print("For body y = ", body_y, "terrain y", terrain_func(body_x))165 return sim_codes["BODY_CRASH"]166 elif terrain_func(foot_pos[0]) > foot_pos[1] + 0.05:167 if debug:168 print("foot collision in flight phase! x = ", foot_pos[0], "y = ", foot_pos[1])169 return sim_codes["FOOT_CRASH"]170 return sim_codes["SUCCESS"]171 def getFootXYInFlight(self, x_flight):172 a = x_flight[5]173 body_x = x_flight[0]174 body_y = x_flight[1]175 foot_x = body_x - np.cos(a) * self.constants.L176 foot_y = body_y - np.sin(a) * self.constants.L177 return [foot_x, foot_y]178 def getBodyXYInStance(self, x_stance, foot_pos):179 a = x_stance[0]180 Lb = x_stance[2]181 x_b = foot_pos[0] + np.cos(a) * Lb182 y_b = foot_pos[1] + np.sin(a) * Lb183 return [x_b, y_b]184 def simulateOneStancePhase(self, x_flight, tstep = 0.01, terrain_func = default_terrain_func, 185 print_fails = True, terrain_normal_func = None, friction = None):186 x0_stance = self.flightToStance(x_flight)187 foot_pos = self.getFootXYInFlight(x_flight)188 integrator = ode(self.stanceDynamics)189 integrator.set_initial_value(x0_stance, 0)190 code = sim_codes["SUCCESS"]191 stance_states = [x0_stance]192 success = True193 while integrator.successful():194 integrator.integrate(integrator.t + tstep)195 # print("stance energy:", getStanceEnergy(integrator.y))196 stance_states.append(integrator.y)197 if integrator.y[2] >= self.constants.L:198 break199 code = self.checkStanceFailure(integrator.y,200 foot_pos,201 terrain_func,202 debug = print_fails,203 terrain_normal_func = terrain_normal_func,204 u = friction)205 if code < 0:206 break207 return code, stance_states, integrator.t208 def simulateOneFlightPhaseODE(self, 209 x_stance, 210 foot_pos = None, 211 x_init = None, 212 debug = False, 213 u = np.pi/2, 214 tstep = 0.01, 215 terrain_func = default_terrain_func,216 till_apex = False,217 print_fails = True,218 hit_apex = False):219 if debug:220 x0_flight = x_init221 else:222 x0_flight = self.stanceToFlight(x_stance, foot_pos)223 foot_angle_next = u224 flight_states = [x0_flight]225 integrator = ode(self.flightDynamics)226 integrator.set_initial_value(x0_flight, 0)227 ret_val = sim_codes["SUCCESS"]228 cond = False229 success = True230 while integrator.successful():231 x = integrator.integrate(integrator.t + tstep)232 state = integrator.y233 # ke = 0.5 * constants.m * (state[2]**2 + state[3]**2)234 # pe = constants.m * np.abs(constants.g) * state[1]235 # print("flight energy:", ke + pe)236 if integrator.y[3] <= 0 and flight_states[len(flight_states)-1][3] >= 0:237 hit_apex = True238 if till_apex:239 flight_states.append(integrator.y)240 return sim_codes["SUCCESS"], flight_states, integrator.t241 cur_state = integrator.y242 if hit_apex:243 cur_state[5] = foot_angle_next244 cond = True245 flight_states.append(cur_state)246 foot_pos = self.getFootXYInFlight(cur_state)247 if cond and foot_pos[1] <= terrain_func(foot_pos[0]):248 if terrain_func(foot_pos[0] + 0.02) == terrain_func(foot_pos[0] - 0.02):249 break250 if np.abs(cur_state[1] - x0_flight[1]) > 0.05:251 ret_val = self.checkFlightCollision(cur_state, terrain_func, debug = print_fails)252 if ret_val < 0: 253 break254 return ret_val, flight_states, integrator.t255# Higher level wrapper functions that simulate multiple flight/stance phases256def getNextState(hopper, x_flight, u, terrain_func):257 success, flight_states, _ = hopper.simulateOneFlightPhaseODE(None, 258 x_init = x_flight,259 debug = True,260 u = u,261 terrain_func = terrain_func,262 print_fails = False)263 if not success:264 return False, -1, -1, []265 last_flight_state = flight_states[len(flight_states)-1]266 foot_pos = hopper.getFootXYInFlight(last_flight_state)267 success, stance_states, _ = hopper.simulateOneStancePhase(last_flight_state, terrain_func = terrain_func,268 print_fails = False)269 if not success:270 return False, -1, -1, []271 last_stance_state = stance_states[len(stance_states) - 1]272 success, flight_states, _ = hopper.simulateOneFlightPhaseODE(last_stance_state, 273 foot_pos, 274 terrain_func = terrain_func,275 print_fails = False)276 if not success:277 return False, -1, -1, []278 apex_state = None279 for i in range (len(flight_states)-1):280 if flight_states[i+1][3] <= 0 and flight_states[i][3] >= 0:281 apex_state = flight_states[i]282 break283 return True, foot_pos[0], flight_states[len(flight_states)-1], apex_state284def getNextState2Count(robot, x_flight, input_angle, terrain_func, terrain_normal_func = None, friction = None,285 at_apex = False):286 count = 0287 code, flight_states, _ = robot.simulateOneFlightPhaseODE(None, 288 x_init = x_flight,289 debug = True,290 u= input_angle,291 terrain_func = terrain_func,292 print_fails = False,293 hit_apex = at_apex)294 count += len(flight_states)295 if code < 0:296 return None, None, None, count297 if at_apex:298 first_apex = x_flight299 else:300 for i in range (len(flight_states)-1):301 if flight_states[i+1][3] <= 0 and flight_states[i][3] >= 0:302 apex_state = flight_states[i]303 first_apex = apex_state304 break305 306 last_flight_state = flight_states[len(flight_states)-1]307 foot_pos = robot.getFootXYInFlight(last_flight_state)308 first_step_loc = foot_pos[0]309 code, stance_states, _ = robot.simulateOneStancePhase(last_flight_state,310 terrain_func = terrain_func,311 print_fails = False,312 terrain_normal_func = terrain_normal_func,313 friction = friction)314 count += len(stance_states)315 if code < 0:316 return None, None, None, count317 last_stance_state = stance_states[len(stance_states) - 1]318 x_flight = robot.stanceToFlight(last_stance_state, foot_pos)319 320 code, flight_states, _ = robot.simulateOneFlightPhaseODE(None, 321 x_init = x_flight,322 debug = True,323 u= np.pi/2,324 terrain_func = terrain_func,325 print_fails = False)326 second_step = flight_states[-1][0]327 count += len(flight_states)328 if code < 0:329 return None, None, None, count330 for i in range (len(flight_states)-1):331 if flight_states[i+1][3] <= 0 and flight_states[i][3] >= 0:332 second_apex = flight_states[i]333 break334 return first_apex, second_apex, flight_states[-1], count335def getNextState2(robot, x_flight, input_angle, terrain_func, terrain_normal_func = None, friction = None,336 at_apex = False):337 code, flight_states, _ = robot.simulateOneFlightPhaseODE(None, 338 x_init = x_flight,339 debug = True,340 u= input_angle,341 terrain_func = terrain_func,342 print_fails = False,343 hit_apex = at_apex)344 if code < 0:345 return None, None, None346 if at_apex:347 first_apex = x_flight348 else:349 for i in range (len(flight_states)-1):350 if flight_states[i+1][3] <= 0 and flight_states[i][3] >= 0:351 apex_state = flight_states[i]352 first_apex = apex_state353 break354 355 last_flight_state = flight_states[len(flight_states)-1]356 foot_pos = robot.getFootXYInFlight(last_flight_state)357 first_step_loc = foot_pos[0]358 code, stance_states, _ = robot.simulateOneStancePhase(last_flight_state,359 terrain_func = terrain_func,360 print_fails = False,361 terrain_normal_func = terrain_normal_func,362 friction = friction)363 if code < 0:364 return None, None, None365 last_stance_state = stance_states[len(stance_states) - 1]366 x_flight = robot.stanceToFlight(last_stance_state, foot_pos)367 368 # simulate one more flight phase to check for collision (for robustness)369 code, flight_states, _ = robot.simulateOneFlightPhaseODE(None, 370 x_init = x_flight,371 debug = True,372 u= np.pi/2,373 terrain_func = terrain_func,374 print_fails = False)375 second_step = flight_states[-1][0]376 if code < 0:377 return None, None, None378 for i in range (len(flight_states)-1):379 if flight_states[i+1][3] <= 0 and flight_states[i][3] >= 0:380 apex_state = flight_states[i]381 second_apex = apex_state382 break383 return first_apex, second_apex, flight_states[-1]384def getNextState3(robot, x_flight, input_angle, terrain_func, terrain_normal_func = None, friction = None):385 code, flight_states, _ = robot.simulateOneFlightPhaseODE(None, 386 x_init = x_flight,387 debug = True,388 u= input_angle,389 terrain_func = terrain_func,390 print_fails = False)391 if code < 0:392 return None, None393 for i in range (len(flight_states)-1):394 if flight_states[i+1][3] <= 0 and flight_states[i][3] >= 0:395 apex_state = flight_states[i]396 first_apex = apex_state397 break398 399 last_flight_state = flight_states[len(flight_states)-1]400 foot_pos = robot.getFootXYInFlight(last_flight_state)401 first_step_loc = foot_pos[0]402 code, stance_states, _ = robot.simulateOneStancePhase(last_flight_state,403 terrain_func = terrain_func,404 print_fails = False,405 terrain_normal_func = terrain_normal_func,406 friction = friction)407 if code < 0:408 return None, None409 last_stance_state = stance_states[len(stance_states) - 1]410 x_flight = robot.stanceToFlight(last_stance_state, foot_pos)411 412 # simulate one more flight phase to check for collision (for robustness)413 code, flight_states, _ = robot.simulateOneFlightPhaseODE(None, 414 x_init = x_flight,415 debug = True,416 u= np.pi/2,417 terrain_func = terrain_func,418 print_fails = False)419 420 second_step = flight_states[-1][0]421 if code < 0:422 return None, None423 return first_step_loc, second_step424def simulateNSteps(robot, n, initial_apex, input_angles, terrain_func, return_apexes = False,425 terrain_normal_func = None, friction = None, print_fails = False):426 steps = 0427 step_locs = []428 if len(input_angles) != n:429 return None, None430 x_flight = initial_apex431 apexes = []432 while steps < n:433 code, flight_states, _ = robot.simulateOneFlightPhaseODE(None, 434 x_init = x_flight,435 debug = True,436 u= input_angles[steps],437 terrain_func = terrain_func,438 print_fails = print_fails)439 if code < 0:440 return None, None441 for i in range (len(flight_states)-1):442 if flight_states[i+1][3] <= 0 and flight_states[i][3] >= 0:443 apex_state = flight_states[i]444 apexes.append(apex_state)445 break446 447 last_flight_state = flight_states[len(flight_states)-1]448 foot_pos = hopper.sgetFootXYInFlight(last_flight_state)449 step_locs.append(foot_pos[0])450 code, stance_states, _ = robot.simulateOneStancePhase(last_flight_state,451 terrain_func = terrain_func,452 print_fails = print_fails,453 terrain_normal_func = terrain_normal_func,454 friction = friction)455 steps += 1456 if code < 0:457 return None, None458 last_stance_state = stance_states[len(stance_states) - 1]459 x_flight = hopper.sstanceToFlight(last_stance_state, foot_pos)460 461 # simulate one more flight phase to check for collision (for robustness)462 code, flight_states, _ = robot.simulateOneFlightPhaseODE(None, 463 x_init = x_flight,464 debug = True,465 u= np.pi/2,466 terrain_func = terrain_func,467 print_fails = print_fails)468 469 if code < 0:470 return None, None471 for i in range (len(flight_states)-1):472 if flight_states[i+1][3] <= 0 and flight_states[i][3] >= 0:473 apex_state = flight_states[i]474 apexes.append(apex_state)475 break476 if return_apexes:477 return step_locs, apexes478 else:...

Full Screen

Full Screen

main.py

Source:main.py Github

copy

Full Screen

1moder = False23try:4 import requests5 import colorama6 import capmonster_python7except:8 moder = True91011if moder == True:12 print("Missing Modules Press Enter To Download Them (May Not Always Work): ")13 input("")14 try:15 import os16 os.system("pip install requests")17 os.system("pip install colorama")18 os.system("pip install capmonster-python")19 print("Problem May Be Fixed Now, Restart The Program")20 input("")21 exit()22 except:23 print("Failed To Install Modules")24 input("")25 exit()26 27 282930import json31import threading32import time33import random34import os3536373839try:40 import os41 os.system("title " + "Discord Account Creator, Made By blob#0005, Github: github.com/blob0005")42except:43 pass444546colorama.init(autoreset=True)47def settings():48 while True:49 error = False50 try:51 global api_key52 global print_fails53 global print_captcha54 global print_taskid55 global print_fingerprint56 global username57 global password58 global print_email59 global print_proxy60 global invite61 global random_letters62 global threads63 global use_proxies64 global random_user65 json_data = open("settings.json")66 json_data = json.load(json_data)67 api_key = json_data["capmonster_key"]68 print_fails = json_data["print_fails_y_or_n"]69 print_captcha = json_data["print_captcha_key_y_or_n"]70 print_taskid = json_data["print_task_id_key_y_or_n"]71 print_fingerprint = json_data["print_fingerprint_y_or_n"]72 username = json_data["tokens_username"]73 password = json_data["tokens_password"]74 print_email = json_data["print_email_y_or_n"]75 print_proxy = json_data["print_proxy_y_or_n"]76 threads = json_data["threads"]77 invite = json_data["invite_code"]78 random_letters = json_data["random_letters_after_token_username_y_or_n"]79 use_proxies = json_data["use_proxies_y_or_n"]80 random_user = json_data["random_username_from_names.txt_y_or_n"]81 try:82 bal = capmonster_python.HCaptchaTask(api_key)83 el = bal.get_balance()84 except:85 error = True86 if print_fails != "y" and print_fails != "n": 87 error = True88 if print_captcha != "y" and print_captcha != "n": 89 error = True 90 if print_taskid != "y" and print_taskid != "n": 91 error = True92 if print_fingerprint != "y" and print_fingerprint != "n": 93 error = True94 if print_email != "y" and print_email != "n": 95 error = True96 if print_proxy != "y" and print_proxy != "n": 97 error = True98 if random_letters != "y" and random_letters != "n": 99 error = True100 if use_proxies != "y" and use_proxies != "n": 101 error = True102 if "-" in str(threads):103 error = True104 if random_user != "y" and random_user != "n":105 error = True106 try:107 threads = int(threads)108 except:109 error = True110 if error == True:111 print(colorama.Fore.RED + "[-] Press Enter When You Have Fixed Settings And All Settings Will Reload")112 input("")113 if error == False:114 break115 except Exception as e:116 print(colorama.Fore.RED + 'Missing "settings.json" File, It Stores All Settings')117 input("")118 exit()119120121 if str(threads) != "1" and use_proxies == "n":122 print("Cannot Have More Than 1 Thread Without Proxies, Please Restart The Program And Enter Valid Settings")123 input("")124 exit()125126127settings()128129130131cap = capmonster_python.HCaptchaTask(api_key)132133134135def gen():136 try:137 while True:138139 session = requests.session()140 141 if use_proxies == "y":142 prox = open("rotating_proxy.txt", "r")143 proxy = str(prox.readline())144 print(proxy)145 print(colorama.Fore.GREEN + "[-] Loaded Proxie")146 147 while True:148 try:149 tt = cap.create_task("https://discord.com/register", "4c672d35-0701-42b2-88c3-78380b0db560")150 if print_taskid == "y":151 print(colorama.Fore.GREEN + "[+] Succsesfully Got Task Id, " + str(tt))152 if print_taskid == "n":153 print(colorama.Fore.GREEN + "[+] Succsesfully Got Task Id")154 break155 except Exception:156 if print_fails == "y":157 print(colorama.Fore.RED + "[-] Failed To Get Task Id, Retrying")158159160 while True:161 try:162 captcha = cap.join_task_result(tt)163 captcha = str(captcha.get("gRecaptchaResponse"))164 if print_captcha == "n":165 print(colorama.Fore.GREEN + "[+] Succsesfully Got Captcha Key")166 if print_captcha == "y":167 print(colorama.Fore.GREEN + "[+] Succsesfully Got Captcha Key, " + captcha)168 break169 except:170 if print_fails == "y":171 print(colorama.Fore.RED + "[-] Failed To Get Captcha Key, Retrying")172173174175 while True:176 try:177 session.headers["X-Fingerprint"] = session.get("https://discord.com/api/v9/experiments").json()["fingerprint"]178 Fingerprint = session.headers["X-Fingerprint"]179 if print_fingerprint == "y":180 print(colorama.Fore.GREEN + "[+] Succsesfully Got Fingerprint, " + Fingerprint)181 if print_fingerprint == "n":182 print(colorama.Fore.GREEN + "[+] Succsesfully Got Fingerprint")183 break184 except:185 if print_fails == "y":186 print(colorama.Fore.RED + "[-] Failed To Get Fingerprint, Retrying")187 session.xsup = 'eyJvcyI6IldpbmRvd3MiLCJicm93c2VyIjoiQ2hyb21lIiwiZGV2aWNlIjoiIiwic3lzdGVtX2xvY2FsZSI6ImVuLVVTIiwiYnJvd3Nlcl91c2VyX2FnZW50IjoiTW96aWxsYS81LjAgKFdpbmRvd3MgTlQgMTAuMDsgV2luNjQ7IHg2NCkgQXBwbGVXZWJLaXQvNTM3LjM2IChLSFRNTCwgbGlrZSBHZWNrbykgQ2hyb21lLzkzLjAuNDU3Ny42MyBTYWZhcmkvNTM3LjM2IEVkZy85My4wLjk2MS40NyIsImJyb3dzZXJfdmVyc2lvbiI6IjkzLjAuNDU3Ny42MyIsIm9zX3ZlcnNpb24iOiIxMCIsInJlZmVycmVyIjoiaHR0cHM6Ly9kaXNjb3JkLmNvbS9jaGFubmVscy81NTQxMjU3Nzc4MTg2MTU4NDQvODcwODgxOTEyMzQyODUxNTk1IiwicmVmZXJyaW5nX2RvbWFpbiI6ImRpc2NvcmQuY29tIiwicmVmZXJyZXJfY3VycmVudCI6IiIsInJlZmVycmluZ19kb21haW5fY3VycmVudCI6IiIsInJlbGVhc2VfY2hhbm5lbCI6InN0YWJsZSIsImNsaWVudF9idWlsZF9udW1iZXIiOjk3NTA3LCJjbGllbnRfZXZlbnRfc291cmNlIjpudWxsfQ=='188 session.headers = {189 'Host': 'discord.com', 'Connection': 'keep-alive',190 'sec-ch-ua': '"Chromium";v="92", " Not A;Brand";v="99", "Google Chrome";v="92"',191 'X-Super-Properties': session.xsup,192 'Accept-Language': 'en-US', 'sec-ch-ua-mobile': '?0',193 "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36 Edg/93.0.961.47",194 'Content-Type': 'application/json', 'Authorization': 'undefined',195 'Accept': '*/*', 'Origin': 'https://discord.com',196 'Sec-Fetch-Site': 'same-origin', 'Sec-Fetch-Mode': 'cors',197 'Sec-Fetch-Dest': 'empty', 'Referer': 'https://discord.com/register',198 'X-Debug-Options': 'bugReporterEnabled',199 'Accept-Encoding': 'gzip, deflate, br',200 'Cookie': 'OptanonConsent=version=6.17.0; locale=th'201 }202 choices = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]203 if random_user == "n":204 if random_letters == "y":205 rande = random.choices(choices, k=5)206 rande = "".join(rande)207 rande = str(rande)208 rande = " | " + rande209 if random_letters == "n":210 rande = ""211212 usa = username + rande213214 if random_user == "y":215 fe = open("names.txt", "r")216 er = fe.readlines()217 ee = []218 for t in er:219 if "\n" in t:220 ee.append(t[:-1])221 else:222 ee.append(t)223 usa = str(random.choice(ee))224 fe.close()225226 print("usa ", usa)227 email = random.choices(choices, k=16)228 email = str("".join(email))229 if print_email == "y":230 print(colorama.Fore.GREEN + f"[+] Generated Email, {email}@gmail.com")231 if print_email == "n":232 print(colorama.Fore.GREEN + f"[+] Generated Email")233 payload = {234 "fingerprint": Fingerprint,235 "email": f"{email}@gmail.com",236 "username": f"{usa}",237 "password": password,238 "invite": invite,239 "consent": True,240 "date_of_birth": "2003-11-18",241 "gift_code_sku_id": None,242 "captcha_key": captcha,243 "promotional_email_opt_in": True244 }245 while True:246 if use_proxies == "y":247 session.proxies = {248 "http": proxy,249 "https": proxy250 }251 reg = session.post('https://discord.com/api/v9/auth/register', json=payload)252 res = str(reg)253 jle = reg.json()254 if "201" in res:255 token = str(jle["token"])256 file = open("tokens.txt", "a")257 file.write(token+"\n")258 file.close()259 print(colorama.Fore.GREEN + f"[+] Generated Token/Account ({usa}), Saved In tokens.txt And If Invite In settings.json Is Valid Token Shall Auto Join")260 break261 if "429" in res:262 time2 = float(jle["retry_after"])263 if print_fails == "y":264 print(colorama.Fore.RED + f"[-] Rate Limited, Sleeping For {str(time2)} Seconds")265 time.sleep((float(time2)))266 if "400" in res:267 if print_fails == "y":268 print(colorama.Fore.RED + "[-] Failed To Create Account")269 break270 if "400" not in res and "429" not in res and "201" not in res:271 if print_fails == "y":272 print(colorama.Fore.RED + "[-] Unkown Error")273 break 274 if str(threads) == "1":275 print(colorama.Fore.LIGHTGREEN_EX + "------------------------")276 except Exception as e:277 print(str(e))278 if print_fails == "y":279 print(colorama.Fore.RED + "[-] Unkown Error")280281def clear():282 os.system("cls")283284try:285 bal = capmonster_python.HCaptchaTask(api_key)286 el = bal.get_balance()287except:288 print(colorama.Fore.RED + "[-] Capmonster Key Is Invalid")289 while True:290 input("")291while True:292 tools = input("""293 1. Token Generator/Member Botter/Token Creator294 2. Check Capmonster Balance295 3. Reload Settings296 > """)297 if tools == "1":298 er = 0299 for u in range(int(threads)):300 threading.Thread(target=gen).start()301 er = int(er) + 1302 print(colorama.Fore.GREEN + f"[+, {str(er)}] Started Thread")303 while True:304 input("")305 if tools == "2":306 print(colorama.Fore.GREEN + "[+] Getting Balance, Be Patient")307 try:308 bal = capmonster_python.HCaptchaTask(api_key)309 print(colorama.Fore.GREEN + "[+] Balance: " + str(bal.get_balance()) + "$")310 except:311 print(colorama.Fore.RED + "[-] Capmonster Key Is Invalid")312 input(" > ")313 clear()314 if tools == "3":315 settings()316 print(colorama.Fore.GREEN + "[+] Reloaded Settings")317 input(" > ") ...

Full Screen

Full Screen

unit_tests.py

Source:unit_tests.py Github

copy

Full Screen

1#!/usr/bin/env python32#3# Copyright (C) [2020] Futurewei Technologies, Inc.4#5# FORCE-RISCV is licensed under the Apache License, Version 2.06# (the "License"); you may not use this file except in compliance7# with the License. You may obtain a copy of the License at8#9# http://www.apache.org/licenses/LICENSE-2.010#11# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES12# OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO13# NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.14# See the License for the specific language governing permissions and15# limitations under the License.16#17import getopt18import os19import shlex20import subprocess21import sys22import time23from functools import partial24from multiprocessing import Pool, Manager25from regression_utils import verify_force_path, verify_dir_writable26def usage(extra=None):27 usage_str = (28 """29Run quick regression30 -h, --help print this help message31 --clean Run "make clean" in each unit test directory before32 running "make".33 --force-path point to force path.34 --nopicky disable -Weffc++ compiler flag.35 -x, --process-max The maximum number of concurrent execution threads.36 -z, --print-failures Print the stdout and stderr of each failing test case37 to the console.38Example:39 %s --force-path force-gen-path40"""41 % sys.argv[0]42 )43 print(usage_str)44 if extra:45 print(extra)46class ExecutionTrace:47 def __init__(self, arg_stdout, arg_retcode, arg_cmd, arg_time):48 self.stdout = arg_stdout49 self.retcode = arg_retcode50 self.cmd = arg_cmd51 self.execution_duration = arg_time52def unit_tests():53 try:54 my_oplist = [55 "help",56 "clean",57 "force-path=",58 "nopicky",59 "process-max=",60 "print-failures",61 ]62 (opts, args) = getopt.getopt(sys.argv[1:], "hx:z", my_oplist)63 except getopt.GetoptError as err:64 print("\nERROR: " + str(err) + "\n")65 print(66 'Please Run "'67 + sys.argv[0]68 + ' -h or --help" for usage information\n'69 )70 sys.exit(1)71 clean_build = False72 force_path = None73 process_max = 1674 print_fails = False75 nopicky = False76 for (o, a) in opts:77 if o in ("-h", "--help"):78 usage()79 sys.exit(0)80 elif o == "--clean":81 clean_build = True82 elif o == "--force-path":83 force_path = a84 elif o == "--nopicky":85 nopicky = True86 elif o in ["-x", "--process-max"]:87 process_max = int(a)88 elif o in ["-z", "--print-failures"]:89 print_fails = True90 else:91 raise ValueError("Unhandled option.")92 if not force_path:93 try:94 force_path = os.environ["FORCE_PATH"]95 except KeyError as ke:96 force_path = "."97 print('Default FORCE_PATH=".".')98 force_path = os.path.abspath(force_path)99 (_, unit_tests_path) = verify_force_path(force_path)100 run_unit_tests(101 unit_tests_path, process_max, print_fails, nopicky, clean_build102 )103 sys.exit(0)104def run_unit_tests(105 unit_tests_path, num_parallel_workers, print_fails, nopicky, clean_build106):107 verify_dir_writable(unit_tests_path)108 p = Pool(num_parallel_workers)109 arg_array = list()110 sharing_manager = Manager()111 job_output_queue = sharing_manager.list()112 for test_layer_dirname in os.listdir(unit_tests_path):113 test_layer_path = os.path.join(unit_tests_path, test_layer_dirname)114 if os.path.isdir(test_layer_path):115 for test_dirname in os.listdir(test_layer_path):116 test_path = os.path.join(test_layer_path, test_dirname)117 if os.path.isdir(test_path) and (test_dirname != ".svn"):118 arg_tuple = (test_path, test_dirname, job_output_queue)119 arg_array.append(arg_tuple)120 run_one_test = partial(run_one_unit_test, nopicky, clean_build)121 p.map(run_one_test, arg_array)122 p.close()123 p.join()124 num_fails = 0125 bufp = list()126 bufp.append("The following tests have failed: \n")127 for (test_dirname, process_return) in job_output_queue:128 if process_return.retcode != 0:129 num_fails += 1130 bufp.append(131 "[%s]: Test: %s. Command: %s. Duration: %s seconds."132 % (133 str(num_fails),134 test_dirname,135 process_return.cmd,136 str(process_return.execution_duration),137 )138 )139 if print_fails:140 bufp.append(process_return.stdout)141 bufp.append("\n=======\n")142 if num_fails == 0:143 print("=====ALL SUCCESS!=====")144 else:145 print("\n=====FAILURES:=====")146 for output in bufp:147 print(output)148 print("%s failures.\n" % (num_fails))149def run_one_unit_test(nopicky, clean_build, arg_tuple):150 (test_path, test_dirname, execution_queue) = arg_tuple151 cur_path = os.getcwd()152 os.chdir(test_path)153 success = True154 if clean_build:155 cmd = "make clean"156 process_return = execute_command(cmd)157 success = process_return.retcode == 0158 make_duration = 0.0159 if success:160 cmd = "make OPTIMIZATION=-O0"161 if nopicky:162 cmd += " PICKY="163 process_return = execute_command(cmd)164 success = process_return.retcode == 0165 make_duration = process_return.execution_duration166 log_output(process_return.stdout, test_path, "make.log")167 run_duration = 0.0168 if success:169 cmd = "bin/%s_test" % test_dirname170 process_return = execute_command(cmd)171 success = process_return.retcode == 0172 run_duration = process_return.execution_duration173 log_output(process_return.stdout, test_path, "run.log")174 result_string = "SUCCESS." if success else "FAILED."175 print(176 "%s: %s (Make Duration: %0.4f sec; Run Duration: %0.4f sec)"177 % (test_dirname, result_string, make_duration, run_duration)178 )179 # Whole append call is done in one GIL lock; list appends are thread safe,180 # no need for special threaded queues181 execution_queue.append((test_dirname, process_return))182 os.chdir(cur_path)183def execute_command(cmd):184 # Measure the amount of time it took to run this test185 start_time = time.time()186 process = subprocess.run(187 shlex.split(cmd), stdout=subprocess.PIPE, stderr=subprocess.STDOUT188 )189 end_time = time.time()190 process_stdout = process.stdout.decode("utf-8")191 ret_code = process.returncode192 trace = ExecutionTrace(193 process_stdout, ret_code, cmd, end_time - start_time194 )195 return trace196def log_output(output, test_path, file_name):197 with open(os.path.join(test_path, "bin", file_name), "w") as log_file:198 log_file.write(output)199if __name__ == "__main__":...

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 stestr 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