def execute(self): if self.apoapsis_altitude() > self.target_apoapsis: return self.ap.engage() self.ap.target_pitch_and_heading(90.0, self.target_heading) self.vessel.control.throttle = 1.0 if (self.vessel.situation == self.conn.space_center.VesselSituation.pre_launch): self.ap.target_pitch_and_heading(90, self.target_heading) countdown_to("LAUNCH!") self.check_staging(force=True) else: self.setup_staging_callback() while self.running: if self.check_staging(): wait() if self.surface_altitude() < 250: self.g_limit(2.2) elif self.apoapsis_altitude() < 0.9 * self.target_apoapsis: self.g_limit(2.2) self.tip_over() elif self.apoapsis_altitude() < self.target_apoapsis: self.g_limit(1.0) else: self.vessel.control.throttle = 0.0 self.running = False wait() self.ap.disengage()
def slow_down(self, vessel): notify('Slowing down...') vessel = self.vessel control = vessel.control rf = vessel.orbit.body.reference_frame flight = vessel.flight(rf) _surface_velocity = self.conn.add_stream(getattr, flight, 'velocity') surface_velocity = lambda: -np.array(_surface_velocity()) ap = vessel.auto_pilot ap.engage() ap.reference_frame = rf ap.target_direction = surface_velocity() ap.wait() g = self.surface_gravity ut, delta_v, delta_t = self.estimate_suicide_burn() self.conn.space_center.warp_to(ut - 0.5 * delta_t) control.throttle = 1.0 effective_twr = self.TWR() - self.surface_gravity notify( f'surface_altitude:{self.surface_altitude()}, vertical_speed:{self.vertical_speed()}, effective_twr:{effective_twr}' ) while -self.vertical_speed() > 10 * effective_twr: ap.target_direction = surface_velocity() wait() control.throttle = 0.0 notify( f'surface_altitude:{self.surface_altitude()}, vertical_speed:{self.vertical_speed()}' )
def get_friends(username): # get or create the user the_user = graph.find_one('User', 'screen_name', username) if not the_user: the_user = Node( 'User', screen_name=username, ) graph.create(the_user) # get or create the friends of the user next_cursor = -1 while next_cursor != 0: try: response = client.api.friends.ids.get( screen_name=username, count=5000, cursor=next_cursor, ) except TwitterRateLimitError, e: wait(e) else: for user_id in response.data.ids: followed_user, created = get_or_create_by_id(user_id) graph.create_unique( Relationship(the_user, "FOLLOWS", followed_user) ) next_cursor = response.data.next_cursor
def test_deadlock(config): """test when two backends try to extract state of each other""" acon1, acon2 = common.n_async_connect(config, 2) acurs1 = acon1.cursor() acurs2 = acon2.cursor() while True: acurs1.callproc('pg_query_state', (acon2.get_backend_pid(), )) acurs2.callproc('pg_query_state', (acon1.get_backend_pid(), )) # listen acon1, acon2 with timeout = 10 sec to determine deadlock r, w, x = select.select([acon1.fileno(), acon2.fileno()], [], [], 10) assert (r or w or x), "Deadlock is happened under cross reading of query states" common.wait(acon1) common.wait(acon2) # exit from loop if one backend could read state of execution 'pg_query_state' # from other backend if acurs1.fetchone() or acurs2.fetchone(): break common.n_close((acon1, acon2))
def execute(self): vessel = self.vessel ksc = self.conn.space_center orbit = vessel.orbit body = orbit.body control = vessel.control atmosphere = body.atmosphere_depth warp_radius = body.equatorial_radius + atmosphere anom = orbit.true_anomaly_at_radius(warp_radius) ut = min(orbit.ut_at_true_anomaly(anom), orbit.ut_at_true_anomaly(-anom)) ksc.warp_to(ut - 15) control.sas = True control.sas_mode = control.sas_mode.retrograde wait(5) control.throttle = 1.0 self.setup_staging_callback() while self.running: self.check_staging() if self.apoapsis_altitude() < atmosphere: break control.throttle = 0 # TODO: handle decoupling heat shields while max([part.decouple_stage for part in vessel.parts.all]) > -1: control.activate_next_stage() control.sas = True control.sas_mode = control.sas_mode.retrograde
def create_socket_connection(self): n = 1 while True: try: wait((n - 1) * 2) self.log.info('creating socket and connecting ... try #%s' % n) self.socket.connect((self.ip_address, self.port)) self.log.info('socket connected to %s:%s' % (self.ip_address, self.port)) break except Exception as ex: self.log.critical(ex) n += 1 if n > 3: break
def download_and_play(name, url, path): if os.path.isfile(path) is True: notification('download Alert', 'The video you are trying to download already exists!') return False else: print 'attempting to download and play file' try: print "Starting download Thread" dlThread = DownloadAndPlayThread(url, path, name) dlThread.start() wait(WAITING_TIME, "Buffering") xbmc.Player().play(path) except: print 'download failed'
def main(): os.makedirs('downloads', exist_ok=True) with open('download.list', 'r') as csvfile: reader = csv.DictReader(csvfile, [ 'download_url', 'file_name', ]) for r in reader: url = r['download_url'] path = os.path.join('downloads', r['file_name']) if os.path.exists(path): print("Already downloaded {} to {}".format(url, path)) else: wait() print("Downloading {} to {}".format(url, path)) wget.download(url, path) print()
def test_concurrent_access(config): """test when two backends compete with each other to extract state from third running backend""" acon1, acon2, acon3 = common.n_async_connect(config, 3) acurs1, acurs2, acurs3 = acon1.cursor(), acon2.cursor(), acon3.cursor() query = 'select count(*) from foo join bar on foo.c1=bar.c1' common.set_guc(acon3, 'max_parallel_workers_per_gather', 0) acurs3.execute(query) time.sleep(0.1) acurs1.callproc('pg_query_state', (acon3.get_backend_pid(), )) acurs2.callproc('pg_query_state', (acon3.get_backend_pid(), )) common.wait(acon1) common.wait(acon2) common.wait(acon3) qs1, qs2 = acurs1.fetchall(), acurs2.fetchall() assert len(qs1) == len(qs2) == 1 \ and qs1[0][0] == qs2[0][0] == acon3.get_backend_pid() \ and qs1[0][1] == qs2[0][1] == 0 \ and qs1[0][2] == qs2[0][2] == query \ and len(qs1[0][3]) > 0 and len(qs2[0][3]) > 0 \ and qs1[0][4] == qs2[0][4] == None common.n_close((acon1, acon2, acon3))
def get_foafs(username): cypher = graph.cypher # get friends of the user; i.e. mutually followed users result = cypher.stream("MATCH ({screen_name:'%(username)s'})-->(friend)-->({screen_name:'%(username)s'}) " "RETURN friend.id" % {'username': username}) for record in result: friend, created = get_or_create_by_id(record['friend.id']) friend_id = friend.properties['id'] print 'getting friends of %s' % friend_id # get or create the friends of the friend next_cursor = -1 while next_cursor != 0: try: response = client.api.friends.ids.get( user_id=friend_id, count=5000, cursor=next_cursor, ) except TwitterRateLimitError, e: wait(e) except:
def get_friend_details(username): # update the friends' nodes with names and screen names def chunks(l, n=100): # 100 is the Twitter limit for i in xrange(0, len(l), n): yield l[i:i+n] cypher = graph.cypher # get friends of the user; i.e. mutually followed users result = cypher.execute("MATCH ({screen_name:'%(username)s'})-->(friend)-->({screen_name:'%(username)s'}) " "RETURN friend.id" % {'username': username}) for chunk in chunks(result): ids = ','.join([str(r['friend.id']) for r in chunk]) try: profiles = client.api.users.lookup.post(user_id=ids, entities=False) except TwitterRateLimitError, e: wait(e) else: for profile in profiles.data: user, created = get_or_create_by_id(profile['id']) user.properties['name'] = profile['name'] user.properties['screen_name'] = profile['screen_name'] graph.push(user)
def apply_job(browser, job_page): # Open job page and send application try: wait() browser.get(job_page) wait() browser.find_elements_by_class_name("m-applyButton__button")[0].click() wait() browser.find_elements_by_class_name("c-applyForm__action")[0].click() return 1 except: output_timed_message('ERROR: Applying error') return 0
def login(browser): # Login to karriere.at try: browser.get(url_login) wait() browser.find_element_by_id('email').send_keys(user_login) wait() browser.find_element_by_id('password').send_keys(user_password) browser.find_elements_by_class_name( "m-userLogin__submitButton")[0].click() wait() if len(browser.find_elements_by_id('email')) > 0: output_timed_message('ERROR: Wrong login/password') return 0 return 1 except: output_timed_message('ERROR: Login error') return 0
def controlled_descent(self, target=None): LANDED = self.conn.space_center.VesselSituation.landed SPLASHED = self.conn.space_center.VesselSituation.splashed vessel = self.vessel control = vessel.control control.trottle = 0 control.brakes = True control.gear = True control.lights = True control.solar_panels = False control.sas = False lat, lon = target # rf = vessel.surface_reference_frame rf = vessel.orbit.body.reference_frame flight = vessel.flight(rf) _pos = self.conn.add_stream(getattr, flight, 'center_of_mass') pos = lambda: np.array(_pos()) target_pos = lambda: np.array( vessel.orbit.body.surface_position(lat, lon, rf)) _surface_velocity = self.conn.add_stream(getattr, flight, 'velocity') surface_velocity = lambda: -np.array(_surface_velocity()) ap = vessel.auto_pilot ap.engage() ap.reference_frame = rf ap.target_direction = surface_velocity() landing_speed = 0.5 v_target = lambda: 0.2 * self.surface_altitude() + landing_speed base_throttle = lambda: self.surface_gravity / self.TWR() effective_twr = self.TWR() - self.surface_gravity notify('Waiting for landing burn...') while self.surface_altitude( ) > self.stopping_distance() + 2.0 * wait.interval * self.speed(): ap.target_direction = surface_velocity() wait() control.throttle = 1.0 notify('Landing burn!') notify(f'altitude: {self.surface_altitude()}') while self.speed() > 5 * effective_twr: d = surface_velocity() ap.target_direction = d / np.linalg.norm(d) wait() notify(f'effective_twr: {effective_twr}') pid = PID(0.2, 0.0, 0.0, sample_time=wait.interval, output_limits=(-1.0, 1.0)) notify('Entering controlled descent...') while self.situation() not in [LANDED, SPLASHED]: altitude = self.surface_altitude() base = base_throttle() target = v_target() actual = -self.vertical_speed() pid_input = target - actual pid_output = pid(pid_input) # notify({ # 'altitude': altitude, # 'target': target, # 'actual': actual, # 'input': pid_input, # 'output': pid_output, # 'pos': pos(), # 'target_pos', target_pos, # }) notify( f'altitude:{altitude:.2f}, target:{target:.2f}, actual:{actual:.2f}, input:{pid_input:.2f}, output:{pid_output:.2f}, pos: {pos()}, target: {target_pos()}' ) control.throttle = base + pid_output if self.surface_altitude() < 25: ap.target_direction = pos() else: d = surface_velocity() ap.target_direction = d wait() control.throttle = 0 ap.disengage() notify('done')
def start(): mark("welcome") oled_page("Hi " + name + "!", "The cursor at", "the bottom right", "means 'press the'", "black button'") wait() oled_page("I'm Pico!", "I'm so happy to", "meet you! Joel", "thinks you're", "awesome.") wait() oled_page("Getting Hints", "If you get stuck", "and need a hint", "use Slack", "#secret-pico") wait() oled_page("Let's begin!", "Let's move this", "convo to your", "laptop, ok?") wait() oled_page("Type in Shell:", "screen", " /dev/tty.usb*", "", "& press RETURN") wait() oled_page("Connect to me!", "", "I'll be waiting", "for you there :)") wait(msg="Press black button") oled_page("Serial output") print(""" Hi again! It's me, Pico! I'm a gift wrapped in a puzzle wrapped in an educational experience. Joel made me just for you and your cohort-mates. I've got lots to show you, plus a reward at the end. But first, like any good hero, you have to overcome some challenges. Don't give up too easily! Part of a challenge is figuring it out. But, remember, if you get stuck, you ask in #pico-secret. """) input("Press RETURN > ") print(""" Along the way, I have some learning material for you. For example, you should read: {url} """.format(url=url('pico'))) input("Press RETURN when ready > ") print(""" I can be programmed in lots of languages but, of course, Joel programmed me in Python. It's actually a version of Python called MicroPython, meant to be run on tiny machines like me. It has almost all of the normal language features, plus some of the standard library. We'll be using it throughout. You'll start each section by importing a Python module, and then running it's `start()` function. You can always revisit and earlier section by importing it. Of course, you won't know all the future sections, so you can't jump ahead :). Let's begin! I'm going to return you to my Python shell. When you're ready, you should type: >>> import begin >>> begin.start() See you there! """)
import common, opcodes, cleo, script script.name("QuickTeleport") script.author("Grinch_") script.desc("Teleport to marker location pressing X+Y") script.version("1.0") while True: common.wait(0) if common.key_pressed(0x58) and common.key_pressed(0x59): while common.key_pressed(0x58) and common.key_pressed(0x59): common.wait(25) coords = cleo.get_target_marker_coords() handle = opcodes.get_player_char(0) opcodes.do_fade(50, 0) opcodes.set_char_coordinates(handle, coords[0], coords[1], coords[2] + 100) opcodes.freeze_char_position_and_dont_load_collision(handle, True) common.wait(500) opcodes.set_char_coordinates(handle, coords[0], coords[1], coords[2]) opcodes.freeze_char_position_and_dont_load_collision(handle, False) opcodes.do_fade(50, 1)
def execute(self): ksc = self.conn.space_center vessel = self.vessel vessel.control.rcs = True rf = vessel.surface_reference_frame # x: up, y: north, z: east ap = vessel.auto_pilot ap.engage() ap.reference_frame = rf body = vessel.orbit.body surface_gravity = body.surface_gravity tick = 0.01 r = body.equatorial_radius degrees_per_meter = 180 / r / math.pi lat0 = self.latitude() + 50 * degrees_per_meter lat1 = lat0 + 10 * degrees_per_meter lon0 = self.longitude() lon1 = lon0 + 20 * degrees_per_meter target = lambda: None if not self.TWR(): vessel.control.activate_next_stage() def create_lateral_control(): Kp = 0.2 Kd = 3.0 * Kp lateral_acc = 0.5 * surface_gravity control = CascadeControl( PID( Kp=Kp, Kd=Kd, sample_time=tick, ), PID( Kp=1.0, Kd=0.0, output_limits=(-lateral_acc, lateral_acc), sample_time=tick, )) control.controls[0] = lambda *x: 0 return control controllers = [ PID(1.0, 0.0, 1.5), # up/down create_lateral_control(), # N/S create_lateral_control(), # E/W ] error = [[], [], []] def update_throttle(): delta_h = target.altitude - self.surface_altitude() twr = self.TWR() err = delta_h acc = surface_gravity + controllers[0](-err) throttle = acc / twr error[0].append(err) return throttle def force_vector(): p = -np.array(target.pointer) v = np.array(target.relative_velocity) scale = min(1.0, max(target.distance, 2.0 * target.speed)) scale = 1.0 vec = np.array([ surface_gravity, scale * controllers[1](p[1], v[1]), scale * controllers[2](p[2], v[2]) ]) error[1].append(ap.error) error[2].append(v[1]) return vec target.altitude = 50.0 target.latitude = self.latitude() target.longitude = self.longitude() while vessel.met < 8.0: vessel.control.throttle = update_throttle() ap.target_direction = (1, 0, 0) wait(tick) while not self.abort(): if self.brakes(): target.altitude = 100.0 target.latitude = lat1 target.longitude = lon1 else: target.altitude = 50 target.latitude = lat0 target.longitude = lon0 target.position = body.position_at_altitude( target.latitude, target.longitude, self.mean_altitude(), body.reference_frame) target.reference_frame = body.reference_frame target.pointer = ksc.transform_position(target.position, target.reference_frame, rf) target.distance = np.linalg.norm(target.pointer) target.relative_velocity = -np.array( ksc.transform_velocity(target.position, (0, 0, 0), target.reference_frame, rf)) target.speed = np.linalg.norm(target.relative_velocity) notify(target.distance, target.speed) F = force_vector() ap.target_direction = F scaled_force = np.linalg.norm(F) / surface_gravity vessel.control.throttle = update_throttle() * scaled_force wait(tick) vessel.control.throttle = 0 err1 = np.array(error[1]) err2 = np.array(error[2]) t = np.arange(len(err1)) plt.plot(t, np.zeros_like(t), label='zero') plt.plot(t, np.log(np.abs(err1) + 1.0), label='log err1') plt.plot(t, err1, label='raw err1') plt.plot(t, np.log(np.abs(err2) + 1.0), label='log err2') plt.plot(t, err2, label='raw err2') plt.xlabel('time') plt.ylabel('error') plt.legend() plt.show() wait()
import common, opcodes, hud, script script.name("CreateCar") script.author("Grinch_") script.desc("Spawns a car when Left Shift is pressed") script.version("1.0") while True: common.wait(0) if common.key_pressed(0xA0): while common.key_pressed(0xA0): common.wait(0) handle = opcodes.get_player_char(0) if opcodes.is_char_in_any_car(handle): hud.set_help_message("Already in a car", False, False, False) else: opcodes.request_model(400) opcodes.load_all_models_now() coord = opcodes.get_char_coordinates(handle) car : int = opcodes.create_car(400, coord[0], coord[1], coord[2]) opcodes.warp_char_into_car(handle, car) opcodes.mark_model_as_no_longer_needed(400)
def execute_next_node(conn): ''' This is the actually interesting function in this script! Executes the Next Maneuver Node for the vessel provided. If you just open and run this file, it will execute a node and exit. You can also include this file into your own script with the line from node_executor import execute_next_node at the top of your script, and then anytime you want to execute a node you just have to call (execute_next_node(conn) passing it the active KRPC connection as a parameter. I'm also demonstrating two different ways to point the vessel with the autopilot. One relies on the vessel having SAS Node holding capabilty, the other uses the KRPC built-in auto-pilot. The one built into KRPC can require some tuning depending on your vessel... but works on any vessel regardless of pilot skill/probe core choice! ''' space_center = conn.space_center vessel = space_center.active_vessel ap = vessel.auto_pilot # Grab the next node if it exists try: node = vessel.control.nodes[0] except Exception: return #Fail silently but gracefully if there was no node to execute # Orient vessel to the node ################## One Way To Orient Vessel!############## rf = vessel.orbit.body.reference_frame ap.reference_frame = rf ap.engage() ap.target_direction = node.remaining_burn_vector(rf) ap.wait() ################## Another Way To Orient Vessel!######## #ap.sas = True #time.sleep(.1) #ap.sas_mode = vessel.auto_pilot.sas_mode.maneuver #ap.wait() # Calculate the length and start of burn m = vessel.mass isp = vessel.specific_impulse dv = node.delta_v F = vessel.available_thrust G = 9.81 burn_time = (m - (m / math.exp(dv / (isp * G)))) / (F / (isp * G)) ap.reference_frame = rf ap.engage() ap.target_direction = node.remaining_burn_vector(rf) ap.wait() # TODO: check fuel level for potential staging # Warp until burn space_center.warp_to(node.ut - (burn_time / 2.0) - 5.0) ap.engage() ap.target_direction = node.remaining_burn_vector(rf) while node.time_to > (burn_time / 2.0): pass # Actually Burn vessel.control.throttle, acc = thrust_controller(vessel, node.remaining_delta_v) while node.remaining_delta_v > acc * wait.interval and node.remaining_delta_v > 0.2: ap.target_direction = node.remaining_burn_vector(rf) vessel.control.throttle, acc = thrust_controller( vessel, node.remaining_delta_v) wait() # Finish Up ap.disengage() vessel.control.throttle = 0.0 node.remove()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' import traceback from common import init_db, append_crash_statistics_db, wait init_db() while True: try: append_crash_statistics_db() wait(hours=12) except Exception as e: print('ERROR: {}:\n\n{}'.format(e, traceback.format_exc())) wait(minutes=5)
def run_tpcds(config): """TPC-DS stress test""" TPC_DS_EXCLUDE_LIST = [] # actual numbers of TPC-DS tests to exclude TPC_DS_STATEMENT_TIMEOUT = 20000 # statement_timeout in ms print('Preparing TPC-DS queries...') queries = [] for query_file in sorted( os.listdir( 'tmp_stress/tpcds-result-reproduction/query_qualification/')): with open( 'tmp_stress/tpcds-result-reproduction/query_qualification/%s' % query_file, 'r') as f: queries.append(f.read()) acon, = common.n_async_connect(config) pid = acon.get_backend_pid() print('Starting TPC-DS queries...') timeout_list = [] bar = progressbar.ProgressBar(max_value=len(queries)) for i, query in enumerate(queries): bar.update(i + 1) if i + 1 in TPC_DS_EXCLUDE_LIST: continue try: # Set query timeout to TPC_DS_STATEMENT_TIMEOUT / 1000 seconds common.set_guc(acon, 'statement_timeout', TPC_DS_STATEMENT_TIMEOUT) # run query acurs = acon.cursor() acurs.execute(query) # periodically run pg_query_state on running backend trying to get # crash of PostgreSQL MAX_FIRST_GETTING_QS_RETRIES = 10 PG_QS_DELAY, BEFORE_GETTING_QS_DELAY = 0.1, 0.1 BEFORE_GETTING_QS, GETTING_QS = range(2) state, n_first_getting_qs_retries = BEFORE_GETTING_QS, 0 while True: result, notices = common.pg_query_state(config, pid) # run state machine to determine the first getting of query state # and query finishing if state == BEFORE_GETTING_QS: if len(result ) > 0 or common.BACKEND_IS_ACTIVE_INFO in notices: state = GETTING_QS continue n_first_getting_qs_retries += 1 if n_first_getting_qs_retries >= MAX_FIRST_GETTING_QS_RETRIES: # pg_query_state callings don't return any result, more likely run # query has completed break time.sleep(BEFORE_GETTING_QS_DELAY) elif state == GETTING_QS: if common.BACKEND_IS_IDLE_INFO in notices: break time.sleep(PG_QS_DELAY) # wait for real query completion common.wait(acon) except psycopg2.extensions.QueryCanceledError: timeout_list.append(i + 1) common.n_close((acon, )) if len(timeout_list) > 0: print( '\nThere were pg_query_state timeouts (%s s) on queries:' % TPC_DS_STATEMENT_TIMEOUT, timeout_list)
def get_pid(logfile): # Wait until the script has written its PID to the logfile wait(lambda: os.path.exists(logfile), timeout=5) with open(logfile, 'r') as f: return int(f.read())
led.on() try: step = uio.open("/step.txt").read().strip() except: step = "welcome" if step == "welcome": # they're just starting, so move for them import welcome welcome.start() else: oled_page( "Welcome back!", "Connect using", "screen", " /dev/tty.usb*") wait("Press black button") print(""" Welcome back. You can pick up where you were with: >>> import {step} >>> {step}.start() (if you know other step names, feel free to use them) """.format(step=step))