_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q230800
MAVFenceLoader.polygon
train
def polygon(self): '''return a polygon for the fence''' points = [] for fp in self.points[1:]: points.append((fp.lat, fp.lng)) return points
python
{ "resource": "" }
q230801
add_input
train
def add_input(cmd, immediate=False): '''add some command input to be processed''' if immediate: process_stdin(cmd) else: mpstate.input_queue.put(cmd)
python
{ "resource": "" }
q230802
param_set
train
def param_set(name, value, retries=3): '''set a parameter''' name = name.upper() return mpstate.mav_param.mavset(mpstate.master(), name, value, retries=retries)
python
{ "resource": "" }
q230803
unload_module
train
def unload_module(modname): '''unload a module''' for (m,pm) in mpstate.modules: if m.name == modname: if hasattr(m, 'unload'): m.unload() mpstate.modules.remove((m,pm)) print("Unloaded module %s" % modname) return True print("Unable to...
python
{ "resource": "" }
q230804
import_package
train
def import_package(name): """Given a package name like 'foo.bar.quux', imports the package and returns the desired module.""" import zipimport try: mod = __import__(name) except ImportError: clear_zipimport_cache() mod = __import__(name) components = name.split('.') ...
python
{ "resource": "" }
q230805
process_master
train
def process_master(m): '''process packets from the MAVLink master''' try: s = m.recv(16*1024) except Exception: time.sleep(0.1) return # prevent a dead serial port from causing the CPU to spin. The user hitting enter will # cause it to try and reconnect if len(s) == 0: ...
python
{ "resource": "" }
q230806
set_stream_rates
train
def set_stream_rates(): '''set mavlink stream rates''' if (not msg_period.trigger() and mpstate.status.last_streamrate1 == mpstate.settings.streamrate and mpstate.status.last_streamrate2 == mpstate.settings.streamrate2): return mpstate.status.last_streamrate1 = mpstate.settings.strea...
python
{ "resource": "" }
q230807
periodic_tasks
train
def periodic_tasks(): '''run periodic checks''' if mpstate.status.setup_mode: return if (mpstate.settings.compdebug & 2) != 0: return if mpstate.settings.heartbeat != 0: heartbeat_period.frequency = mpstate.settings.heartbeat if heartbeat_period.trigger() and mpstate.setti...
python
{ "resource": "" }
q230808
MPState.master
train
def master(self): '''return the currently chosen mavlink master object''' if len(self.mav_master) == 0: return None if self.settings.link > len(self.mav_master): self.settings.link = 1 # try to use one with no link error if not self.mav_master[self.setti...
python
{ "resource": "" }
q230809
generate
train
def generate(basename, xml): '''generate complete MAVLink CSharp implemenation''' structsfilename = basename + '.generated.cs' msgs = [] enums = [] filelist = [] for x in xml: msgs.extend(x.message) enums.extend(x.enum) filelist.append(os.path.basename(x.filename)) ...
python
{ "resource": "" }
q230810
load_stylesheet
train
def load_stylesheet(pyside=True): """ Loads the stylesheet. Takes care of importing the rc module. :param pyside: True to load the pyside rc file, False to load the PyQt rc file :return the stylesheet string """ # Smart import of the rc file if pyside: import qdarkstyle.pyside_styl...
python
{ "resource": "" }
q230811
load_stylesheet_pyqt5
train
def load_stylesheet_pyqt5(): """ Loads the stylesheet for use in a pyqt5 application. :param pyside: True to load the pyside rc file, False to load the PyQt rc file :return the stylesheet string """ # Smart import of the rc file import qdarkstyle.pyqt5_style_rc # Load the stylesheet c...
python
{ "resource": "" }
q230812
MPMenuItem.call_handler
train
def call_handler(self): '''optionally call a handler function''' if self.handler is None: return call = getattr(self.handler, 'call', None) if call is not None: self.handler_result = call()
python
{ "resource": "" }
q230813
MPMenuTop.add
train
def add(self, items): '''add a submenu''' if not isinstance(items, list): items = [items] for m in items: updated = False for i in range(len(self.items)): if self.items[i].name == m.name: self.items[i] = m ...
python
{ "resource": "" }
q230814
MPMenuChildMessageDialog.call
train
def call(self): '''show the dialog as a child process''' mp_util.child_close_fds() import wx_processguard from wx_loader import wx from wx.lib.agw.genericmessagedialog import GenericMessageDialog app = wx.App(False) # note! font size change is not working. I don't...
python
{ "resource": "" }
q230815
ERMap.read_ermapper
train
def read_ermapper(self, ifile): '''Read in a DEM file and associated .ers file''' ers_index = ifile.find('.ers') if ers_index > 0: data_file = ifile[0:ers_index] header_file = ifile else: data_file = ifile header_file = ifile + '.ers' ...
python
{ "resource": "" }
q230816
ERMap.printBoundingBox
train
def printBoundingBox(self): '''Print the bounding box that this DEM covers''' print ("Bounding Latitude: ") print (self.startlatitude) print (self.endlatitude) print ("Bounding Longitude: ") print (self.startlongitude) print (self.endlongitude)
python
{ "resource": "" }
q230817
ERMap.getPercentBlank
train
def getPercentBlank(self): '''Print how many null cells are in the DEM - Quality measure''' blank = 0 nonblank = 0 for x in self.data.flat: if x == -99999.0: blank = blank + 1 else: nonblank = nonblank + 1 print ("Blank til...
python
{ "resource": "" }
q230818
RCModule.send_rc_override
train
def send_rc_override(self): '''send RC override packet''' if self.sitl_output: buf = struct.pack('<HHHHHHHH', *self.override) self.sitl_output.write(buf) else: self.master.mav.rc_channels_override_send(self.target_system, ...
python
{ "resource": "" }
q230819
RCModule.cmd_switch
train
def cmd_switch(self, args): '''handle RC switch changes''' mapping = [ 0, 1165, 1295, 1425, 1555, 1685, 1815 ] if len(args) != 1: print("Usage: switch <pwmvalue>") return value = int(args[0]) if value < 0 or value > 6: print("Invalid switch val...
python
{ "resource": "" }
q230820
write_NetCDF_georeference
train
def write_NetCDF_georeference(origin, outfile): """Write georeference info to a netcdf file, usually sww. The origin can be a georef instance or parameters for a geo_ref instance outfile is the name of the file to be written to. """ geo_ref = ensure_geo_reference(origin) geo_ref.write_NetCDF(...
python
{ "resource": "" }
q230821
Geo_reference.is_absolute
train
def is_absolute(self): """Return True if xllcorner==yllcorner==0 indicating that points in question are absolute. """ # FIXME(Ole): It is unfortunate that decision about whether points # are absolute or not lies with the georeference object. Ross pointed this out. # More...
python
{ "resource": "" }
q230822
mkdir_p
train
def mkdir_p(dir): '''like mkdir -p''' if not dir: return if dir.endswith("/") or dir.endswith("\\"): mkdir_p(dir[:-1]) return if os.path.isdir(dir): return mkdir_p(os.path.dirname(dir)) try: os.mkdir(dir) except Exception: pass
python
{ "resource": "" }
q230823
polygon_load
train
def polygon_load(filename): '''load a polygon from a file''' ret = [] f = open(filename) for line in f: if line.startswith('#'): continue line = line.strip() if not line: continue a = line.split() if len(a) != 2: raise RuntimeEr...
python
{ "resource": "" }
q230824
bounds_overlap
train
def bounds_overlap(bound1, bound2): '''return true if two bounding boxes overlap''' (x1,y1,w1,h1) = bound1 (x2,y2,w2,h2) = bound2 if x1+w1 < x2: return False if x2+w2 < x1: return False if y1+h1 < y2: return False if y2+h2 < y1: return False return True
python
{ "resource": "" }
q230825
latlon_to_grid
train
def latlon_to_grid(latlon): '''convert to grid reference''' from MAVProxy.modules.lib.ANUGA import redfearn (zone, easting, northing) = redfearn.redfearn(latlon[0], latlon[1]) if latlon[0] < 0: hemisphere = 'S' else: hemisphere = 'N' return UTMGrid(zone, easting, northing, hemisp...
python
{ "resource": "" }
q230826
latlon_round
train
def latlon_round(latlon, spacing=1000): '''round to nearest grid corner''' g = latlon_to_grid(latlon) g.easting = (g.easting // spacing) * spacing g.northing = (g.northing // spacing) * spacing return g.latlon()
python
{ "resource": "" }
q230827
wxToPIL
train
def wxToPIL(wimg): '''convert a wxImage to a PIL Image''' from PIL import Image (w,h) = wimg.GetSize() d = wimg.GetData() pimg = Image.new("RGB", (w,h), color=1) pimg.fromstring(d) return pimg
python
{ "resource": "" }
q230828
child_close_fds
train
def child_close_fds(): '''close file descriptors that a child process should not inherit. Should be called from child processes.''' global child_fd_list import os while len(child_fd_list) > 0: fd = child_fd_list.pop(0) try: os.close(fd) except Exception as msg:...
python
{ "resource": "" }
q230829
snapshot_folder
train
def snapshot_folder(): """ Use the commit date in UTC as folder name """ logger.info("Snapshot folder") try: stdout = subprocess.check_output(["git", "show", "-s", "--format=%cI", "HEAD"]) except subprocess.CalledProcessError as e: logger.error("Error: {}".format(e.output.decode(...
python
{ "resource": "" }
q230830
opengraph_get
train
def opengraph_get(html, prop): """ Extract specified OpenGraph property from html. >>> opengraph_get('<html><head><meta property="og:image" content="http://example.com/img.jpg"><meta ...', "image") 'http://example.com/img.jpg' >>> opengraph_get('<html><head><meta content="http://example...
python
{ "resource": "" }
q230831
decode_html_entities
train
def decode_html_entities(s): """ Replaces html entities with the character they represent. >>> print(decode_html_entities("&lt;3 &amp;")) <3 & """ parser = HTMLParser.HTMLParser() def unesc(m): return parser.unescape(m.group()) return re.sub(r'(&[^;]+;)', unesc, ensure_...
python
{ "resource": "" }
q230832
filenamify
train
def filenamify(title): """ Convert a string to something suitable as a file name. E.g. Matlagning del 1 av 10 - Räksmörgås | SVT Play -> matlagning.del.1.av.10.-.raksmorgas.svt.play """ # ensure it is unicode title = ensure_unicode(title) # NFD decomposes chars into base char and ...
python
{ "resource": "" }
q230833
HTTP.download
train
def download(self): """ Get the stream from HTTP """ _, ext = os.path.splitext(self.url) if ext == ".mp3": self.output_extention = "mp3" else: self.output_extention = "mp4" # this might be wrong.. data = self.http.request("get", self.url, stream=True) ...
python
{ "resource": "" }
q230834
progress
train
def progress(byte, total, extra=""): """ Print some info about how much we have downloaded """ if total == 0: progresstr = "Downloaded %dkB bytes" % (byte >> 10) progress_stream.write(progresstr + '\r') return progressbar(total, byte, extra)
python
{ "resource": "" }
q230835
ETA.update
train
def update(self, pos): """ Set new absolute progress position. Parameters: pos: new absolute progress """ self.pos = pos self.now = time.time()
python
{ "resource": "" }
q230836
Graph_UI.check_xlim_change
train
def check_xlim_change(self): '''check for new X bounds''' if self.xlim_pipe is None: return None xlim = None while self.xlim_pipe[0].poll(): try: xlim = self.xlim_pipe[0].recv() except EOFError: return None if xl...
python
{ "resource": "" }
q230837
Graph_UI.set_xlim
train
def set_xlim(self, xlim): '''set new X bounds''' if self.xlim_pipe is not None and self.xlim != xlim: #print("send0: ", graph_count, xlim) try: self.xlim_pipe[0].send(xlim) except IOError: return False self.xlim = xlim ...
python
{ "resource": "" }
q230838
SerialModule.serial_lock
train
def serial_lock(self, lock): '''lock or unlock the port''' mav = self.master.mav if lock: flags = mavutil.mavlink.SERIAL_CONTROL_FLAG_EXCLUSIVE self.locked = True else: flags = 0 self.locked = False mav.serial_control_send(self.seri...
python
{ "resource": "" }
q230839
SerialModule.cmd_serial
train
def cmd_serial(self, args): '''serial control commands''' usage = "Usage: serial <lock|unlock|set|send>" if len(args) < 1: print(usage) return if args[0] == "lock": self.serial_lock(True) elif args[0] == "unlock": self.serial_lock(F...
python
{ "resource": "" }
q230840
MPTile.downloader
train
def downloader(self): '''the download thread''' while self.tiles_pending() > 0: time.sleep(self.tile_delay) keys = sorted(self._download_pending.keys()) # work out which one to download next, choosing by request_time tile_info = self._download_pending[ke...
python
{ "resource": "" }
q230841
FirmwareModule.cmd_fw
train
def cmd_fw(self, args): '''execute command defined in args''' if len(args) == 0: print(self.usage()) return rest = args[1:] if args[0] == "manifest": self.cmd_fw_manifest(rest) elif args[0] == "list": self.cmd_fw_list(rest) ...
python
{ "resource": "" }
q230842
FirmwareModule.frame_from_firmware
train
def frame_from_firmware(self, firmware): '''extract information from firmware, return pretty string to user''' # see Tools/scripts/generate-manifest for this map: frame_to_mavlink_dict = { "quad": "QUADROTOR", "hexa": "HEXAROTOR", "y6": "ARDUPILOT_Y6", ...
python
{ "resource": "" }
q230843
FirmwareModule.row_is_filtered
train
def row_is_filtered(self, row_subs, filters): '''returns True if row should NOT be included according to filters''' for filtername in filters: filtervalue = filters[filtername] if filtername in row_subs: row_subs_value = row_subs[filtername] if str...
python
{ "resource": "" }
q230844
FirmwareModule.filters_from_args
train
def filters_from_args(self, args): '''take any argument of the form name=value anmd put it into a dict; return that and the remaining arguments''' filters = dict() remainder = [] for arg in args: try: equals = arg.index('=') # anything ofthe fo...
python
{ "resource": "" }
q230845
FirmwareModule.all_firmwares
train
def all_firmwares(self): ''' return firmware entries from all manifests''' all = [] for manifest in self.manifests: for firmware in manifest["firmware"]: all.append(firmware) return all
python
{ "resource": "" }
q230846
FirmwareModule.rows_for_firmwares
train
def rows_for_firmwares(self, firmwares): '''provide user-readable text for a firmware entry''' rows = [] i = 0 for firmware in firmwares: frame = self.frame_from_firmware(firmware) row = { "seq": i, "platform": firmware["platform"],...
python
{ "resource": "" }
q230847
FirmwareModule.filter_rows
train
def filter_rows(self, filters, rows): '''returns rows as filtered by filters''' ret = [] for row in rows: if not self.row_is_filtered(row, filters): ret.append(row) return ret
python
{ "resource": "" }
q230848
FirmwareModule.filtered_rows_from_args
train
def filtered_rows_from_args(self, args): '''extracts filters from args, rows from manifests, returns filtered rows''' if len(self.manifests) == 0: print("fw: No manifests downloaded. Try 'manifest download'") return None (filters,remainder) = self.filters_from_args(args...
python
{ "resource": "" }
q230849
FirmwareModule.cmd_fw_list
train
def cmd_fw_list(self, args): '''cmd handler for list''' stuff = self.filtered_rows_from_args(args) if stuff is None: return (filtered, remainder) = stuff print("") print(" seq platform frame major.minor.patch releasetype latest git-sha format") for ...
python
{ "resource": "" }
q230850
FirmwareModule.cmd_fw_download
train
def cmd_fw_download(self, args): '''cmd handler for downloading firmware''' stuff = self.filtered_rows_from_args(args) if stuff is None: return (filtered, remainder) = stuff if len(filtered) == 0: print("fw: No firmware specified") return ...
python
{ "resource": "" }
q230851
FirmwareModule.find_manifests
train
def find_manifests(self): '''locate manifests and return filepaths thereof''' manifest_dir = mp_util.dot_mavproxy() ret = [] for file in os.listdir(manifest_dir): try: file.index("manifest") ret.append(os.path.join(manifest_dir,file)) ...
python
{ "resource": "" }
q230852
FirmwareModule.cmd_fw_manifest_purge
train
def cmd_fw_manifest_purge(self): '''remove all downloaded manifests''' for filepath in self.find_manifests(): os.unlink(filepath) self.manifests_parse()
python
{ "resource": "" }
q230853
FirmwareModule.cmd_fw_manifest
train
def cmd_fw_manifest(self, args): '''cmd handler for manipulating manifests''' if len(args) == 0: print(self.fw_manifest_usage()) return rest = args[1:] if args[0] == "download": return self.manifest_download() if args[0] == "list": ...
python
{ "resource": "" }
q230854
FirmwareModule.manifest_parse
train
def manifest_parse(self, path): '''parse manifest at path, return JSON object''' print("fw: parsing manifests") content = open(path).read() return json.loads(content)
python
{ "resource": "" }
q230855
FirmwareModule.manifest_path_is_old
train
def manifest_path_is_old(self, path): '''return true if path is more than a day old''' mtime = os.path.getmtime(path) return (time.time() - mtime) > 24*60*60
python
{ "resource": "" }
q230856
FirmwareModule.manifests_parse
train
def manifests_parse(self): '''parse manifests present on system''' self.manifests = [] for manifest_path in self.find_manifests(): if self.manifest_path_is_old(manifest_path): print("fw: Manifest (%s) is old; consider 'manifest download'" % (manifest_path)) ...
python
{ "resource": "" }
q230857
FirmwareModule.make_safe_filename_from_url
train
def make_safe_filename_from_url(self, url): '''return a version of url safe for use as a filename''' r = re.compile("([^a-zA-Z0-9_.-])") filename = r.sub(lambda m : "%" + str(hex(ord(str(m.group(1))))).upper(), url) return filename
python
{ "resource": "" }
q230858
FirmwareModule.manifest_download
train
def manifest_download(self): '''download manifest files''' if self.downloaders_lock.acquire(False): if len(self.downloaders): # there already exist downloader threads self.downloaders_lock.release() return for url in ['http://firmw...
python
{ "resource": "" }
q230859
colour_for_point
train
def colour_for_point(mlog, point, instance, options): global colour_expression_exceptions, colour_source_max, colour_source_min '''indicate a colour to be used to plot point''' source = getattr(options, "colour_source", "flightmode") if source == "flightmode": return colour_for_point_flightmode(...
python
{ "resource": "" }
q230860
mavlink_to_json
train
def mavlink_to_json(msg): '''Translate mavlink python messages in json string''' ret = '\"%s\": {' % msg._type for fieldname in msg._fieldnames: data = getattr(msg, fieldname) ret += '\"%s\" : \"%s\", ' % (fieldname, data) ret = ret[0:-2] + '}' return ret
python
{ "resource": "" }
q230861
mpstatus_to_json
train
def mpstatus_to_json(status): '''Translate MPStatus in json string''' msg_keys = list(status.msgs.keys()) data = '{' for key in msg_keys[:-1]: data += mavlink_to_json(status.msgs[key]) + ',' data += mavlink_to_json(status.msgs[msg_keys[-1]]) data += '}' return data
python
{ "resource": "" }
q230862
RestServer.set_ip_port
train
def set_ip_port(self, ip, port): '''set ip and port''' self.address = ip self.port = port self.stop() self.start()
python
{ "resource": "" }
q230863
RestServer.request
train
def request(self, arg=None): '''Deal with requests''' if not self.status: return '{"result": "No message"}' try: status_dict = json.loads(mpstatus_to_json(self.status)) except Exception as e: print(e) return # If no key, send the ...
python
{ "resource": "" }
q230864
BatteryModule.power_status_update
train
def power_status_update(self, POWER_STATUS): '''update POWER_STATUS warnings level''' now = time.time() Vservo = POWER_STATUS.Vservo * 0.001 Vcc = POWER_STATUS.Vcc * 0.001 self.high_servo_voltage = max(self.high_servo_voltage, Vservo) if self.high_servo_voltage > 1 and Vs...
python
{ "resource": "" }
q230865
GasHeliModule.valid_starter_settings
train
def valid_starter_settings(self): '''check starter settings''' if self.gasheli_settings.ignition_chan <= 0 or self.gasheli_settings.ignition_chan > 8: print("Invalid ignition channel %d" % self.gasheli_settings.ignition_chan) return False if self.gasheli_settings.starter_...
python
{ "resource": "" }
q230866
GasHeliModule.cmd_gasheli
train
def cmd_gasheli(self, args): '''gas help commands''' usage = "Usage: gasheli <start|stop|set>" if len(args) < 1: print(usage) return if args[0] == "start": self.start_motor() elif args[0] == "stop": self.stop_motor() elif ar...
python
{ "resource": "" }
q230867
WPModule.wploader
train
def wploader(self): '''per-sysid wploader''' if self.target_system not in self.wploader_by_sysid: self.wploader_by_sysid[self.target_system] = mavwp.MAVWPLoader() return self.wploader_by_sysid[self.target_system]
python
{ "resource": "" }
q230868
WPModule.send_wp_requests
train
def send_wp_requests(self, wps=None): '''send some more WP requests''' if wps is None: wps = self.missing_wps_to_request() tnow = time.time() for seq in wps: #print("REQUESTING %u/%u (%u)" % (seq, self.wploader.expected_count, i)) self.wp_requested[seq...
python
{ "resource": "" }
q230869
WPModule.wp_status
train
def wp_status(self): '''show status of wp download''' try: print("Have %u of %u waypoints" % (self.wploader.count()+len(self.wp_received), self.wploader.expected_count)) except Exception: print("Have %u waypoints" % (self.wploader.count()+len(self.wp_received)))
python
{ "resource": "" }
q230870
WPModule.wp_slope
train
def wp_slope(self): '''show slope of waypoints''' last_w = None for i in range(1, self.wploader.count()): w = self.wploader.wp(i) if w.command not in [mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, mavutil.mavlink.MAV_CMD_NAV_LAND]: continue if last_w i...
python
{ "resource": "" }
q230871
WPModule.save_waypoints_csv
train
def save_waypoints_csv(self, filename): '''save waypoints to a file in a human readable CSV file''' try: #need to remove the leading and trailing quotes in filename self.wploader.savecsv(filename.strip('"')) except Exception as msg: print("Failed to save %s - ...
python
{ "resource": "" }
q230872
WPModule.get_home
train
def get_home(self): '''get home location''' if 'HOME_POSITION' in self.master.messages: h = self.master.messages['HOME_POSITION'] return mavutil.mavlink.MAVLink_mission_item_message(self.target_system, self.target_co...
python
{ "resource": "" }
q230873
WPModule.nofly_add
train
def nofly_add(self): '''add a square flight exclusion zone''' try: latlon = self.module('map').click_position except Exception: print("No position chosen") return loader = self.wploader (center_lat, center_lon) = latlon points = [] ...
python
{ "resource": "" }
q230874
WPModule.cmd_wp_changealt
train
def cmd_wp_changealt(self, args): '''handle wp change target alt of multiple waypoints''' if len(args) < 2: print("usage: wp changealt WPNUM NEWALT <NUMWP>") return idx = int(args[0]) if idx < 1 or idx > self.wploader.count(): print("Invalid wp number ...
python
{ "resource": "" }
q230875
WPModule.cmd_wp_remove
train
def cmd_wp_remove(self, args): '''handle wp remove''' if len(args) != 1: print("usage: wp remove WPNUM") return idx = int(args[0]) if idx < 0 or idx >= self.wploader.count(): print("Invalid wp number %u" % idx) return wp = self.wplo...
python
{ "resource": "" }
q230876
WPModule.cmd_wp_undo
train
def cmd_wp_undo(self): '''handle wp undo''' if self.undo_wp_idx == -1 or self.undo_wp is None: print("No undo information") return wp = self.undo_wp if self.undo_type == 'move': wp.target_system = self.target_system wp.target_component =...
python
{ "resource": "" }
q230877
WPModule.csv_line
train
def csv_line(self, line): '''turn a list of values into a CSV line''' self.csv_sep = "," return self.csv_sep.join(['"' + str(x) + '"' for x in line])
python
{ "resource": "" }
q230878
WPModule.savecsv
train
def savecsv(self, filename): '''save waypoints to a file in human-readable CSV file''' f = open(filename, mode='w') headers = ["Seq", "Frame", "Cmd", "P1", "P2", "P3", "P4", "X", "Y", "Z"] print(self.csv_line(headers)) f.write(self.csv_line(headers) + "\n") for w in self....
python
{ "resource": "" }
q230879
list_joysticks
train
def list_joysticks(): '''Print a list of available joysticks''' print('Available joysticks:') print() for jid in range(pygame.joystick.get_count()): j = pygame.joystick.Joystick(jid) print('({}) {}'.format(jid, j.get_name()))
python
{ "resource": "" }
q230880
select_joystick
train
def select_joystick(): '''Allow user to select a joystick from a menu''' list_joysticks() while True: print('Select a joystick (L to list, Q to quit)'), choice = sys.stdin.readline().strip() if choice.lower() == 'l': list_joysticks() elif choice.lower() == 'q':...
python
{ "resource": "" }
q230881
select
train
def select(versions, optionsRequired=False): """ Search for a wxPython installation that matches version. If one is found then sys.path is modified so that version will be imported with a 'import wx', otherwise a VersionError exception is raised. This function should only be called once at the beg...
python
{ "resource": "" }
q230882
ensureMinimal
train
def ensureMinimal(minVersion, optionsRequired=False): """ Checks to see if the default version of wxPython is greater-than or equal to `minVersion`. If not then it will try to find an installed version that is >= minVersion. If none are available then a message is displayed that will inform the us...
python
{ "resource": "" }
q230883
checkInstalled
train
def checkInstalled(versions, optionsRequired=False): """ Check if there is a version of wxPython installed that matches one of the versions given. Returns True if so, False if not. This can be used to determine if calling `select` will succeed or not. :param versions: Same as in `select`, eit...
python
{ "resource": "" }
q230884
getInstalled
train
def getInstalled(): """ Returns a list of strings representing the installed wxPython versions that are found on the system. """ installed = _find_installed() return [os.path.basename(p.pathname)[3:] for p in installed]
python
{ "resource": "" }
q230885
flightmode_colours
train
def flightmode_colours(): '''return mapping of flight mode to colours''' from MAVProxy.modules.lib.grapher import flightmode_colours mapping = {} idx = 0 for (mode,t0,t1) in flightmodes: if not mode in mapping: mapping[mode] = flightmode_colours[idx] idx += 1 ...
python
{ "resource": "" }
q230886
cmd_fft
train
def cmd_fft(args): '''display fft from log''' from MAVProxy.modules.lib import mav_fft if len(args) > 0: condition = args[0] else: condition = None child = multiproc.Process(target=mav_fft.mavfft_display, args=[mestate.filename,condition]) child.start()
python
{ "resource": "" }
q230887
cmd_save
train
def cmd_save(args): '''save a graph''' child = multiproc.Process(target=save_process, args=[mestate.last_graph, mestate.child_pipe_send_console, mestate.child_pipe_send_graph, mestate.status.msgs]) child.start()
python
{ "resource": "" }
q230888
cmd_loadfile
train
def cmd_loadfile(args): '''callback from menu to load a log file''' if len(args) != 1: fileargs = " ".join(args) else: fileargs = args[0] if not os.path.exists(fileargs): print("Error loading file ", fileargs); return if os.name == 'nt': #convert slashes in Wi...
python
{ "resource": "" }
q230889
GPSInputModule.cmd_port
train
def cmd_port(self, args): 'handle port selection' if len(args) != 1: print("Usage: port <number>") return self.port.close() self.portnum = int(args[0]) self.port = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.port.setsockopt(socke...
python
{ "resource": "" }
q230890
Vehicle.RunScript
train
def RunScript(self, script): ''' Actuate on the vehicle through a script. The script is a sequence of commands. Each command is a sequence with the first element as the command name and the remaining values as parameters. The script is executed asynchronously by a timer with a p...
python
{ "resource": "" }
q230891
PPPModule.ppp_read
train
def ppp_read(self, ppp_fd): '''called from main select loop in mavproxy when the pppd child sends us some data''' buf = os.read(ppp_fd, 100) if len(buf) == 0: # EOF on the child fd self.stop_ppp_link() return print("ppp packet len=%u" % len(buf...
python
{ "resource": "" }
q230892
PPPModule.start_ppp_link
train
def start_ppp_link(self): '''startup the link''' cmd = ['pppd'] cmd.extend(self.command) (self.pid, self.ppp_fd) = pty.fork() if self.pid == 0: os.execvp("pppd", cmd) raise RuntimeError("pppd exited") if self.ppp_fd == -1: print("Failed...
python
{ "resource": "" }
q230893
PPPModule.stop_ppp_link
train
def stop_ppp_link(self): '''stop the link''' if self.ppp_fd == -1: return try: self.mpself.select_extra.pop(self.ppp_fd) os.close(self.ppp_fd) os.waitpid(self.pid, 0) except Exception: pass self.pid = -1 self.ppp...
python
{ "resource": "" }
q230894
PPPModule.cmd_ppp
train
def cmd_ppp(self, args): '''set ppp parameters and start link''' usage = "ppp <command|start|stop>" if len(args) == 0: print(usage) return if args[0] == "command": if len(args) == 1: print("ppp.command=%s" % " ".join(self.command)) ...
python
{ "resource": "" }
q230895
MPModule.module_matching
train
def module_matching(self, name): '''Find a list of modules matching a wildcard pattern''' import fnmatch ret = [] for mname in self.mpstate.public_modules.keys(): if fnmatch.fnmatch(mname, name): ret.append(self.mpstate.public_modules[mname]) return re...
python
{ "resource": "" }
q230896
MPModule.get_time
train
def get_time(self): '''get time, using ATTITUDE.time_boot_ms if in SITL with SIM_SPEEDUP != 1''' systime = time.time() - self.mpstate.start_time_s if not self.mpstate.is_sitl: return systime try: speedup = int(self.get_mav_param('SIM_SPEEDUP',1)) except Ex...
python
{ "resource": "" }
q230897
MPModule.dist_string
train
def dist_string(self, val_meters): '''return a distance as a string''' if self.settings.dist_unit == 'nm': return "%.1fnm" % (val_meters * 0.000539957) if self.settings.dist_unit == 'miles': return "%.1fmiles" % (val_meters * 0.000621371) return "%um" % val_meters
python
{ "resource": "" }
q230898
MPModule.speed_convert_units
train
def speed_convert_units(self, val_ms): '''return a speed in configured units''' if self.settings.speed_unit == 'knots': return val_ms * 1.94384 elif self.settings.speed_unit == 'mph': return val_ms * 2.23694 return val_ms
python
{ "resource": "" }
q230899
MPModule.set_prompt
train
def set_prompt(self, prompt): '''set prompt for command line''' if prompt and self.settings.vehicle_name: # add in optional vehicle name prompt = self.settings.vehicle_name + ':' + prompt self.mpstate.rl.set_prompt(prompt)
python
{ "resource": "" }