repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavwp.py
MAVWPLoader.remove
def remove(self, w): '''remove a waypoint''' self.wpoints.remove(w) self.last_change = time.time() self.reindex()
python
def remove(self, w): '''remove a waypoint''' self.wpoints.remove(w) self.last_change = time.time() self.reindex()
[ "def", "remove", "(", "self", ",", "w", ")", ":", "self", ".", "wpoints", ".", "remove", "(", "w", ")", "self", ".", "last_change", "=", "time", ".", "time", "(", ")", "self", ".", "reindex", "(", ")" ]
remove a waypoint
[ "remove", "a", "waypoint" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavwp.py#L112-L116
train
230,300
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavwp.py
MAVWPLoader._read_waypoints_v100
def _read_waypoints_v100(self, file): '''read a version 100 waypoint''' cmdmap = { 2 : mavutil.mavlink.MAV_CMD_NAV_TAKEOFF, 3 : mavutil.mavlink.MAV_CMD_NAV_RETURN_TO_LAUNCH, 4 : mavutil.mavlink.MAV_CMD_NAV_LAND, 24: mavutil.mavlink.MAV_CMD_NAV_TAKEOFF, 26: mavutil.mavlink.MAV_CMD_NAV_LAND, 25: mavutil.mavlink.MAV_CMD_NAV_WAYPOINT , 27: mavutil.mavlink.MAV_CMD_NAV_LOITER_UNLIM } comment = '' for line in file: if line.startswith('#'): comment = line[1:].lstrip() continue line = line.strip() if not line: continue a = line.split() if len(a) != 13: raise MAVWPError("invalid waypoint line with %u values" % len(a)) if mavutil.mavlink10(): fn = mavutil.mavlink.MAVLink_mission_item_message else: fn = mavutil.mavlink.MAVLink_waypoint_message w = fn(self.target_system, self.target_component, int(a[0]), # seq int(a[1]), # frame int(a[2]), # action int(a[7]), # current int(a[12]), # autocontinue float(a[5]), # param1, float(a[6]), # param2, float(a[3]), # param3 float(a[4]), # param4 float(a[9]), # x, latitude float(a[8]), # y, longitude float(a[10]) # z ) if not w.command in cmdmap: raise MAVWPError("Unknown v100 waypoint action %u" % w.command) w.command = cmdmap[w.command] self.add(w, comment) comment = ''
python
def _read_waypoints_v100(self, file): '''read a version 100 waypoint''' cmdmap = { 2 : mavutil.mavlink.MAV_CMD_NAV_TAKEOFF, 3 : mavutil.mavlink.MAV_CMD_NAV_RETURN_TO_LAUNCH, 4 : mavutil.mavlink.MAV_CMD_NAV_LAND, 24: mavutil.mavlink.MAV_CMD_NAV_TAKEOFF, 26: mavutil.mavlink.MAV_CMD_NAV_LAND, 25: mavutil.mavlink.MAV_CMD_NAV_WAYPOINT , 27: mavutil.mavlink.MAV_CMD_NAV_LOITER_UNLIM } comment = '' for line in file: if line.startswith('#'): comment = line[1:].lstrip() continue line = line.strip() if not line: continue a = line.split() if len(a) != 13: raise MAVWPError("invalid waypoint line with %u values" % len(a)) if mavutil.mavlink10(): fn = mavutil.mavlink.MAVLink_mission_item_message else: fn = mavutil.mavlink.MAVLink_waypoint_message w = fn(self.target_system, self.target_component, int(a[0]), # seq int(a[1]), # frame int(a[2]), # action int(a[7]), # current int(a[12]), # autocontinue float(a[5]), # param1, float(a[6]), # param2, float(a[3]), # param3 float(a[4]), # param4 float(a[9]), # x, latitude float(a[8]), # y, longitude float(a[10]) # z ) if not w.command in cmdmap: raise MAVWPError("Unknown v100 waypoint action %u" % w.command) w.command = cmdmap[w.command] self.add(w, comment) comment = ''
[ "def", "_read_waypoints_v100", "(", "self", ",", "file", ")", ":", "cmdmap", "=", "{", "2", ":", "mavutil", ".", "mavlink", ".", "MAV_CMD_NAV_TAKEOFF", ",", "3", ":", "mavutil", ".", "mavlink", ".", "MAV_CMD_NAV_RETURN_TO_LAUNCH", ",", "4", ":", "mavutil", ...
read a version 100 waypoint
[ "read", "a", "version", "100", "waypoint" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavwp.py#L123-L168
train
230,301
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavwp.py
MAVWPLoader._read_waypoints_v110
def _read_waypoints_v110(self, file): '''read a version 110 waypoint''' comment = '' for line in file: if line.startswith('#'): comment = line[1:].lstrip() continue line = line.strip() if not line: continue a = line.split() if len(a) != 12: raise MAVWPError("invalid waypoint line with %u values" % len(a)) if mavutil.mavlink10(): fn = mavutil.mavlink.MAVLink_mission_item_message else: fn = mavutil.mavlink.MAVLink_waypoint_message w = fn(self.target_system, self.target_component, int(a[0]), # seq int(a[2]), # frame int(a[3]), # command int(a[1]), # current int(a[11]), # autocontinue float(a[4]), # param1, float(a[5]), # param2, float(a[6]), # param3 float(a[7]), # param4 float(a[8]), # x (latitude) float(a[9]), # y (longitude) float(a[10]) # z (altitude) ) if w.command == 0 and w.seq == 0 and self.count() == 0: # special handling for Mission Planner created home wp w.command = mavutil.mavlink.MAV_CMD_NAV_WAYPOINT self.add(w, comment) comment = ''
python
def _read_waypoints_v110(self, file): '''read a version 110 waypoint''' comment = '' for line in file: if line.startswith('#'): comment = line[1:].lstrip() continue line = line.strip() if not line: continue a = line.split() if len(a) != 12: raise MAVWPError("invalid waypoint line with %u values" % len(a)) if mavutil.mavlink10(): fn = mavutil.mavlink.MAVLink_mission_item_message else: fn = mavutil.mavlink.MAVLink_waypoint_message w = fn(self.target_system, self.target_component, int(a[0]), # seq int(a[2]), # frame int(a[3]), # command int(a[1]), # current int(a[11]), # autocontinue float(a[4]), # param1, float(a[5]), # param2, float(a[6]), # param3 float(a[7]), # param4 float(a[8]), # x (latitude) float(a[9]), # y (longitude) float(a[10]) # z (altitude) ) if w.command == 0 and w.seq == 0 and self.count() == 0: # special handling for Mission Planner created home wp w.command = mavutil.mavlink.MAV_CMD_NAV_WAYPOINT self.add(w, comment) comment = ''
[ "def", "_read_waypoints_v110", "(", "self", ",", "file", ")", ":", "comment", "=", "''", "for", "line", "in", "file", ":", "if", "line", ".", "startswith", "(", "'#'", ")", ":", "comment", "=", "line", "[", "1", ":", "]", ".", "lstrip", "(", ")", ...
read a version 110 waypoint
[ "read", "a", "version", "110", "waypoint" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavwp.py#L170-L205
train
230,302
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavwp.py
MAVWPLoader.load
def load(self, filename): '''load waypoints from a file. returns number of waypoints loaded''' f = open(filename, mode='r') version_line = f.readline().strip() if version_line == "QGC WPL 100": readfn = self._read_waypoints_v100 elif version_line == "QGC WPL 110": readfn = self._read_waypoints_v110 elif version_line == "QGC WPL PB 110": readfn = self._read_waypoints_pb_110 else: f.close() raise MAVWPError("Unsupported waypoint format '%s'" % version_line) self.clear() readfn(f) f.close() return len(self.wpoints)
python
def load(self, filename): '''load waypoints from a file. returns number of waypoints loaded''' f = open(filename, mode='r') version_line = f.readline().strip() if version_line == "QGC WPL 100": readfn = self._read_waypoints_v100 elif version_line == "QGC WPL 110": readfn = self._read_waypoints_v110 elif version_line == "QGC WPL PB 110": readfn = self._read_waypoints_pb_110 else: f.close() raise MAVWPError("Unsupported waypoint format '%s'" % version_line) self.clear() readfn(f) f.close() return len(self.wpoints)
[ "def", "load", "(", "self", ",", "filename", ")", ":", "f", "=", "open", "(", "filename", ",", "mode", "=", "'r'", ")", "version_line", "=", "f", ".", "readline", "(", ")", ".", "strip", "(", ")", "if", "version_line", "==", "\"QGC WPL 100\"", ":", ...
load waypoints from a file. returns number of waypoints loaded
[ "load", "waypoints", "from", "a", "file", ".", "returns", "number", "of", "waypoints", "loaded" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavwp.py#L263-L282
train
230,303
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavwp.py
MAVWPLoader.view_indexes
def view_indexes(self, done=None): '''return a list waypoint indexes in view order''' ret = [] if done is None: done = set() idx = 0 # find first point not done yet while idx < self.count(): if not idx in done: break idx += 1 while idx < self.count(): w = self.wp(idx) if idx in done: if w.x != 0 or w.y != 0: ret.append(idx) break done.add(idx) if w.command == mavutil.mavlink.MAV_CMD_DO_JUMP: idx = int(w.param1) w = self.wp(idx) if w.x != 0 or w.y != 0: ret.append(idx) continue if (w.x != 0 or w.y != 0) and self.is_location_command(w.command): ret.append(idx) idx += 1 return ret
python
def view_indexes(self, done=None): '''return a list waypoint indexes in view order''' ret = [] if done is None: done = set() idx = 0 # find first point not done yet while idx < self.count(): if not idx in done: break idx += 1 while idx < self.count(): w = self.wp(idx) if idx in done: if w.x != 0 or w.y != 0: ret.append(idx) break done.add(idx) if w.command == mavutil.mavlink.MAV_CMD_DO_JUMP: idx = int(w.param1) w = self.wp(idx) if w.x != 0 or w.y != 0: ret.append(idx) continue if (w.x != 0 or w.y != 0) and self.is_location_command(w.command): ret.append(idx) idx += 1 return ret
[ "def", "view_indexes", "(", "self", ",", "done", "=", "None", ")", ":", "ret", "=", "[", "]", "if", "done", "is", "None", ":", "done", "=", "set", "(", ")", "idx", "=", "0", "# find first point not done yet", "while", "idx", "<", "self", ".", "count"...
return a list waypoint indexes in view order
[ "return", "a", "list", "waypoint", "indexes", "in", "view", "order" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavwp.py#L330-L359
train
230,304
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavwp.py
MAVWPLoader.polygon
def polygon(self, done=None): '''return a polygon for the waypoints''' indexes = self.view_indexes(done) points = [] for idx in indexes: w = self.wp(idx) points.append((w.x, w.y)) return points
python
def polygon(self, done=None): '''return a polygon for the waypoints''' indexes = self.view_indexes(done) points = [] for idx in indexes: w = self.wp(idx) points.append((w.x, w.y)) return points
[ "def", "polygon", "(", "self", ",", "done", "=", "None", ")", ":", "indexes", "=", "self", ".", "view_indexes", "(", "done", ")", "points", "=", "[", "]", "for", "idx", "in", "indexes", ":", "w", "=", "self", ".", "wp", "(", "idx", ")", "points",...
return a polygon for the waypoints
[ "return", "a", "polygon", "for", "the", "waypoints" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavwp.py#L361-L368
train
230,305
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavwp.py
MAVWPLoader.polygon_list
def polygon_list(self): '''return a list of polygons for the waypoints''' done = set() ret = [] while len(done) != self.count(): p = self.polygon(done) if len(p) > 0: ret.append(p) return ret
python
def polygon_list(self): '''return a list of polygons for the waypoints''' done = set() ret = [] while len(done) != self.count(): p = self.polygon(done) if len(p) > 0: ret.append(p) return ret
[ "def", "polygon_list", "(", "self", ")", ":", "done", "=", "set", "(", ")", "ret", "=", "[", "]", "while", "len", "(", "done", ")", "!=", "self", ".", "count", "(", ")", ":", "p", "=", "self", ".", "polygon", "(", "done", ")", "if", "len", "(...
return a list of polygons for the waypoints
[ "return", "a", "list", "of", "polygons", "for", "the", "waypoints" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavwp.py#L370-L378
train
230,306
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavwp.py
MAVWPLoader.view_list
def view_list(self): '''return a list of polygon indexes lists for the waypoints''' done = set() ret = [] while len(done) != self.count(): p = self.view_indexes(done) if len(p) > 0: ret.append(p) return ret
python
def view_list(self): '''return a list of polygon indexes lists for the waypoints''' done = set() ret = [] while len(done) != self.count(): p = self.view_indexes(done) if len(p) > 0: ret.append(p) return ret
[ "def", "view_list", "(", "self", ")", ":", "done", "=", "set", "(", ")", "ret", "=", "[", "]", "while", "len", "(", "done", ")", "!=", "self", ".", "count", "(", ")", ":", "p", "=", "self", ".", "view_indexes", "(", "done", ")", "if", "len", ...
return a list of polygon indexes lists for the waypoints
[ "return", "a", "list", "of", "polygon", "indexes", "lists", "for", "the", "waypoints" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavwp.py#L380-L388
train
230,307
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavwp.py
MAVRallyLoader.reindex
def reindex(self): '''reset counters and indexes''' for i in range(self.rally_count()): self.rally_points[i].count = self.rally_count() self.rally_points[i].idx = i self.last_change = time.time()
python
def reindex(self): '''reset counters and indexes''' for i in range(self.rally_count()): self.rally_points[i].count = self.rally_count() self.rally_points[i].idx = i self.last_change = time.time()
[ "def", "reindex", "(", "self", ")", ":", "for", "i", "in", "range", "(", "self", ".", "rally_count", "(", ")", ")", ":", "self", ".", "rally_points", "[", "i", "]", ".", "count", "=", "self", ".", "rally_count", "(", ")", "self", ".", "rally_points...
reset counters and indexes
[ "reset", "counters", "and", "indexes" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavwp.py#L412-L417
train
230,308
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavwp.py
MAVRallyLoader.append_rally_point
def append_rally_point(self, p): '''add rallypoint to end of list''' if (self.rally_count() > 9): print("Can't have more than 10 rally points, not adding.") return self.rally_points.append(p) self.reindex()
python
def append_rally_point(self, p): '''add rallypoint to end of list''' if (self.rally_count() > 9): print("Can't have more than 10 rally points, not adding.") return self.rally_points.append(p) self.reindex()
[ "def", "append_rally_point", "(", "self", ",", "p", ")", ":", "if", "(", "self", ".", "rally_count", "(", ")", ">", "9", ")", ":", "print", "(", "\"Can't have more than 10 rally points, not adding.\"", ")", "return", "self", ".", "rally_points", ".", "append",...
add rallypoint to end of list
[ "add", "rallypoint", "to", "end", "of", "list" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavwp.py#L419-L426
train
230,309
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavwp.py
MAVRallyLoader.load
def load(self, filename): '''load rally and rally_land points from a file. returns number of points loaded''' f = open(filename, mode='r') self.clear() for line in f: if line.startswith('#'): continue line = line.strip() if not line: continue a = line.split() if len(a) != 7: raise MAVRallyError("invalid rally file line: %s" % line) if (a[0].lower() == "rally"): self.create_and_append_rally_point(float(a[1]) * 1e7, float(a[2]) * 1e7, float(a[3]), float(a[4]), float(a[5]) * 100.0, int(a[6])) f.close() return len(self.rally_points)
python
def load(self, filename): '''load rally and rally_land points from a file. returns number of points loaded''' f = open(filename, mode='r') self.clear() for line in f: if line.startswith('#'): continue line = line.strip() if not line: continue a = line.split() if len(a) != 7: raise MAVRallyError("invalid rally file line: %s" % line) if (a[0].lower() == "rally"): self.create_and_append_rally_point(float(a[1]) * 1e7, float(a[2]) * 1e7, float(a[3]), float(a[4]), float(a[5]) * 100.0, int(a[6])) f.close() return len(self.rally_points)
[ "def", "load", "(", "self", ",", "filename", ")", ":", "f", "=", "open", "(", "filename", ",", "mode", "=", "'r'", ")", "self", ".", "clear", "(", ")", "for", "line", "in", "f", ":", "if", "line", ".", "startswith", "(", "'#'", ")", ":", "conti...
load rally and rally_land points from a file. returns number of points loaded
[ "load", "rally", "and", "rally_land", "points", "from", "a", "file", ".", "returns", "number", "of", "points", "loaded" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavwp.py#L466-L485
train
230,310
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavwp.py
MAVFenceLoader.load
def load(self, filename): '''load points from a file. returns number of points loaded''' f = open(filename, mode='r') self.clear() for line in f: if line.startswith('#'): continue line = line.strip() if not line: continue a = line.split() if len(a) != 2: raise MAVFenceError("invalid fence point line: %s" % line) self.add_latlon(float(a[0]), float(a[1])) f.close() return len(self.points)
python
def load(self, filename): '''load points from a file. returns number of points loaded''' f = open(filename, mode='r') self.clear() for line in f: if line.startswith('#'): continue line = line.strip() if not line: continue a = line.split() if len(a) != 2: raise MAVFenceError("invalid fence point line: %s" % line) self.add_latlon(float(a[0]), float(a[1])) f.close() return len(self.points)
[ "def", "load", "(", "self", ",", "filename", ")", ":", "f", "=", "open", "(", "filename", ",", "mode", "=", "'r'", ")", "self", ".", "clear", "(", ")", "for", "line", "in", "f", ":", "if", "line", ".", "startswith", "(", "'#'", ")", ":", "conti...
load points from a file. returns number of points loaded
[ "load", "points", "from", "a", "file", ".", "returns", "number", "of", "points", "loaded" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavwp.py#L543-L559
train
230,311
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavwp.py
MAVFenceLoader.move
def move(self, i, lat, lng, change_time=True): '''move a fence point''' if i < 0 or i >= self.count(): print("Invalid fence point number %u" % i) self.points[i].lat = lat self.points[i].lng = lng # ensure we close the polygon if i == 1: self.points[self.count()-1].lat = lat self.points[self.count()-1].lng = lng if i == self.count() - 1: self.points[1].lat = lat self.points[1].lng = lng if change_time: self.last_change = time.time()
python
def move(self, i, lat, lng, change_time=True): '''move a fence point''' if i < 0 or i >= self.count(): print("Invalid fence point number %u" % i) self.points[i].lat = lat self.points[i].lng = lng # ensure we close the polygon if i == 1: self.points[self.count()-1].lat = lat self.points[self.count()-1].lng = lng if i == self.count() - 1: self.points[1].lat = lat self.points[1].lng = lng if change_time: self.last_change = time.time()
[ "def", "move", "(", "self", ",", "i", ",", "lat", ",", "lng", ",", "change_time", "=", "True", ")", ":", "if", "i", "<", "0", "or", "i", ">=", "self", ".", "count", "(", ")", ":", "print", "(", "\"Invalid fence point number %u\"", "%", "i", ")", ...
move a fence point
[ "move", "a", "fence", "point" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavwp.py#L568-L582
train
230,312
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavwp.py
MAVFenceLoader.remove
def remove(self, i, change_time=True): '''remove a fence point''' if i < 0 or i >= self.count(): print("Invalid fence point number %u" % i) self.points.pop(i) # ensure we close the polygon if i == 1: self.points[self.count()-1].lat = self.points[1].lat self.points[self.count()-1].lng = self.points[1].lng if i == self.count(): self.points[1].lat = self.points[self.count()-1].lat self.points[1].lng = self.points[self.count()-1].lng if change_time: self.last_change = time.time()
python
def remove(self, i, change_time=True): '''remove a fence point''' if i < 0 or i >= self.count(): print("Invalid fence point number %u" % i) self.points.pop(i) # ensure we close the polygon if i == 1: self.points[self.count()-1].lat = self.points[1].lat self.points[self.count()-1].lng = self.points[1].lng if i == self.count(): self.points[1].lat = self.points[self.count()-1].lat self.points[1].lng = self.points[self.count()-1].lng if change_time: self.last_change = time.time()
[ "def", "remove", "(", "self", ",", "i", ",", "change_time", "=", "True", ")", ":", "if", "i", "<", "0", "or", "i", ">=", "self", ".", "count", "(", ")", ":", "print", "(", "\"Invalid fence point number %u\"", "%", "i", ")", "self", ".", "points", "...
remove a fence point
[ "remove", "a", "fence", "point" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavwp.py#L584-L597
train
230,313
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavwp.py
MAVFenceLoader.polygon
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
def polygon(self): '''return a polygon for the fence''' points = [] for fp in self.points[1:]: points.append((fp.lat, fp.lng)) return points
[ "def", "polygon", "(", "self", ")", ":", "points", "=", "[", "]", "for", "fp", "in", "self", ".", "points", "[", "1", ":", "]", ":", "points", ".", "append", "(", "(", "fp", ".", "lat", ",", "fp", ".", "lng", ")", ")", "return", "points" ]
return a polygon for the fence
[ "return", "a", "polygon", "for", "the", "fence" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavwp.py#L599-L604
train
230,314
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/mavproxy.py
add_input
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
def add_input(cmd, immediate=False): '''add some command input to be processed''' if immediate: process_stdin(cmd) else: mpstate.input_queue.put(cmd)
[ "def", "add_input", "(", "cmd", ",", "immediate", "=", "False", ")", ":", "if", "immediate", ":", "process_stdin", "(", "cmd", ")", "else", ":", "mpstate", ".", "input_queue", ".", "put", "(", "cmd", ")" ]
add some command input to be processed
[ "add", "some", "command", "input", "to", "be", "processed" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/mavproxy.py#L122-L127
train
230,315
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/mavproxy.py
param_set
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
def param_set(name, value, retries=3): '''set a parameter''' name = name.upper() return mpstate.mav_param.mavset(mpstate.master(), name, value, retries=retries)
[ "def", "param_set", "(", "name", ",", "value", ",", "retries", "=", "3", ")", ":", "name", "=", "name", ".", "upper", "(", ")", "return", "mpstate", ".", "mav_param", ".", "mavset", "(", "mpstate", ".", "master", "(", ")", ",", "name", ",", "value"...
set a parameter
[ "set", "a", "parameter" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/mavproxy.py#L242-L245
train
230,316
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/mavproxy.py
unload_module
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 find module %s" % modname) return False
python
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 find module %s" % modname) return False
[ "def", "unload_module", "(", "modname", ")", ":", "for", "(", "m", ",", "pm", ")", "in", "mpstate", ".", "modules", ":", "if", "m", ".", "name", "==", "modname", ":", "if", "hasattr", "(", "m", ",", "'unload'", ")", ":", "m", ".", "unload", "(", ...
unload a module
[ "unload", "a", "module" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/mavproxy.py#L313-L323
train
230,317
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/mavproxy.py
import_package
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('.') for comp in components[1:]: mod = getattr(mod, comp) return mod
python
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('.') for comp in components[1:]: mod = getattr(mod, comp) return mod
[ "def", "import_package", "(", "name", ")", ":", "import", "zipimport", "try", ":", "mod", "=", "__import__", "(", "name", ")", "except", "ImportError", ":", "clear_zipimport_cache", "(", ")", "mod", "=", "__import__", "(", "name", ")", "components", "=", "...
Given a package name like 'foo.bar.quux', imports the package and returns the desired module.
[ "Given", "a", "package", "name", "like", "foo", ".", "bar", ".", "quux", "imports", "the", "package", "and", "returns", "the", "desired", "module", "." ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/mavproxy.py#L416-L429
train
230,318
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/mavproxy.py
process_master
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: time.sleep(0.1) return if (mpstate.settings.compdebug & 1) != 0: return if mpstate.logqueue_raw: mpstate.logqueue_raw.put(str(s)) if mpstate.status.setup_mode: if mpstate.system == 'Windows': # strip nsh ansi codes s = s.replace("\033[K","") sys.stdout.write(str(s)) sys.stdout.flush() return if m.first_byte and opts.auto_protocol: m.auto_mavlink_version(s) msgs = m.mav.parse_buffer(s) if msgs: for msg in msgs: sysid = msg.get_srcSystem() if sysid in mpstate.sysid_outputs: # the message has been handled by a specialised handler for this system continue if getattr(m, '_timestamp', None) is None: m.post_message(msg) if msg.get_type() == "BAD_DATA": if opts.show_errors: mpstate.console.writeln("MAV error: %s" % msg) mpstate.status.mav_error += 1
python
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: time.sleep(0.1) return if (mpstate.settings.compdebug & 1) != 0: return if mpstate.logqueue_raw: mpstate.logqueue_raw.put(str(s)) if mpstate.status.setup_mode: if mpstate.system == 'Windows': # strip nsh ansi codes s = s.replace("\033[K","") sys.stdout.write(str(s)) sys.stdout.flush() return if m.first_byte and opts.auto_protocol: m.auto_mavlink_version(s) msgs = m.mav.parse_buffer(s) if msgs: for msg in msgs: sysid = msg.get_srcSystem() if sysid in mpstate.sysid_outputs: # the message has been handled by a specialised handler for this system continue if getattr(m, '_timestamp', None) is None: m.post_message(msg) if msg.get_type() == "BAD_DATA": if opts.show_errors: mpstate.console.writeln("MAV error: %s" % msg) mpstate.status.mav_error += 1
[ "def", "process_master", "(", "m", ")", ":", "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 ...
process packets from the MAVLink master
[ "process", "packets", "from", "the", "MAVLink", "master" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/mavproxy.py#L518-L559
train
230,319
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/mavproxy.py
set_stream_rates
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.streamrate mpstate.status.last_streamrate2 = mpstate.settings.streamrate2 for master in mpstate.mav_master: if master.linknum == 0: rate = mpstate.settings.streamrate else: rate = mpstate.settings.streamrate2 if rate != -1: master.mav.request_data_stream_send(mpstate.settings.target_system, mpstate.settings.target_component, mavutil.mavlink.MAV_DATA_STREAM_ALL, rate, 1)
python
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.streamrate mpstate.status.last_streamrate2 = mpstate.settings.streamrate2 for master in mpstate.mav_master: if master.linknum == 0: rate = mpstate.settings.streamrate else: rate = mpstate.settings.streamrate2 if rate != -1: master.mav.request_data_stream_send(mpstate.settings.target_system, mpstate.settings.target_component, mavutil.mavlink.MAV_DATA_STREAM_ALL, rate, 1)
[ "def", "set_stream_rates", "(", ")", ":", "if", "(", "not", "msg_period", ".", "trigger", "(", ")", "and", "mpstate", ".", "status", ".", "last_streamrate1", "==", "mpstate", ".", "settings", ".", "streamrate", "and", "mpstate", ".", "status", ".", "last_s...
set mavlink stream rates
[ "set", "mavlink", "stream", "rates" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/mavproxy.py#L669-L685
train
230,320
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/mavproxy.py
periodic_tasks
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.settings.heartbeat != 0: mpstate.status.counters['MasterOut'] += 1 for master in mpstate.mav_master: send_heartbeat(master) if heartbeat_check_period.trigger(): check_link_status() set_stream_rates() # call optional module idle tasks. These are called at several hundred Hz for (m,pm) in mpstate.modules: if hasattr(m, 'idle_task'): try: m.idle_task() except Exception as msg: if mpstate.settings.moddebug == 1: print(msg) elif mpstate.settings.moddebug > 1: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout) # also see if the module should be unloaded: if m.needs_unloading: unload_module(m.name)
python
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.settings.heartbeat != 0: mpstate.status.counters['MasterOut'] += 1 for master in mpstate.mav_master: send_heartbeat(master) if heartbeat_check_period.trigger(): check_link_status() set_stream_rates() # call optional module idle tasks. These are called at several hundred Hz for (m,pm) in mpstate.modules: if hasattr(m, 'idle_task'): try: m.idle_task() except Exception as msg: if mpstate.settings.moddebug == 1: print(msg) elif mpstate.settings.moddebug > 1: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout) # also see if the module should be unloaded: if m.needs_unloading: unload_module(m.name)
[ "def", "periodic_tasks", "(", ")", ":", "if", "mpstate", ".", "status", ".", "setup_mode", ":", "return", "if", "(", "mpstate", ".", "settings", ".", "compdebug", "&", "2", ")", "!=", "0", ":", "return", "if", "mpstate", ".", "settings", ".", "heartbea...
run periodic checks
[ "run", "periodic", "checks" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/mavproxy.py#L707-L743
train
230,321
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/mavproxy.py
MPState.master
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.settings.link-1].linkerror: return self.mav_master[self.settings.link-1] for m in self.mav_master: if not m.linkerror: return m return self.mav_master[self.settings.link-1]
python
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.settings.link-1].linkerror: return self.mav_master[self.settings.link-1] for m in self.mav_master: if not m.linkerror: return m return self.mav_master[self.settings.link-1]
[ "def", "master", "(", "self", ")", ":", "if", "len", "(", "self", ".", "mav_master", ")", "==", "0", ":", "return", "None", "if", "self", ".", "settings", ".", "link", ">", "len", "(", "self", ".", "mav_master", ")", ":", "self", ".", "settings", ...
return the currently chosen mavlink master object
[ "return", "the", "currently", "chosen", "mavlink", "master", "object" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/mavproxy.py#L223-L235
train
230,322
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/generator/mavgen_cs.py
generate
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)) for m in msgs: m.order_map = [ 0 ] * len(m.fieldnames) for i in range(0, len(m.fieldnames)): m.order_map[i] = m.ordered_fieldnames.index(m.fieldnames[i]) m.fields_in_order = [] for i in range(0, len(m.fieldnames)): m.order_map[i] = m.ordered_fieldnames.index(m.fieldnames[i]) print("Generating messages file: %s" % structsfilename) dir = os.path.dirname(structsfilename) if not os.path.exists(dir): os.makedirs(dir) outf = open(structsfilename, "w") generate_preamble(outf, msgs, filelist, xml[0]) outf.write(""" using System.Reflection; [assembly: AssemblyTitle("Mavlink Classes")] [assembly: AssemblyDescription("Generated Message Classes for Mavlink. See http://qgroundcontrol.org/mavlink/start")] [assembly: AssemblyProduct("Mavlink")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] """) generate_enums(outf, enums) generate_classes(outf, msgs) outf.close() print("Generating the (De)Serializer classes") serfilename = basename + '_codec.generated.cs' outf = open(serfilename, "w") generate_CodecIndex(outf, msgs, xml) generate_Deserialization(outf, msgs) generate_Serialization(outf, msgs) outf.write("\t}\n\n") outf.write("}\n\n") outf.close() # Some build commands depend on the platform - eg MS .NET Windows Vs Mono on Linux if platform.system() == "Windows": winpath=os.environ['WinDir'] cscCommand = winpath + "\\Microsoft.NET\\Framework\\v4.0.30319\\csc.exe" if (os.path.exists(cscCommand)==False): print("\nError: CS compiler not found. .Net Assembly generation skipped") return else: print("Error:.Net Assembly generation not yet supported on non Windows platforms") return cscCommand = "csc" print("Compiling Assembly for .Net Framework 4.0") generatedCsFiles = [ serfilename, structsfilename] includedCsFiles = [ 'CS/common/ByteArrayUtil.cs', 'CS/common/FrameworkBitConverter.cs', 'CS/common/Mavlink.cs' ] outputLibraryPath = os.path.normpath(dir + "/mavlink.dll") compileCommand = "%s %s" % (cscCommand, "/target:library /debug /out:" + outputLibraryPath) compileCommand = compileCommand + " /doc:" + os.path.normpath(dir + "/mavlink.xml") for csFile in generatedCsFiles + includedCsFiles: compileCommand = compileCommand + " " + os.path.normpath(csFile) #print("Cmd:" + compileCommand) res = os.system (compileCommand) if res == '0': print("Generated %s OK" % filename) else: print("Error")
python
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)) for m in msgs: m.order_map = [ 0 ] * len(m.fieldnames) for i in range(0, len(m.fieldnames)): m.order_map[i] = m.ordered_fieldnames.index(m.fieldnames[i]) m.fields_in_order = [] for i in range(0, len(m.fieldnames)): m.order_map[i] = m.ordered_fieldnames.index(m.fieldnames[i]) print("Generating messages file: %s" % structsfilename) dir = os.path.dirname(structsfilename) if not os.path.exists(dir): os.makedirs(dir) outf = open(structsfilename, "w") generate_preamble(outf, msgs, filelist, xml[0]) outf.write(""" using System.Reflection; [assembly: AssemblyTitle("Mavlink Classes")] [assembly: AssemblyDescription("Generated Message Classes for Mavlink. See http://qgroundcontrol.org/mavlink/start")] [assembly: AssemblyProduct("Mavlink")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] """) generate_enums(outf, enums) generate_classes(outf, msgs) outf.close() print("Generating the (De)Serializer classes") serfilename = basename + '_codec.generated.cs' outf = open(serfilename, "w") generate_CodecIndex(outf, msgs, xml) generate_Deserialization(outf, msgs) generate_Serialization(outf, msgs) outf.write("\t}\n\n") outf.write("}\n\n") outf.close() # Some build commands depend on the platform - eg MS .NET Windows Vs Mono on Linux if platform.system() == "Windows": winpath=os.environ['WinDir'] cscCommand = winpath + "\\Microsoft.NET\\Framework\\v4.0.30319\\csc.exe" if (os.path.exists(cscCommand)==False): print("\nError: CS compiler not found. .Net Assembly generation skipped") return else: print("Error:.Net Assembly generation not yet supported on non Windows platforms") return cscCommand = "csc" print("Compiling Assembly for .Net Framework 4.0") generatedCsFiles = [ serfilename, structsfilename] includedCsFiles = [ 'CS/common/ByteArrayUtil.cs', 'CS/common/FrameworkBitConverter.cs', 'CS/common/Mavlink.cs' ] outputLibraryPath = os.path.normpath(dir + "/mavlink.dll") compileCommand = "%s %s" % (cscCommand, "/target:library /debug /out:" + outputLibraryPath) compileCommand = compileCommand + " /doc:" + os.path.normpath(dir + "/mavlink.xml") for csFile in generatedCsFiles + includedCsFiles: compileCommand = compileCommand + " " + os.path.normpath(csFile) #print("Cmd:" + compileCommand) res = os.system (compileCommand) if res == '0': print("Generated %s OK" % filename) else: print("Error")
[ "def", "generate", "(", "basename", ",", "xml", ")", ":", "structsfilename", "=", "basename", "+", "'.generated.cs'", "msgs", "=", "[", "]", "enums", "=", "[", "]", "filelist", "=", "[", "]", "for", "x", "in", "xml", ":", "msgs", ".", "extend", "(", ...
generate complete MAVLink CSharp implemenation
[ "generate", "complete", "MAVLink", "CSharp", "implemenation" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/generator/mavgen_cs.py#L254-L343
train
230,323
JdeRobot/base
src/tools/colorTuner_py/QDarkStyleSheet/qdarkstyle/__init__.py
load_stylesheet
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_style_rc else: import qdarkstyle.pyqt_style_rc # Load the stylesheet content from resources if not pyside: from PyQt4.QtCore import QFile, QTextStream else: from PySide.QtCore import QFile, QTextStream f = QFile(":qdarkstyle/style.qss") if not f.exists(): _logger().error("Unable to load stylesheet, file not found in " "resources") return "" else: f.open(QFile.ReadOnly | QFile.Text) ts = QTextStream(f) stylesheet = ts.readAll() if platform.system().lower() == 'darwin': # see issue #12 on github mac_fix = ''' QDockWidget::title { background-color: #31363b; text-align: center; height: 12px; } ''' stylesheet += mac_fix return stylesheet
python
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_style_rc else: import qdarkstyle.pyqt_style_rc # Load the stylesheet content from resources if not pyside: from PyQt4.QtCore import QFile, QTextStream else: from PySide.QtCore import QFile, QTextStream f = QFile(":qdarkstyle/style.qss") if not f.exists(): _logger().error("Unable to load stylesheet, file not found in " "resources") return "" else: f.open(QFile.ReadOnly | QFile.Text) ts = QTextStream(f) stylesheet = ts.readAll() if platform.system().lower() == 'darwin': # see issue #12 on github mac_fix = ''' QDockWidget::title { background-color: #31363b; text-align: center; height: 12px; } ''' stylesheet += mac_fix return stylesheet
[ "def", "load_stylesheet", "(", "pyside", "=", "True", ")", ":", "# Smart import of the rc file", "if", "pyside", ":", "import", "qdarkstyle", ".", "pyside_style_rc", "else", ":", "import", "qdarkstyle", ".", "pyqt_style_rc", "# Load the stylesheet content from resources",...
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
[ "Loads", "the", "stylesheet", ".", "Takes", "care", "of", "importing", "the", "rc", "module", "." ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/tools/colorTuner_py/QDarkStyleSheet/qdarkstyle/__init__.py#L42-L81
train
230,324
JdeRobot/base
src/tools/colorTuner_py/QDarkStyleSheet/qdarkstyle/__init__.py
load_stylesheet_pyqt5
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 content from resources from PyQt5.QtCore import QFile, QTextStream f = QFile(":qdarkstyle/style.qss") if not f.exists(): _logger().error("Unable to load stylesheet, file not found in " "resources") return "" else: f.open(QFile.ReadOnly | QFile.Text) ts = QTextStream(f) stylesheet = ts.readAll() if platform.system().lower() == 'darwin': # see issue #12 on github mac_fix = ''' QDockWidget::title { background-color: #31363b; text-align: center; height: 12px; } ''' stylesheet += mac_fix return stylesheet
python
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 content from resources from PyQt5.QtCore import QFile, QTextStream f = QFile(":qdarkstyle/style.qss") if not f.exists(): _logger().error("Unable to load stylesheet, file not found in " "resources") return "" else: f.open(QFile.ReadOnly | QFile.Text) ts = QTextStream(f) stylesheet = ts.readAll() if platform.system().lower() == 'darwin': # see issue #12 on github mac_fix = ''' QDockWidget::title { background-color: #31363b; text-align: center; height: 12px; } ''' stylesheet += mac_fix return stylesheet
[ "def", "load_stylesheet_pyqt5", "(", ")", ":", "# Smart import of the rc file", "import", "qdarkstyle", ".", "pyqt5_style_rc", "# Load the stylesheet content from resources", "from", "PyQt5", ".", "QtCore", "import", "QFile", ",", "QTextStream", "f", "=", "QFile", "(", ...
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
[ "Loads", "the", "stylesheet", "for", "use", "in", "a", "pyqt5", "application", "." ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/tools/colorTuner_py/QDarkStyleSheet/qdarkstyle/__init__.py#L84-L117
train
230,325
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/modules/lib/mp_menu.py
MPMenuItem.call_handler
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
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()
[ "def", "call_handler", "(", "self", ")", ":", "if", "self", ".", "handler", "is", "None", ":", "return", "call", "=", "getattr", "(", "self", ".", "handler", ",", "'call'", ",", "None", ")", "if", "call", "is", "not", "None", ":", "self", ".", "han...
optionally call a handler function
[ "optionally", "call", "a", "handler", "function" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/modules/lib/mp_menu.py#L58-L64
train
230,326
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/modules/lib/mp_menu.py
MPMenuTop.add
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 updated = True if not updated: self.items.append(m)
python
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 updated = True if not updated: self.items.append(m)
[ "def", "add", "(", "self", ",", "items", ")", ":", "if", "not", "isinstance", "(", "items", ",", "list", ")", ":", "items", "=", "[", "items", "]", "for", "m", "in", "items", ":", "updated", "=", "False", "for", "i", "in", "range", "(", "len", ...
add a submenu
[ "add", "a", "submenu" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/modules/lib/mp_menu.py#L216-L227
train
230,327
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/modules/lib/mp_menu.py
MPMenuChildMessageDialog.call
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 know why yet font = wx.Font(self.font_size, wx.MODERN, wx.NORMAL, wx.NORMAL) dlg = GenericMessageDialog(None, self.message, self.title, wx.ICON_INFORMATION|wx.OK) dlg.SetFont(font) dlg.ShowModal() app.MainLoop()
python
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 know why yet font = wx.Font(self.font_size, wx.MODERN, wx.NORMAL, wx.NORMAL) dlg = GenericMessageDialog(None, self.message, self.title, wx.ICON_INFORMATION|wx.OK) dlg.SetFont(font) dlg.ShowModal() app.MainLoop()
[ "def", "call", "(", "self", ")", ":", "mp_util", ".", "child_close_fds", "(", ")", "import", "wx_processguard", "from", "wx_loader", "import", "wx", "from", "wx", ".", "lib", ".", "agw", ".", "genericmessagedialog", "import", "GenericMessageDialog", "app", "="...
show the dialog as a child process
[ "show", "the", "dialog", "as", "a", "child", "process" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/modules/lib/mp_menu.py#L299-L311
train
230,328
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_map/GAreader.py
ERMap.read_ermapper
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' self.header = self.read_ermapper_header(header_file) nroflines = int(self.header['nroflines']) nrofcellsperlines = int(self.header['nrofcellsperline']) self.data = self.read_ermapper_data(data_file, offset=int(self.header['headeroffset'])) self.data = numpy.reshape(self.data,(nroflines,nrofcellsperlines)) longy = numpy.fromstring(self.getHeaderParam('longitude'), sep=':') latty = numpy.fromstring(self.getHeaderParam('latitude'), sep=':') self.deltalatitude = float(self.header['ydimension']) self.deltalongitude = float(self.header['xdimension']) if longy[0] < 0: self.startlongitude = longy[0]+-((longy[1]/60)+(longy[2]/3600)) self.endlongitude = self.startlongitude - int(self.header['nrofcellsperline'])*self.deltalongitude else: self.startlongitude = longy[0]+(longy[1]/60)+(longy[2]/3600) self.endlongitude = self.startlongitude + int(self.header['nrofcellsperline'])*self.deltalongitude if latty[0] < 0: self.startlatitude = latty[0]-((latty[1]/60)+(latty[2]/3600)) self.endlatitude = self.startlatitude - int(self.header['nroflines'])*self.deltalatitude else: self.startlatitude = latty[0]+(latty[1]/60)+(latty[2]/3600) self.endlatitude = self.startlatitude + int(self.header['nroflines'])*self.deltalatitude
python
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' self.header = self.read_ermapper_header(header_file) nroflines = int(self.header['nroflines']) nrofcellsperlines = int(self.header['nrofcellsperline']) self.data = self.read_ermapper_data(data_file, offset=int(self.header['headeroffset'])) self.data = numpy.reshape(self.data,(nroflines,nrofcellsperlines)) longy = numpy.fromstring(self.getHeaderParam('longitude'), sep=':') latty = numpy.fromstring(self.getHeaderParam('latitude'), sep=':') self.deltalatitude = float(self.header['ydimension']) self.deltalongitude = float(self.header['xdimension']) if longy[0] < 0: self.startlongitude = longy[0]+-((longy[1]/60)+(longy[2]/3600)) self.endlongitude = self.startlongitude - int(self.header['nrofcellsperline'])*self.deltalongitude else: self.startlongitude = longy[0]+(longy[1]/60)+(longy[2]/3600) self.endlongitude = self.startlongitude + int(self.header['nrofcellsperline'])*self.deltalongitude if latty[0] < 0: self.startlatitude = latty[0]-((latty[1]/60)+(latty[2]/3600)) self.endlatitude = self.startlatitude - int(self.header['nroflines'])*self.deltalatitude else: self.startlatitude = latty[0]+(latty[1]/60)+(latty[2]/3600) self.endlatitude = self.startlatitude + int(self.header['nroflines'])*self.deltalatitude
[ "def", "read_ermapper", "(", "self", ",", "ifile", ")", ":", "ers_index", "=", "ifile", ".", "find", "(", "'.ers'", ")", "if", "ers_index", ">", "0", ":", "data_file", "=", "ifile", "[", "0", ":", "ers_index", "]", "header_file", "=", "ifile", "else", ...
Read in a DEM file and associated .ers file
[ "Read", "in", "a", "DEM", "file", "and", "associated", ".", "ers", "file" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_map/GAreader.py#L25-L59
train
230,329
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_map/GAreader.py
ERMap.printBoundingBox
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
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)
[ "def", "printBoundingBox", "(", "self", ")", ":", "print", "(", "\"Bounding Latitude: \"", ")", "print", "(", "self", ".", "startlatitude", ")", "print", "(", "self", ".", "endlatitude", ")", "print", "(", "\"Bounding Longitude: \"", ")", "print", "(", "self",...
Print the bounding box that this DEM covers
[ "Print", "the", "bounding", "box", "that", "this", "DEM", "covers" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_map/GAreader.py#L92-L100
train
230,330
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_map/GAreader.py
ERMap.getPercentBlank
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 tiles = ", blank, "out of ", (nonblank+blank))
python
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 tiles = ", blank, "out of ", (nonblank+blank))
[ "def", "getPercentBlank", "(", "self", ")", ":", "blank", "=", "0", "nonblank", "=", "0", "for", "x", "in", "self", ".", "data", ".", "flat", ":", "if", "x", "==", "-", "99999.0", ":", "blank", "=", "blank", "+", "1", "else", ":", "nonblank", "="...
Print how many null cells are in the DEM - Quality measure
[ "Print", "how", "many", "null", "cells", "are", "in", "the", "DEM", "-", "Quality", "measure" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_map/GAreader.py#L102-L112
train
230,331
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_rc.py
RCModule.send_rc_override
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, self.target_component, *self.override)
python
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, self.target_component, *self.override)
[ "def", "send_rc_override", "(", "self", ")", ":", "if", "self", ".", "sitl_output", ":", "buf", "=", "struct", ".", "pack", "(", "'<HHHHHHHH'", ",", "*", "self", ".", "override", ")", "self", ".", "sitl_output", ".", "write", "(", "buf", ")", "else", ...
send RC override packet
[ "send", "RC", "override", "packet" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_rc.py#L31-L40
train
230,332
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_rc.py
RCModule.cmd_switch
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 value. Use 1-6 for flight modes, '0' to disable") return if self.vehicle_type == 'copter': default_channel = 5 else: default_channel = 8 if self.vehicle_type == 'rover': flite_mode_ch_parm = int(self.get_mav_param("MODE_CH", default_channel)) else: flite_mode_ch_parm = int(self.get_mav_param("FLTMODE_CH", default_channel)) self.override[flite_mode_ch_parm - 1] = mapping[value] self.override_counter = 10 self.send_rc_override() if value == 0: print("Disabled RC switch override") else: print("Set RC switch override to %u (PWM=%u channel=%u)" % ( value, mapping[value], flite_mode_ch_parm))
python
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 value. Use 1-6 for flight modes, '0' to disable") return if self.vehicle_type == 'copter': default_channel = 5 else: default_channel = 8 if self.vehicle_type == 'rover': flite_mode_ch_parm = int(self.get_mav_param("MODE_CH", default_channel)) else: flite_mode_ch_parm = int(self.get_mav_param("FLTMODE_CH", default_channel)) self.override[flite_mode_ch_parm - 1] = mapping[value] self.override_counter = 10 self.send_rc_override() if value == 0: print("Disabled RC switch override") else: print("Set RC switch override to %u (PWM=%u channel=%u)" % ( value, mapping[value], flite_mode_ch_parm))
[ "def", "cmd_switch", "(", "self", ",", "args", ")", ":", "mapping", "=", "[", "0", ",", "1165", ",", "1295", ",", "1425", ",", "1555", ",", "1685", ",", "1815", "]", "if", "len", "(", "args", ")", "!=", "1", ":", "print", "(", "\"Usage: switch <p...
handle RC switch changes
[ "handle", "RC", "switch", "changes" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_rc.py#L42-L67
train
230,333
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/modules/lib/ANUGA/geo_reference.py
write_NetCDF_georeference
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(outfile) return geo_ref
python
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(outfile) return geo_ref
[ "def", "write_NetCDF_georeference", "(", "origin", ",", "outfile", ")", ":", "geo_ref", "=", "ensure_geo_reference", "(", "origin", ")", "geo_ref", ".", "write_NetCDF", "(", "outfile", ")", "return", "geo_ref" ]
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.
[ "Write", "georeference", "info", "to", "a", "netcdf", "file", "usually", "sww", "." ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/modules/lib/ANUGA/geo_reference.py#L430-L440
train
230,334
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/modules/lib/ANUGA/geo_reference.py
Geo_reference.is_absolute
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. # Moreover, this little function is responsible for a large fraction of the time # using in data fitting (something in like 40 - 50%. # This was due to the repeated calls to allclose. # With the flag method fitting is much faster (18 Mar 2009). # FIXME(Ole): HACK to be able to reuse data already cached (18 Mar 2009). # Remove at some point if not hasattr(self, 'absolute'): self.absolute = num.allclose([self.xllcorner, self.yllcorner], 0) # Return absolute flag return self.absolute
python
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. # Moreover, this little function is responsible for a large fraction of the time # using in data fitting (something in like 40 - 50%. # This was due to the repeated calls to allclose. # With the flag method fitting is much faster (18 Mar 2009). # FIXME(Ole): HACK to be able to reuse data already cached (18 Mar 2009). # Remove at some point if not hasattr(self, 'absolute'): self.absolute = num.allclose([self.xllcorner, self.yllcorner], 0) # Return absolute flag return self.absolute
[ "def", "is_absolute", "(", "self", ")", ":", "# FIXME(Ole): It is unfortunate that decision about whether points", "# are absolute or not lies with the georeference object. Ross pointed this out.", "# Moreover, this little function is responsible for a large fraction of the time", "# using in data...
Return True if xllcorner==yllcorner==0 indicating that points in question are absolute.
[ "Return", "True", "if", "xllcorner", "==", "yllcorner", "==", "0", "indicating", "that", "points", "in", "question", "are", "absolute", "." ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/modules/lib/ANUGA/geo_reference.py#L275-L293
train
230,335
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/modules/lib/mp_util.py
mkdir_p
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
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
[ "def", "mkdir_p", "(", "dir", ")", ":", "if", "not", "dir", ":", "return", "if", "dir", ".", "endswith", "(", "\"/\"", ")", "or", "dir", ".", "endswith", "(", "\"\\\\\"", ")", ":", "mkdir_p", "(", "dir", "[", ":", "-", "1", "]", ")", "return", ...
like mkdir -p
[ "like", "mkdir", "-", "p" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/modules/lib/mp_util.py#L88-L101
train
230,336
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/modules/lib/mp_util.py
polygon_load
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 RuntimeError("invalid polygon line: %s" % line) ret.append((float(a[0]), float(a[1]))) f.close() return ret
python
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 RuntimeError("invalid polygon line: %s" % line) ret.append((float(a[0]), float(a[1]))) f.close() return ret
[ "def", "polygon_load", "(", "filename", ")", ":", "ret", "=", "[", "]", "f", "=", "open", "(", "filename", ")", "for", "line", "in", "f", ":", "if", "line", ".", "startswith", "(", "'#'", ")", ":", "continue", "line", "=", "line", ".", "strip", "...
load a polygon from a file
[ "load", "a", "polygon", "from", "a", "file" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/modules/lib/mp_util.py#L103-L118
train
230,337
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/modules/lib/mp_util.py
bounds_overlap
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
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
[ "def", "bounds_overlap", "(", "bound1", ",", "bound2", ")", ":", "(", "x1", ",", "y1", ",", "w1", ",", "h1", ")", "=", "bound1", "(", "x2", ",", "y2", ",", "w2", ",", "h2", ")", "=", "bound2", "if", "x1", "+", "w1", "<", "x2", ":", "return", ...
return true if two bounding boxes overlap
[ "return", "true", "if", "two", "bounding", "boxes", "overlap" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/modules/lib/mp_util.py#L132-L144
train
230,338
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/modules/lib/mp_util.py
latlon_to_grid
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, hemisphere=hemisphere)
python
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, hemisphere=hemisphere)
[ "def", "latlon_to_grid", "(", "latlon", ")", ":", "from", "MAVProxy", ".", "modules", ".", "lib", ".", "ANUGA", "import", "redfearn", "(", "zone", ",", "easting", ",", "northing", ")", "=", "redfearn", ".", "redfearn", "(", "latlon", "[", "0", "]", ","...
convert to grid reference
[ "convert", "to", "grid", "reference" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/modules/lib/mp_util.py#L189-L197
train
230,339
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/modules/lib/mp_util.py
latlon_round
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
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()
[ "def", "latlon_round", "(", "latlon", ",", "spacing", "=", "1000", ")", ":", "g", "=", "latlon_to_grid", "(", "latlon", ")", "g", ".", "easting", "=", "(", "g", ".", "easting", "//", "spacing", ")", "*", "spacing", "g", ".", "northing", "=", "(", "...
round to nearest grid corner
[ "round", "to", "nearest", "grid", "corner" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/modules/lib/mp_util.py#L199-L204
train
230,340
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/modules/lib/mp_util.py
wxToPIL
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
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
[ "def", "wxToPIL", "(", "wimg", ")", ":", "from", "PIL", "import", "Image", "(", "w", ",", "h", ")", "=", "wimg", ".", "GetSize", "(", ")", "d", "=", "wimg", ".", "GetData", "(", ")", "pimg", "=", "Image", ".", "new", "(", "\"RGB\"", ",", "(", ...
convert a wxImage to a PIL Image
[ "convert", "a", "wxImage", "to", "a", "PIL", "Image" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/modules/lib/mp_util.py#L207-L214
train
230,341
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/modules/lib/mp_util.py
child_close_fds
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: pass
python
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: pass
[ "def", "child_close_fds", "(", ")", ":", "global", "child_fd_list", "import", "os", "while", "len", "(", "child_fd_list", ")", ">", "0", ":", "fd", "=", "child_fd_list", ".", "pop", "(", "0", ")", "try", ":", "os", ".", "close", "(", "fd", ")", "exce...
close file descriptors that a child process should not inherit. Should be called from child processes.
[ "close", "file", "descriptors", "that", "a", "child", "process", "should", "not", "inherit", ".", "Should", "be", "called", "from", "child", "processes", "." ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/modules/lib/mp_util.py#L256-L266
train
230,342
spaam/svtplay-dl
scripts/cibuild.py
snapshot_folder
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('ascii', 'ignore').strip())) sys.exit(2) except FileNotFoundError as e: logger.error("Error: {}".format(e)) sys.exit(2) ds = stdout.decode('ascii', 'ignore').strip() dt = datetime.fromisoformat(ds) utc = dt - dt.utcoffset() return utc.strftime("%Y%m%d_%H%M%S")
python
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('ascii', 'ignore').strip())) sys.exit(2) except FileNotFoundError as e: logger.error("Error: {}".format(e)) sys.exit(2) ds = stdout.decode('ascii', 'ignore').strip() dt = datetime.fromisoformat(ds) utc = dt - dt.utcoffset() return utc.strftime("%Y%m%d_%H%M%S")
[ "def", "snapshot_folder", "(", ")", ":", "logger", ".", "info", "(", "\"Snapshot folder\"", ")", "try", ":", "stdout", "=", "subprocess", ".", "check_output", "(", "[", "\"git\"", ",", "\"show\"", ",", "\"-s\"", ",", "\"--format=%cI\"", ",", "\"HEAD\"", "]",...
Use the commit date in UTC as folder name
[ "Use", "the", "commit", "date", "in", "UTC", "as", "folder", "name" ]
d33186e54e436ebb1537e5baf67758e3bd3bf076
https://github.com/spaam/svtplay-dl/blob/d33186e54e436ebb1537e5baf67758e3bd3bf076/scripts/cibuild.py#L76-L92
train
230,343
spaam/svtplay-dl
lib/svtplay_dl/service/__init__.py
opengraph_get
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.com/img2.jpg" property="og:image"><meta ...', "image") 'http://example.com/img2.jpg' >>> opengraph_get('<html><head><meta name="og:image" property="og:image" content="http://example.com/img3.jpg"><meta ...', "image") 'http://example.com/img3.jpg' """ match = re.search('<meta [^>]*property="og:' + prop + '" content="([^"]*)"', html) if match is None: match = re.search('<meta [^>]*content="([^"]*)" property="og:' + prop + '"', html) if match is None: return None return match.group(1)
python
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.com/img2.jpg" property="og:image"><meta ...', "image") 'http://example.com/img2.jpg' >>> opengraph_get('<html><head><meta name="og:image" property="og:image" content="http://example.com/img3.jpg"><meta ...', "image") 'http://example.com/img3.jpg' """ match = re.search('<meta [^>]*property="og:' + prop + '" content="([^"]*)"', html) if match is None: match = re.search('<meta [^>]*content="([^"]*)" property="og:' + prop + '"', html) if match is None: return None return match.group(1)
[ "def", "opengraph_get", "(", "html", ",", "prop", ")", ":", "match", "=", "re", ".", "search", "(", "'<meta [^>]*property=\"og:'", "+", "prop", "+", "'\" content=\"([^\"]*)\"'", ",", "html", ")", "if", "match", "is", "None", ":", "match", "=", "re", ".", ...
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.com/img2.jpg" property="og:image"><meta ...', "image") 'http://example.com/img2.jpg' >>> opengraph_get('<html><head><meta name="og:image" property="og:image" content="http://example.com/img3.jpg"><meta ...', "image") 'http://example.com/img3.jpg'
[ "Extract", "specified", "OpenGraph", "property", "from", "html", "." ]
d33186e54e436ebb1537e5baf67758e3bd3bf076
https://github.com/spaam/svtplay-dl/blob/d33186e54e436ebb1537e5baf67758e3bd3bf076/lib/svtplay_dl/service/__init__.py#L82-L98
train
230,344
spaam/svtplay-dl
lib/svtplay_dl/utils/text.py
decode_html_entities
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_unicode(s))
python
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_unicode(s))
[ "def", "decode_html_entities", "(", "s", ")", ":", "parser", "=", "HTMLParser", ".", "HTMLParser", "(", ")", "def", "unesc", "(", "m", ")", ":", "return", "parser", ".", "unescape", "(", "m", ".", "group", "(", ")", ")", "return", "re", ".", "sub", ...
Replaces html entities with the character they represent. >>> print(decode_html_entities("&lt;3 &amp;")) <3 &
[ "Replaces", "html", "entities", "with", "the", "character", "they", "represent", "." ]
d33186e54e436ebb1537e5baf67758e3bd3bf076
https://github.com/spaam/svtplay-dl/blob/d33186e54e436ebb1537e5baf67758e3bd3bf076/lib/svtplay_dl/utils/text.py#L17-L28
train
230,345
spaam/svtplay-dl
lib/svtplay_dl/utils/text.py
filenamify
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 diacritical mark, which # means that we will get base char when we strip out non-ascii. title = unicodedata.normalize('NFD', title) # Convert to lowercase # Drop any non ascii letters/digits # Drop any leading/trailing whitespace that may have appeared title = re.sub(r'[^a-z0-9 .-]', '', title.lower().strip()) # Replace whitespace with dot title = re.sub(r'\s+', '.', title) title = re.sub(r'\.-\.', '-', title) return title
python
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 diacritical mark, which # means that we will get base char when we strip out non-ascii. title = unicodedata.normalize('NFD', title) # Convert to lowercase # Drop any non ascii letters/digits # Drop any leading/trailing whitespace that may have appeared title = re.sub(r'[^a-z0-9 .-]', '', title.lower().strip()) # Replace whitespace with dot title = re.sub(r'\s+', '.', title) title = re.sub(r'\.-\.', '-', title) return title
[ "def", "filenamify", "(", "title", ")", ":", "# ensure it is unicode", "title", "=", "ensure_unicode", "(", "title", ")", "# NFD decomposes chars into base char and diacritical mark, which", "# means that we will get base char when we strip out non-ascii.", "title", "=", "unicodeda...
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
[ "Convert", "a", "string", "to", "something", "suitable", "as", "a", "file", "name", ".", "E", ".", "g", "." ]
d33186e54e436ebb1537e5baf67758e3bd3bf076
https://github.com/spaam/svtplay-dl/blob/d33186e54e436ebb1537e5baf67758e3bd3bf076/lib/svtplay_dl/utils/text.py#L31-L54
train
230,346
spaam/svtplay-dl
lib/svtplay_dl/fetcher/http.py
HTTP.download
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) try: total_size = data.headers['content-length'] except KeyError: total_size = 0 total_size = int(total_size) bytes_so_far = 0 file_d = output(self.output, self.config, self.output_extention) if file_d is None: return eta = ETA(total_size) for i in data.iter_content(8192): bytes_so_far += len(i) file_d.write(i) if not self.config.get("silent"): eta.update(bytes_so_far) progressbar(total_size, bytes_so_far, ''.join(["ETA: ", str(eta)])) file_d.close() self.finished = True
python
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) try: total_size = data.headers['content-length'] except KeyError: total_size = 0 total_size = int(total_size) bytes_so_far = 0 file_d = output(self.output, self.config, self.output_extention) if file_d is None: return eta = ETA(total_size) for i in data.iter_content(8192): bytes_so_far += len(i) file_d.write(i) if not self.config.get("silent"): eta.update(bytes_so_far) progressbar(total_size, bytes_so_far, ''.join(["ETA: ", str(eta)])) file_d.close() self.finished = True
[ "def", "download", "(", "self", ")", ":", "_", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "self", ".", "url", ")", "if", "ext", "==", "\".mp3\"", ":", "self", ".", "output_extention", "=", "\"mp3\"", "else", ":", "self", ".", "output...
Get the stream from HTTP
[ "Get", "the", "stream", "from", "HTTP" ]
d33186e54e436ebb1537e5baf67758e3bd3bf076
https://github.com/spaam/svtplay-dl/blob/d33186e54e436ebb1537e5baf67758e3bd3bf076/lib/svtplay_dl/fetcher/http.py#L15-L43
train
230,347
spaam/svtplay-dl
lib/svtplay_dl/utils/output.py
progress
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
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)
[ "def", "progress", "(", "byte", ",", "total", ",", "extra", "=", "\"\"", ")", ":", "if", "total", "==", "0", ":", "progresstr", "=", "\"Downloaded %dkB bytes\"", "%", "(", "byte", ">>", "10", ")", "progress_stream", ".", "write", "(", "progresstr", "+", ...
Print some info about how much we have downloaded
[ "Print", "some", "info", "about", "how", "much", "we", "have", "downloaded" ]
d33186e54e436ebb1537e5baf67758e3bd3bf076
https://github.com/spaam/svtplay-dl/blob/d33186e54e436ebb1537e5baf67758e3bd3bf076/lib/svtplay_dl/utils/output.py#L80-L86
train
230,348
spaam/svtplay-dl
lib/svtplay_dl/utils/output.py
ETA.update
def update(self, pos): """ Set new absolute progress position. Parameters: pos: new absolute progress """ self.pos = pos self.now = time.time()
python
def update(self, pos): """ Set new absolute progress position. Parameters: pos: new absolute progress """ self.pos = pos self.now = time.time()
[ "def", "update", "(", "self", ",", "pos", ")", ":", "self", ".", "pos", "=", "pos", "self", ".", "now", "=", "time", ".", "time", "(", ")" ]
Set new absolute progress position. Parameters: pos: new absolute progress
[ "Set", "new", "absolute", "progress", "position", "." ]
d33186e54e436ebb1537e5baf67758e3bd3bf076
https://github.com/spaam/svtplay-dl/blob/d33186e54e436ebb1537e5baf67758e3bd3bf076/lib/svtplay_dl/utils/output.py#L39-L47
train
230,349
ArduPilot/MAVProxy
MAVProxy/modules/lib/graph_ui.py
Graph_UI.check_xlim_change
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 xlim != self.xlim: return xlim return None
python
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 xlim != self.xlim: return xlim return None
[ "def", "check_xlim_change", "(", "self", ")", ":", "if", "self", ".", "xlim_pipe", "is", "None", ":", "return", "None", "xlim", "=", "None", "while", "self", ".", "xlim_pipe", "[", "0", "]", ".", "poll", "(", ")", ":", "try", ":", "xlim", "=", "sel...
check for new X bounds
[ "check", "for", "new", "X", "bounds" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/lib/graph_ui.py#L50-L62
train
230,350
ArduPilot/MAVProxy
MAVProxy/modules/lib/graph_ui.py
Graph_UI.set_xlim
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 return True
python
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 return True
[ "def", "set_xlim", "(", "self", ",", "xlim", ")", ":", "if", "self", ".", "xlim_pipe", "is", "not", "None", "and", "self", ".", "xlim", "!=", "xlim", ":", "#print(\"send0: \", graph_count, xlim)", "try", ":", "self", ".", "xlim_pipe", "[", "0", "]", ".",...
set new X bounds
[ "set", "new", "X", "bounds" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/lib/graph_ui.py#L64-L73
train
230,351
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_serial.py
SerialModule.serial_lock
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.serial_settings.port, flags, 0, 0, 0, [0]*70)
python
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.serial_settings.port, flags, 0, 0, 0, [0]*70)
[ "def", "serial_lock", "(", "self", ",", "lock", ")", ":", "mav", "=", "self", ".", "master", ".", "mav", "if", "lock", ":", "flags", "=", "mavutil", ".", "mavlink", ".", "SERIAL_CONTROL_FLAG_EXCLUSIVE", "self", ".", "locked", "=", "True", "else", ":", ...
lock or unlock the port
[ "lock", "or", "unlock", "the", "port" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_serial.py#L32-L43
train
230,352
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_serial.py
SerialModule.cmd_serial
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(False) elif args[0] == "set": self.serial_settings.command(args[1:]) elif args[0] == "send": self.serial_send(args[1:]) else: print(usage)
python
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(False) elif args[0] == "set": self.serial_settings.command(args[1:]) elif args[0] == "send": self.serial_send(args[1:]) else: print(usage)
[ "def", "cmd_serial", "(", "self", ",", "args", ")", ":", "usage", "=", "\"Usage: serial <lock|unlock|set|send>\"", "if", "len", "(", "args", ")", "<", "1", ":", "print", "(", "usage", ")", "return", "if", "args", "[", "0", "]", "==", "\"lock\"", ":", "...
serial control commands
[ "serial", "control", "commands" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_serial.py#L67-L82
train
230,353
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_map/mp_tile.py
MPTile.downloader
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[keys[0]] for key in keys: if self._download_pending[key].request_time > tile_info.request_time: tile_info = self._download_pending[key] url = tile_info.url(self.service) path = self.tile_to_path(tile_info) key = tile_info.key() try: if self.debug: print("Downloading %s [%u left]" % (url, len(keys))) req = url_request(url) if url.find('google') != -1: req.add_header('Referer', 'https://maps.google.com/') resp = url_open(req) headers = resp.info() except url_error as e: #print('Error loading %s' % url) if not key in self._tile_cache: self._tile_cache[key] = self._unavailable self._download_pending.pop(key) if self.debug: print("Failed %s: %s" % (url, str(e))) continue if 'content-type' not in headers or headers['content-type'].find('image') == -1: if not key in self._tile_cache: self._tile_cache[key] = self._unavailable self._download_pending.pop(key) if self.debug: print("non-image response %s" % url) continue else: img = resp.read() # see if its a blank/unavailable tile md5 = hashlib.md5(img).hexdigest() if md5 in BLANK_TILES: if self.debug: print("blank tile %s" % url) if not key in self._tile_cache: self._tile_cache[key] = self._unavailable self._download_pending.pop(key) continue mp_util.mkdir_p(os.path.dirname(path)) h = open(path+'.tmp','wb') h.write(img) h.close() try: os.unlink(path) except Exception: pass os.rename(path+'.tmp', path) self._download_pending.pop(key) self._download_thread = None
python
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[keys[0]] for key in keys: if self._download_pending[key].request_time > tile_info.request_time: tile_info = self._download_pending[key] url = tile_info.url(self.service) path = self.tile_to_path(tile_info) key = tile_info.key() try: if self.debug: print("Downloading %s [%u left]" % (url, len(keys))) req = url_request(url) if url.find('google') != -1: req.add_header('Referer', 'https://maps.google.com/') resp = url_open(req) headers = resp.info() except url_error as e: #print('Error loading %s' % url) if not key in self._tile_cache: self._tile_cache[key] = self._unavailable self._download_pending.pop(key) if self.debug: print("Failed %s: %s" % (url, str(e))) continue if 'content-type' not in headers or headers['content-type'].find('image') == -1: if not key in self._tile_cache: self._tile_cache[key] = self._unavailable self._download_pending.pop(key) if self.debug: print("non-image response %s" % url) continue else: img = resp.read() # see if its a blank/unavailable tile md5 = hashlib.md5(img).hexdigest() if md5 in BLANK_TILES: if self.debug: print("blank tile %s" % url) if not key in self._tile_cache: self._tile_cache[key] = self._unavailable self._download_pending.pop(key) continue mp_util.mkdir_p(os.path.dirname(path)) h = open(path+'.tmp','wb') h.write(img) h.close() try: os.unlink(path) except Exception: pass os.rename(path+'.tmp', path) self._download_pending.pop(key) self._download_thread = None
[ "def", "downloader", "(", "self", ")", ":", "while", "self", ".", "tiles_pending", "(", ")", ">", "0", ":", "time", ".", "sleep", "(", "self", ".", "tile_delay", ")", "keys", "=", "sorted", "(", "self", ".", "_download_pending", ".", "keys", "(", ")"...
the download thread
[ "the", "download", "thread" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_map/mp_tile.py#L250-L313
train
230,354
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_firmware.py
FirmwareModule.cmd_fw
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) elif args[0] == "download": self.cmd_fw_download(rest) elif args[0] in ["help","usage"]: self.cmd_fw_help(rest) else: print(self.usage())
python
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) elif args[0] == "download": self.cmd_fw_download(rest) elif args[0] in ["help","usage"]: self.cmd_fw_help(rest) else: print(self.usage())
[ "def", "cmd_fw", "(", "self", ",", "args", ")", ":", "if", "len", "(", "args", ")", "==", "0", ":", "print", "(", "self", ".", "usage", "(", ")", ")", "return", "rest", "=", "args", "[", "1", ":", "]", "if", "args", "[", "0", "]", "==", "\"...
execute command defined in args
[ "execute", "command", "defined", "in", "args" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_firmware.py#L47-L62
train
230,355
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_firmware.py
FirmwareModule.frame_from_firmware
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", "tri": "TRICOPTER", "octa": "OCTOROTOR", "octa-quad": "ARDUPILOT_OCTAQUAD", "heli": "HELICOPTER", "Plane": "FIXED_WING", "Tracker": "ANTENNA_TRACKER", "Rover": "GROUND_ROVER", "PX4IO": "ARDUPILOT_PX4IO", } mavlink_to_frame_dict = { v : k for k,v in frame_to_mavlink_dict.items() } x = firmware["mav-type"] if firmware["mav-autopilot"] != "ARDUPILOTMEGA": return x if x in mavlink_to_frame_dict: return mavlink_to_frame_dict[x] return x
python
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", "tri": "TRICOPTER", "octa": "OCTOROTOR", "octa-quad": "ARDUPILOT_OCTAQUAD", "heli": "HELICOPTER", "Plane": "FIXED_WING", "Tracker": "ANTENNA_TRACKER", "Rover": "GROUND_ROVER", "PX4IO": "ARDUPILOT_PX4IO", } mavlink_to_frame_dict = { v : k for k,v in frame_to_mavlink_dict.items() } x = firmware["mav-type"] if firmware["mav-autopilot"] != "ARDUPILOTMEGA": return x if x in mavlink_to_frame_dict: return mavlink_to_frame_dict[x] return x
[ "def", "frame_from_firmware", "(", "self", ",", "firmware", ")", ":", "# see Tools/scripts/generate-manifest for this map:", "frame_to_mavlink_dict", "=", "{", "\"quad\"", ":", "\"QUADROTOR\"", ",", "\"hexa\"", ":", "\"HEXAROTOR\"", ",", "\"y6\"", ":", "\"ARDUPILOT_Y6\"",...
extract information from firmware, return pretty string to user
[ "extract", "information", "from", "firmware", "return", "pretty", "string", "to", "user" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_firmware.py#L64-L87
train
230,356
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_firmware.py
FirmwareModule.row_is_filtered
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(row_subs_value) != str(filtervalue): return True else: print("fw: Unknown filter keyword (%s)" % (filtername,)) return False
python
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(row_subs_value) != str(filtervalue): return True else: print("fw: Unknown filter keyword (%s)" % (filtername,)) return False
[ "def", "row_is_filtered", "(", "self", ",", "row_subs", ",", "filters", ")", ":", "for", "filtername", "in", "filters", ":", "filtervalue", "=", "filters", "[", "filtername", "]", "if", "filtername", "in", "row_subs", ":", "row_subs_value", "=", "row_subs", ...
returns True if row should NOT be included according to filters
[ "returns", "True", "if", "row", "should", "NOT", "be", "included", "according", "to", "filters" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_firmware.py#L98-L108
train
230,357
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_firmware.py
FirmwareModule.filters_from_args
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 form key-value is taken as a filter filters[arg[0:equals]] = arg[equals+1:]; except ValueError: remainder.append(arg) return (filters,remainder)
python
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 form key-value is taken as a filter filters[arg[0:equals]] = arg[equals+1:]; except ValueError: remainder.append(arg) return (filters,remainder)
[ "def", "filters_from_args", "(", "self", ",", "args", ")", ":", "filters", "=", "dict", "(", ")", "remainder", "=", "[", "]", "for", "arg", "in", "args", ":", "try", ":", "equals", "=", "arg", ".", "index", "(", "'='", ")", "# anything ofthe form key-v...
take any argument of the form name=value anmd put it into a dict; return that and the remaining arguments
[ "take", "any", "argument", "of", "the", "form", "name", "=", "value", "anmd", "put", "it", "into", "a", "dict", ";", "return", "that", "and", "the", "remaining", "arguments" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_firmware.py#L110-L121
train
230,358
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_firmware.py
FirmwareModule.all_firmwares
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
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
[ "def", "all_firmwares", "(", "self", ")", ":", "all", "=", "[", "]", "for", "manifest", "in", "self", ".", "manifests", ":", "for", "firmware", "in", "manifest", "[", "\"firmware\"", "]", ":", "all", ".", "append", "(", "firmware", ")", "return", "all"...
return firmware entries from all manifests
[ "return", "firmware", "entries", "from", "all", "manifests" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_firmware.py#L123-L129
train
230,359
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_firmware.py
FirmwareModule.rows_for_firmwares
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"], "frame": frame, # "type": firmware["mav-type"], "releasetype": firmware["mav-firmware-version-type"], "latest": firmware["latest"], "git-sha": firmware["git-sha"][0:7], "format": firmware["format"], "_firmware": firmware, } (major,minor,patch) = self.semver_from_firmware(firmware) if major is None: row["version"] = "" row["major"] = "" row["minor"] = "" row["patch"] = "" else: row["version"] = firmware["mav-firmware-version"] row["major"] = major row["minor"] = minor row["patch"] = patch i += 1 rows.append(row) return rows
python
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"], "frame": frame, # "type": firmware["mav-type"], "releasetype": firmware["mav-firmware-version-type"], "latest": firmware["latest"], "git-sha": firmware["git-sha"][0:7], "format": firmware["format"], "_firmware": firmware, } (major,minor,patch) = self.semver_from_firmware(firmware) if major is None: row["version"] = "" row["major"] = "" row["minor"] = "" row["patch"] = "" else: row["version"] = firmware["mav-firmware-version"] row["major"] = major row["minor"] = minor row["patch"] = patch i += 1 rows.append(row) return rows
[ "def", "rows_for_firmwares", "(", "self", ",", "firmwares", ")", ":", "rows", "=", "[", "]", "i", "=", "0", "for", "firmware", "in", "firmwares", ":", "frame", "=", "self", ".", "frame_from_firmware", "(", "firmware", ")", "row", "=", "{", "\"seq\"", "...
provide user-readable text for a firmware entry
[ "provide", "user", "-", "readable", "text", "for", "a", "firmware", "entry" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_firmware.py#L131-L163
train
230,360
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_firmware.py
FirmwareModule.filter_rows
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
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
[ "def", "filter_rows", "(", "self", ",", "filters", ",", "rows", ")", ":", "ret", "=", "[", "]", "for", "row", "in", "rows", ":", "if", "not", "self", ".", "row_is_filtered", "(", "row", ",", "filters", ")", ":", "ret", ".", "append", "(", "row", ...
returns rows as filtered by filters
[ "returns", "rows", "as", "filtered", "by", "filters" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_firmware.py#L165-L171
train
230,361
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_firmware.py
FirmwareModule.filtered_rows_from_args
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) all = self.all_firmwares() rows = self.rows_for_firmwares(all) filtered = self.filter_rows(filters, rows) return (filtered, remainder)
python
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) all = self.all_firmwares() rows = self.rows_for_firmwares(all) filtered = self.filter_rows(filters, rows) return (filtered, remainder)
[ "def", "filtered_rows_from_args", "(", "self", ",", "args", ")", ":", "if", "len", "(", "self", ".", "manifests", ")", "==", "0", ":", "print", "(", "\"fw: No manifests downloaded. Try 'manifest download'\"", ")", "return", "None", "(", "filters", ",", "remaind...
extracts filters from args, rows from manifests, returns filtered rows
[ "extracts", "filters", "from", "args", "rows", "from", "manifests", "returns", "filtered", "rows" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_firmware.py#L173-L183
train
230,362
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_firmware.py
FirmwareModule.cmd_fw_list
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 row in filtered: print("{seq:>5} {platform:<13} {frame:<10} {version:<10} {releasetype:<9} {latest:<6} {git-sha} {format}".format(**row))
python
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 row in filtered: print("{seq:>5} {platform:<13} {frame:<10} {version:<10} {releasetype:<9} {latest:<6} {git-sha} {format}".format(**row))
[ "def", "cmd_fw_list", "(", "self", ",", "args", ")", ":", "stuff", "=", "self", ".", "filtered_rows_from_args", "(", "args", ")", "if", "stuff", "is", "None", ":", "return", "(", "filtered", ",", "remainder", ")", "=", "stuff", "print", "(", "\"\"", ")...
cmd handler for list
[ "cmd", "handler", "for", "list" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_firmware.py#L185-L194
train
230,363
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_firmware.py
FirmwareModule.cmd_fw_download
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 if len(filtered) > 1: print("fw: No single firmware specified") return firmware = filtered[0]["_firmware"] url = firmware["url"] try: print("fw: URL: %s" % (url,)) filename=os.path.basename(url) files = [] files.append((url,filename)) child = multiproc.Process(target=mp_util.download_files, args=(files,)) child.start() except Exception as e: print("fw: download failed") print(e)
python
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 if len(filtered) > 1: print("fw: No single firmware specified") return firmware = filtered[0]["_firmware"] url = firmware["url"] try: print("fw: URL: %s" % (url,)) filename=os.path.basename(url) files = [] files.append((url,filename)) child = multiproc.Process(target=mp_util.download_files, args=(files,)) child.start() except Exception as e: print("fw: download failed") print(e)
[ "def", "cmd_fw_download", "(", "self", ",", "args", ")", ":", "stuff", "=", "self", ".", "filtered_rows_from_args", "(", "args", ")", "if", "stuff", "is", "None", ":", "return", "(", "filtered", ",", "remainder", ")", "=", "stuff", "if", "len", "(", "f...
cmd handler for downloading firmware
[ "cmd", "handler", "for", "downloading", "firmware" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_firmware.py#L196-L221
train
230,364
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_firmware.py
FirmwareModule.find_manifests
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)) except ValueError: pass return ret
python
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)) except ValueError: pass return ret
[ "def", "find_manifests", "(", "self", ")", ":", "manifest_dir", "=", "mp_util", ".", "dot_mavproxy", "(", ")", "ret", "=", "[", "]", "for", "file", "in", "os", ".", "listdir", "(", "manifest_dir", ")", ":", "try", ":", "file", ".", "index", "(", "\"m...
locate manifests and return filepaths thereof
[ "locate", "manifests", "and", "return", "filepaths", "thereof" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_firmware.py#L231-L242
train
230,365
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_firmware.py
FirmwareModule.cmd_fw_manifest_purge
def cmd_fw_manifest_purge(self): '''remove all downloaded manifests''' for filepath in self.find_manifests(): os.unlink(filepath) self.manifests_parse()
python
def cmd_fw_manifest_purge(self): '''remove all downloaded manifests''' for filepath in self.find_manifests(): os.unlink(filepath) self.manifests_parse()
[ "def", "cmd_fw_manifest_purge", "(", "self", ")", ":", "for", "filepath", "in", "self", ".", "find_manifests", "(", ")", ":", "os", ".", "unlink", "(", "filepath", ")", "self", ".", "manifests_parse", "(", ")" ]
remove all downloaded manifests
[ "remove", "all", "downloaded", "manifests" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_firmware.py#L253-L257
train
230,366
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_firmware.py
FirmwareModule.cmd_fw_manifest
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": return self.cmd_fw_manifest_list() if args[0] == "load": return self.cmd_fw_manifest_load() if args[0] == "purge": return self.cmd_fw_manifest_purge() if args[0] == "help": return self.cmd_fw_manifest_help() else: print("fw: Unknown manifest option (%s)" % args[0]) print(fw_manifest_usage())
python
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": return self.cmd_fw_manifest_list() if args[0] == "load": return self.cmd_fw_manifest_load() if args[0] == "purge": return self.cmd_fw_manifest_purge() if args[0] == "help": return self.cmd_fw_manifest_help() else: print("fw: Unknown manifest option (%s)" % args[0]) print(fw_manifest_usage())
[ "def", "cmd_fw_manifest", "(", "self", ",", "args", ")", ":", "if", "len", "(", "args", ")", "==", "0", ":", "print", "(", "self", ".", "fw_manifest_usage", "(", ")", ")", "return", "rest", "=", "args", "[", "1", ":", "]", "if", "args", "[", "0",...
cmd handler for manipulating manifests
[ "cmd", "handler", "for", "manipulating", "manifests" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_firmware.py#L259-L277
train
230,367
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_firmware.py
FirmwareModule.manifest_parse
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
def manifest_parse(self, path): '''parse manifest at path, return JSON object''' print("fw: parsing manifests") content = open(path).read() return json.loads(content)
[ "def", "manifest_parse", "(", "self", ",", "path", ")", ":", "print", "(", "\"fw: parsing manifests\"", ")", "content", "=", "open", "(", "path", ")", ".", "read", "(", ")", "return", "json", ".", "loads", "(", "content", ")" ]
parse manifest at path, return JSON object
[ "parse", "manifest", "at", "path", "return", "JSON", "object" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_firmware.py#L279-L283
train
230,368
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_firmware.py
FirmwareModule.manifest_path_is_old
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
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
[ "def", "manifest_path_is_old", "(", "self", ",", "path", ")", ":", "mtime", "=", "os", ".", "path", ".", "getmtime", "(", "path", ")", "return", "(", "time", ".", "time", "(", ")", "-", "mtime", ")", ">", "24", "*", "60", "*", "60" ]
return true if path is more than a day old
[ "return", "true", "if", "path", "is", "more", "than", "a", "day", "old" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_firmware.py#L289-L292
train
230,369
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_firmware.py
FirmwareModule.manifests_parse
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)) manifest = self.manifest_parse(manifest_path) if self.semver_major(manifest["format-version"]) != 1: print("fw: Manifest (%s) has major version %d; MAVProxy only understands version 1" % (manifest_path,manifest["format-version"])) continue self.manifests.append(manifest)
python
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)) manifest = self.manifest_parse(manifest_path) if self.semver_major(manifest["format-version"]) != 1: print("fw: Manifest (%s) has major version %d; MAVProxy only understands version 1" % (manifest_path,manifest["format-version"])) continue self.manifests.append(manifest)
[ "def", "manifests_parse", "(", "self", ")", ":", "self", ".", "manifests", "=", "[", "]", "for", "manifest_path", "in", "self", ".", "find_manifests", "(", ")", ":", "if", "self", ".", "manifest_path_is_old", "(", "manifest_path", ")", ":", "print", "(", ...
parse manifests present on system
[ "parse", "manifests", "present", "on", "system" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_firmware.py#L294-L304
train
230,370
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_firmware.py
FirmwareModule.make_safe_filename_from_url
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
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
[ "def", "make_safe_filename_from_url", "(", "self", ",", "url", ")", ":", "r", "=", "re", ".", "compile", "(", "\"([^a-zA-Z0-9_.-])\"", ")", "filename", "=", "r", ".", "sub", "(", "lambda", "m", ":", "\"%\"", "+", "str", "(", "hex", "(", "ord", "(", "...
return a version of url safe for use as a filename
[ "return", "a", "version", "of", "url", "safe", "for", "use", "as", "a", "filename" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_firmware.py#L324-L328
train
230,371
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_firmware.py
FirmwareModule.manifest_download
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://firmware.ardupilot.org/manifest.json']: filename = self.make_safe_filename_from_url(url) path = mp_util.dot_mavproxy("manifest-%s" % filename) self.downloaders[url] = threading.Thread(target=self.download_url, args=(url, path)) self.downloaders[url].start() self.downloaders_lock.release() else: print("fw: Failed to acquire download lock")
python
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://firmware.ardupilot.org/manifest.json']: filename = self.make_safe_filename_from_url(url) path = mp_util.dot_mavproxy("manifest-%s" % filename) self.downloaders[url] = threading.Thread(target=self.download_url, args=(url, path)) self.downloaders[url].start() self.downloaders_lock.release() else: print("fw: Failed to acquire download lock")
[ "def", "manifest_download", "(", "self", ")", ":", "if", "self", ".", "downloaders_lock", ".", "acquire", "(", "False", ")", ":", "if", "len", "(", "self", ".", "downloaders", ")", ":", "# there already exist downloader threads", "self", ".", "downloaders_lock",...
download manifest files
[ "download", "manifest", "files" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_firmware.py#L330-L345
train
230,372
ArduPilot/MAVProxy
MAVProxy/tools/mavflightview.py
colour_for_point
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(mlog, point, instance, options) # evaluate source as an expression which should return a # number in the range 0..255 try: v = eval(source, globals(),mlog.messages) except Exception as e: str_e = str(e) try: count = colour_expression_exceptions[str_e] except KeyError: colour_expression_exceptions[str_e] = 0 count = 0 if count > 100: print("Too many exceptions processing (%s): %s" % (source, str_e)) sys.exit(1) colour_expression_exceptions[str_e] += 1 v = 0 # we don't use evaluate_expression as we want the exceptions... # v = mavutil.evaluate_expression(source, mlog.messages) if v is None: v = 0 elif isinstance(v, str): print("colour expression returned a string: %s" % v) sys.exit(1) elif v < 0: print("colour expression returned %d (< 0)" % v) v = 0 elif v > 255: print("colour expression returned %d (> 255)" % v) v = 255 if v < colour_source_min: colour_source_min = v if v > colour_source_max: colour_source_max = v r = 255 g = 255 b = v return (b,b,b)
python
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(mlog, point, instance, options) # evaluate source as an expression which should return a # number in the range 0..255 try: v = eval(source, globals(),mlog.messages) except Exception as e: str_e = str(e) try: count = colour_expression_exceptions[str_e] except KeyError: colour_expression_exceptions[str_e] = 0 count = 0 if count > 100: print("Too many exceptions processing (%s): %s" % (source, str_e)) sys.exit(1) colour_expression_exceptions[str_e] += 1 v = 0 # we don't use evaluate_expression as we want the exceptions... # v = mavutil.evaluate_expression(source, mlog.messages) if v is None: v = 0 elif isinstance(v, str): print("colour expression returned a string: %s" % v) sys.exit(1) elif v < 0: print("colour expression returned %d (< 0)" % v) v = 0 elif v > 255: print("colour expression returned %d (> 255)" % v) v = 255 if v < colour_source_min: colour_source_min = v if v > colour_source_max: colour_source_max = v r = 255 g = 255 b = v return (b,b,b)
[ "def", "colour_for_point", "(", "mlog", ",", "point", ",", "instance", ",", "options", ")", ":", "global", "colour_expression_exceptions", ",", "colour_source_max", ",", "colour_source_min", "source", "=", "getattr", "(", "options", ",", "\"colour_source\"", ",", ...
indicate a colour to be used to plot point
[ "indicate", "a", "colour", "to", "be", "used", "to", "plot", "point" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/tools/mavflightview.py#L154-L201
train
230,373
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_restserver.py
mavlink_to_json
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
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
[ "def", "mavlink_to_json", "(", "msg", ")", ":", "ret", "=", "'\\\"%s\\\": {'", "%", "msg", ".", "_type", "for", "fieldname", "in", "msg", ".", "_fieldnames", ":", "data", "=", "getattr", "(", "msg", ",", "fieldname", ")", "ret", "+=", "'\\\"%s\\\" : \\\"%s...
Translate mavlink python messages in json string
[ "Translate", "mavlink", "python", "messages", "in", "json", "string" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_restserver.py#L18-L25
train
230,374
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_restserver.py
mpstatus_to_json
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
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
[ "def", "mpstatus_to_json", "(", "status", ")", ":", "msg_keys", "=", "list", "(", "status", ".", "msgs", ".", "keys", "(", ")", ")", "data", "=", "'{'", "for", "key", "in", "msg_keys", "[", ":", "-", "1", "]", ":", "data", "+=", "mavlink_to_json", ...
Translate MPStatus in json string
[ "Translate", "MPStatus", "in", "json", "string" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_restserver.py#L27-L35
train
230,375
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_restserver.py
RestServer.set_ip_port
def set_ip_port(self, ip, port): '''set ip and port''' self.address = ip self.port = port self.stop() self.start()
python
def set_ip_port(self, ip, port): '''set ip and port''' self.address = ip self.port = port self.stop() self.start()
[ "def", "set_ip_port", "(", "self", ",", "ip", ",", "port", ")", ":", "self", ".", "address", "=", "ip", "self", ".", "port", "=", "port", "self", ".", "stop", "(", ")", "self", ".", "start", "(", ")" ]
set ip and port
[ "set", "ip", "and", "port" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_restserver.py#L59-L64
train
230,376
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_restserver.py
RestServer.request
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 entire json if not arg: return json.dumps(status_dict) # Get item from path new_dict = status_dict args = arg.split('/') for key in args: if key in new_dict: new_dict = new_dict[key] else: return '{"key": "%s", "last_dict": %s}' % (key, json.dumps(new_dict)) return json.dumps(new_dict)
python
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 entire json if not arg: return json.dumps(status_dict) # Get item from path new_dict = status_dict args = arg.split('/') for key in args: if key in new_dict: new_dict = new_dict[key] else: return '{"key": "%s", "last_dict": %s}' % (key, json.dumps(new_dict)) return json.dumps(new_dict)
[ "def", "request", "(", "self", ",", "arg", "=", "None", ")", ":", "if", "not", "self", ".", "status", ":", "return", "'{\"result\": \"No message\"}'", "try", ":", "status_dict", "=", "json", ".", "loads", "(", "mpstatus_to_json", "(", "self", ".", "status"...
Deal with requests
[ "Deal", "with", "requests" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_restserver.py#L93-L117
train
230,377
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_battery.py
BatteryModule.power_status_update
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 Vservo < self.settings.servowarn: if now - self.last_servo_warn_time > 30: self.last_servo_warn_time = now self.say("Servo volt %.1f" % Vservo) if Vservo < 1: # prevent continuous announcements on power down self.high_servo_voltage = Vservo if Vcc > 0 and Vcc < self.settings.vccwarn: if now - self.last_vcc_warn_time > 30: self.last_vcc_warn_time = now self.say("Vcc %.1f" % Vcc)
python
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 Vservo < self.settings.servowarn: if now - self.last_servo_warn_time > 30: self.last_servo_warn_time = now self.say("Servo volt %.1f" % Vservo) if Vservo < 1: # prevent continuous announcements on power down self.high_servo_voltage = Vservo if Vcc > 0 and Vcc < self.settings.vccwarn: if now - self.last_vcc_warn_time > 30: self.last_vcc_warn_time = now self.say("Vcc %.1f" % Vcc)
[ "def", "power_status_update", "(", "self", ",", "POWER_STATUS", ")", ":", "now", "=", "time", ".", "time", "(", ")", "Vservo", "=", "POWER_STATUS", ".", "Vservo", "*", "0.001", "Vcc", "=", "POWER_STATUS", ".", "Vcc", "*", "0.001", "self", ".", "high_serv...
update POWER_STATUS warnings level
[ "update", "POWER_STATUS", "warnings", "level" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_battery.py#L101-L118
train
230,378
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_gasheli.py
GasHeliModule.valid_starter_settings
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_chan <= 0 or self.gasheli_settings.starter_chan > 14: print("Invalid starter channel %d" % self.gasheli_settings.starter_chan) return False return True
python
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_chan <= 0 or self.gasheli_settings.starter_chan > 14: print("Invalid starter channel %d" % self.gasheli_settings.starter_chan) return False return True
[ "def", "valid_starter_settings", "(", "self", ")", ":", "if", "self", ".", "gasheli_settings", ".", "ignition_chan", "<=", "0", "or", "self", ".", "gasheli_settings", ".", "ignition_chan", ">", "8", ":", "print", "(", "\"Invalid ignition channel %d\"", "%", "sel...
check starter settings
[ "check", "starter", "settings" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_gasheli.py#L73-L81
train
230,379
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_gasheli.py
GasHeliModule.cmd_gasheli
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 args[0] == "set": self.gasheli_settings.command(args[1:]) else: print(usage)
python
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 args[0] == "set": self.gasheli_settings.command(args[1:]) else: print(usage)
[ "def", "cmd_gasheli", "(", "self", ",", "args", ")", ":", "usage", "=", "\"Usage: gasheli <start|stop|set>\"", "if", "len", "(", "args", ")", "<", "1", ":", "print", "(", "usage", ")", "return", "if", "args", "[", "0", "]", "==", "\"start\"", ":", "sel...
gas help commands
[ "gas", "help", "commands" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_gasheli.py#L135-L148
train
230,380
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_wp.py
WPModule.wploader
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
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]
[ "def", "wploader", "(", "self", ")", ":", "if", "self", ".", "target_system", "not", "in", "self", ".", "wploader_by_sysid", ":", "self", ".", "wploader_by_sysid", "[", "self", ".", "target_system", "]", "=", "mavwp", ".", "MAVWPLoader", "(", ")", "return"...
per-sysid wploader
[ "per", "-", "sysid", "wploader" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_wp.py#L60-L64
train
230,381
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_wp.py
WPModule.send_wp_requests
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] = tnow self.master.waypoint_request_send(seq)
python
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] = tnow self.master.waypoint_request_send(seq)
[ "def", "send_wp_requests", "(", "self", ",", "wps", "=", "None", ")", ":", "if", "wps", "is", "None", ":", "wps", "=", "self", ".", "missing_wps_to_request", "(", ")", "tnow", "=", "time", ".", "time", "(", ")", "for", "seq", "in", "wps", ":", "#pr...
send some more WP requests
[ "send", "some", "more", "WP", "requests" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_wp.py#L79-L87
train
230,382
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_wp.py
WPModule.wp_status
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
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)))
[ "def", "wp_status", "(", "self", ")", ":", "try", ":", "print", "(", "\"Have %u of %u waypoints\"", "%", "(", "self", ".", "wploader", ".", "count", "(", ")", "+", "len", "(", "self", ".", "wp_received", ")", ",", "self", ".", "wploader", ".", "expecte...
show status of wp download
[ "show", "status", "of", "wp", "download" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_wp.py#L89-L94
train
230,383
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_wp.py
WPModule.wp_slope
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 is not None: if last_w.frame != w.frame: print("WARNING: frame change %u -> %u at %u" % (last_w.frame, w.frame, i)) delta_alt = last_w.z - w.z if delta_alt == 0: slope = "Level" else: delta_xy = mp_util.gps_distance(w.x, w.y, last_w.x, last_w.y) slope = "%.1f" % (delta_xy / delta_alt) print("WP%u: slope %s" % (i, slope)) last_w = w
python
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 is not None: if last_w.frame != w.frame: print("WARNING: frame change %u -> %u at %u" % (last_w.frame, w.frame, i)) delta_alt = last_w.z - w.z if delta_alt == 0: slope = "Level" else: delta_xy = mp_util.gps_distance(w.x, w.y, last_w.x, last_w.y) slope = "%.1f" % (delta_xy / delta_alt) print("WP%u: slope %s" % (i, slope)) last_w = w
[ "def", "wp_slope", "(", "self", ")", ":", "last_w", "=", "None", "for", "i", "in", "range", "(", "1", ",", "self", ".", "wploader", ".", "count", "(", ")", ")", ":", "w", "=", "self", ".", "wploader", ".", "wp", "(", "i", ")", "if", "w", ".",...
show slope of waypoints
[ "show", "slope", "of", "waypoints" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_wp.py#L97-L114
train
230,384
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_wp.py
WPModule.save_waypoints_csv
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 - %s" % (filename, msg)) return print("Saved %u waypoints to CSV %s" % (self.wploader.count(), filename))
python
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 - %s" % (filename, msg)) return print("Saved %u waypoints to CSV %s" % (self.wploader.count(), filename))
[ "def", "save_waypoints_csv", "(", "self", ",", "filename", ")", ":", "try", ":", "#need to remove the leading and trailing quotes in filename", "self", ".", "wploader", ".", "savecsv", "(", "filename", ".", "strip", "(", "'\"'", ")", ")", "except", "Exception", "a...
save waypoints to a file in a human readable CSV file
[ "save", "waypoints", "to", "a", "file", "in", "a", "human", "readable", "CSV", "file" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_wp.py#L293-L301
train
230,385
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_wp.py
WPModule.get_home
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_component, 0, 0, mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, 0, 0, 0, 0, 0, 0, h.latitude*1.0e-7, h.longitude*1.0e-7, h.altitude*1.0e-3) if self.wploader.count() > 0: return self.wploader.wp(0) return None
python
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_component, 0, 0, mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, 0, 0, 0, 0, 0, 0, h.latitude*1.0e-7, h.longitude*1.0e-7, h.altitude*1.0e-3) if self.wploader.count() > 0: return self.wploader.wp(0) return None
[ "def", "get_home", "(", "self", ")", ":", "if", "'HOME_POSITION'", "in", "self", ".", "master", ".", "messages", ":", "h", "=", "self", ".", "master", ".", "messages", "[", "'HOME_POSITION'", "]", "return", "mavutil", ".", "mavlink", ".", "MAVLink_mission_...
get home location
[ "get", "home", "location" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_wp.py#L313-L326
train
230,386
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_wp.py
WPModule.nofly_add
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 = [] points.append(mp_util.gps_offset(center_lat, center_lon, -25, 25)) points.append(mp_util.gps_offset(center_lat, center_lon, 25, 25)) points.append(mp_util.gps_offset(center_lat, center_lon, 25, -25)) points.append(mp_util.gps_offset(center_lat, center_lon, -25, -25)) start_idx = loader.count() for p in points: wp = mavutil.mavlink.MAVLink_mission_item_message(0, 0, 0, 0, mavutil.mavlink.MAV_CMD_NAV_FENCE_POLYGON_VERTEX_EXCLUSION, 0, 1, 4, 0, 0, 0, p[0], p[1], 0) loader.add(wp) self.loading_waypoints = True self.loading_waypoint_lasttime = time.time() self.master.mav.mission_write_partial_list_send(self.target_system, self.target_component, start_idx, start_idx+4) print("Added nofly zone")
python
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 = [] points.append(mp_util.gps_offset(center_lat, center_lon, -25, 25)) points.append(mp_util.gps_offset(center_lat, center_lon, 25, 25)) points.append(mp_util.gps_offset(center_lat, center_lon, 25, -25)) points.append(mp_util.gps_offset(center_lat, center_lon, -25, -25)) start_idx = loader.count() for p in points: wp = mavutil.mavlink.MAVLink_mission_item_message(0, 0, 0, 0, mavutil.mavlink.MAV_CMD_NAV_FENCE_POLYGON_VERTEX_EXCLUSION, 0, 1, 4, 0, 0, 0, p[0], p[1], 0) loader.add(wp) self.loading_waypoints = True self.loading_waypoint_lasttime = time.time() self.master.mav.mission_write_partial_list_send(self.target_system, self.target_component, start_idx, start_idx+4) print("Added nofly zone")
[ "def", "nofly_add", "(", "self", ")", ":", "try", ":", "latlon", "=", "self", ".", "module", "(", "'map'", ")", ".", "click_position", "except", "Exception", ":", "print", "(", "\"No position chosen\"", ")", "return", "loader", "=", "self", ".", "wploader"...
add a square flight exclusion zone
[ "add", "a", "square", "flight", "exclusion", "zone" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_wp.py#L368-L392
train
230,387
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_wp.py
WPModule.cmd_wp_changealt
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 %u" % idx) return newalt = float(args[1]) if len(args) >= 3: count = int(args[2]) else: count = 1 for wpnum in range(idx, idx+count): wp = self.wploader.wp(wpnum) if not self.wploader.is_location_command(wp.command): continue wp.z = newalt wp.target_system = self.target_system wp.target_component = self.target_component self.wploader.set(wp, wpnum) self.loading_waypoints = True self.loading_waypoint_lasttime = time.time() self.master.mav.mission_write_partial_list_send(self.target_system, self.target_component, idx, idx+count) print("Changed alt for WPs %u:%u to %f" % (idx, idx+(count-1), newalt))
python
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 %u" % idx) return newalt = float(args[1]) if len(args) >= 3: count = int(args[2]) else: count = 1 for wpnum in range(idx, idx+count): wp = self.wploader.wp(wpnum) if not self.wploader.is_location_command(wp.command): continue wp.z = newalt wp.target_system = self.target_system wp.target_component = self.target_component self.wploader.set(wp, wpnum) self.loading_waypoints = True self.loading_waypoint_lasttime = time.time() self.master.mav.mission_write_partial_list_send(self.target_system, self.target_component, idx, idx+count) print("Changed alt for WPs %u:%u to %f" % (idx, idx+(count-1), newalt))
[ "def", "cmd_wp_changealt", "(", "self", ",", "args", ")", ":", "if", "len", "(", "args", ")", "<", "2", ":", "print", "(", "\"usage: wp changealt WPNUM NEWALT <NUMWP>\"", ")", "return", "idx", "=", "int", "(", "args", "[", "0", "]", ")", "if", "idx", "...
handle wp change target alt of multiple waypoints
[ "handle", "wp", "change", "target", "alt", "of", "multiple", "waypoints" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_wp.py#L535-L564
train
230,388
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_wp.py
WPModule.cmd_wp_remove
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.wploader.wp(idx) # setup for undo self.undo_wp = copy.copy(wp) self.undo_wp_idx = idx self.undo_type = "remove" self.wploader.remove(wp) self.fix_jumps(idx, -1) self.send_all_waypoints() print("Removed WP %u" % idx)
python
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.wploader.wp(idx) # setup for undo self.undo_wp = copy.copy(wp) self.undo_wp_idx = idx self.undo_type = "remove" self.wploader.remove(wp) self.fix_jumps(idx, -1) self.send_all_waypoints() print("Removed WP %u" % idx)
[ "def", "cmd_wp_remove", "(", "self", ",", "args", ")", ":", "if", "len", "(", "args", ")", "!=", "1", ":", "print", "(", "\"usage: wp remove WPNUM\"", ")", "return", "idx", "=", "int", "(", "args", "[", "0", "]", ")", "if", "idx", "<", "0", "or", ...
handle wp remove
[ "handle", "wp", "remove" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_wp.py#L580-L599
train
230,389
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_wp.py
WPModule.cmd_wp_undo
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 = self.target_component self.loading_waypoints = True self.loading_waypoint_lasttime = time.time() self.master.mav.mission_write_partial_list_send(self.target_system, self.target_component, self.undo_wp_idx, self.undo_wp_idx) self.wploader.set(wp, self.undo_wp_idx) print("Undid WP move") elif self.undo_type == 'remove': self.wploader.insert(self.undo_wp_idx, wp) self.fix_jumps(self.undo_wp_idx, 1) self.send_all_waypoints() print("Undid WP remove") else: print("bad undo type") self.undo_wp = None self.undo_wp_idx = -1
python
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 = self.target_component self.loading_waypoints = True self.loading_waypoint_lasttime = time.time() self.master.mav.mission_write_partial_list_send(self.target_system, self.target_component, self.undo_wp_idx, self.undo_wp_idx) self.wploader.set(wp, self.undo_wp_idx) print("Undid WP move") elif self.undo_type == 'remove': self.wploader.insert(self.undo_wp_idx, wp) self.fix_jumps(self.undo_wp_idx, 1) self.send_all_waypoints() print("Undid WP remove") else: print("bad undo type") self.undo_wp = None self.undo_wp_idx = -1
[ "def", "cmd_wp_undo", "(", "self", ")", ":", "if", "self", ".", "undo_wp_idx", "==", "-", "1", "or", "self", ".", "undo_wp", "is", "None", ":", "print", "(", "\"No undo information\"", ")", "return", "wp", "=", "self", ".", "undo_wp", "if", "self", "."...
handle wp undo
[ "handle", "wp", "undo" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_wp.py#L601-L625
train
230,390
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_wp.py
WPModule.csv_line
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
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])
[ "def", "csv_line", "(", "self", ",", "line", ")", ":", "self", ".", "csv_sep", "=", "\",\"", "return", "self", ".", "csv_sep", ".", "join", "(", "[", "'\"'", "+", "str", "(", "x", ")", "+", "'\"'", "for", "x", "in", "line", "]", ")" ]
turn a list of values into a CSV line
[ "turn", "a", "list", "of", "values", "into", "a", "CSV", "line" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_wp.py#L778-L781
train
230,391
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_wp.py
WPModule.savecsv
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.wploader.wpoints: if getattr(w, 'comment', None): # f.write("# %s\n" % w.comment) pass out_list = [ w.seq, self.pretty_enum_value('MAV_FRAME', w.frame), self.pretty_enum_value('MAV_CMD', w.command), self.pretty_parameter_value(w.param1), self.pretty_parameter_value(w.param2), self.pretty_parameter_value(w.param3), self.pretty_parameter_value(w.param4), self.pretty_parameter_value(w.x), self.pretty_parameter_value(w.y), self.pretty_parameter_value(w.z), ] print(self.csv_line(out_list)) f.write(self.csv_line(out_list) + "\n") f.close()
python
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.wploader.wpoints: if getattr(w, 'comment', None): # f.write("# %s\n" % w.comment) pass out_list = [ w.seq, self.pretty_enum_value('MAV_FRAME', w.frame), self.pretty_enum_value('MAV_CMD', w.command), self.pretty_parameter_value(w.param1), self.pretty_parameter_value(w.param2), self.pretty_parameter_value(w.param3), self.pretty_parameter_value(w.param4), self.pretty_parameter_value(w.x), self.pretty_parameter_value(w.y), self.pretty_parameter_value(w.z), ] print(self.csv_line(out_list)) f.write(self.csv_line(out_list) + "\n") f.close()
[ "def", "savecsv", "(", "self", ",", "filename", ")", ":", "f", "=", "open", "(", "filename", ",", "mode", "=", "'w'", ")", "headers", "=", "[", "\"Seq\"", ",", "\"Frame\"", ",", "\"Cmd\"", ",", "\"P1\"", ",", "\"P2\"", ",", "\"P3\"", ",", "\"P4\"", ...
save waypoints to a file in human-readable CSV file
[ "save", "waypoints", "to", "a", "file", "in", "human", "-", "readable", "CSV", "file" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_wp.py#L787-L810
train
230,392
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_joystick/findjoy.py
list_joysticks
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
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()))
[ "def", "list_joysticks", "(", ")", ":", "print", "(", "'Available joysticks:'", ")", "print", "(", ")", "for", "jid", "in", "range", "(", "pygame", ".", "joystick", ".", "get_count", "(", ")", ")", ":", "j", "=", "pygame", ".", "joystick", ".", "Joysti...
Print a list of available joysticks
[ "Print", "a", "list", "of", "available", "joysticks" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_joystick/findjoy.py#L30-L37
train
230,393
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_joystick/findjoy.py
select_joystick
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': return elif choice.isdigit(): jid = int(choice) if jid not in range(pygame.joystick.get_count()): print('Invalid joystick.') continue break else: print('What?') return jid
python
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': return elif choice.isdigit(): jid = int(choice) if jid not in range(pygame.joystick.get_count()): print('Invalid joystick.') continue break else: print('What?') return jid
[ "def", "select_joystick", "(", ")", ":", "list_joysticks", "(", ")", "while", "True", ":", "print", "(", "'Select a joystick (L to list, Q to quit)'", ")", ",", "choice", "=", "sys", ".", "stdin", ".", "readline", "(", ")", ".", "strip", "(", ")", "if", "c...
Allow user to select a joystick from a menu
[ "Allow", "user", "to", "select", "a", "joystick", "from", "a", "menu" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_joystick/findjoy.py#L40-L62
train
230,394
ArduPilot/MAVProxy
MAVProxy/modules/lib/MacOS/wxversion.py
select
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 beginning of the application before wxPython is imported. :param versions: Specifies the version to look for, it can either be a string or a list of strings. Each string is compared to the installed wxPythons and the best match is inserted into the sys.path, allowing an 'import wx' to find that version. The version string is composed of the dotted version number (at least 2 of the 4 components) optionally followed by hyphen ('-') separated options (wx port, unicode/ansi, flavour, etc.) A match is determined by how much of the installed version matches what is given in the version parameter. If the version number components don't match then the score is zero, otherwise the score is increased for every specified optional component that is specified and that matches. Please note, however, that it is possible for a match to be selected that doesn't exactly match the versions requested. The only component that is required to be matched is the version number. If you need to require a match on the other components as well, then please use the optional ``optionsRequired`` parameter described next. :param optionsRequired: Allows you to specify that the other components of the version string (such as the port name or character type) are also required to be present for an installed version to be considered a match. Using this parameter allows you to change the selection from a soft, as close as possible match to a hard, exact match. """ if type(versions) == str: versions = [versions] global _selected if _selected is not None: # A version was previously selected, ensure that it matches # this new request for ver in versions: if _selected.Score(_wxPackageInfo(ver), optionsRequired) > 0: return # otherwise, raise an exception raise VersionError("A previously selected wx version does not match the new request.") # If we get here then this is the first time wxversion is used, # ensure that wxPython hasn't been imported yet. if sys.modules.has_key('wx') or sys.modules.has_key('wxPython'): raise AlreadyImportedError("wxversion.select() must be called before wxPython is imported") # Look for a matching version and manipulate the sys.path as # needed to allow it to be imported. installed = _find_installed(True) bestMatch = _get_best_match(installed, versions, optionsRequired) if bestMatch is None: raise VersionError("Requested version of wxPython not found") sys.path.insert(0, bestMatch.pathname) # q.v. Bug #1409256 path64 = re.sub('/lib/','/lib64/',bestMatch.pathname) if os.path.isdir(path64): sys.path.insert(0, path64) _selected = bestMatch
python
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 beginning of the application before wxPython is imported. :param versions: Specifies the version to look for, it can either be a string or a list of strings. Each string is compared to the installed wxPythons and the best match is inserted into the sys.path, allowing an 'import wx' to find that version. The version string is composed of the dotted version number (at least 2 of the 4 components) optionally followed by hyphen ('-') separated options (wx port, unicode/ansi, flavour, etc.) A match is determined by how much of the installed version matches what is given in the version parameter. If the version number components don't match then the score is zero, otherwise the score is increased for every specified optional component that is specified and that matches. Please note, however, that it is possible for a match to be selected that doesn't exactly match the versions requested. The only component that is required to be matched is the version number. If you need to require a match on the other components as well, then please use the optional ``optionsRequired`` parameter described next. :param optionsRequired: Allows you to specify that the other components of the version string (such as the port name or character type) are also required to be present for an installed version to be considered a match. Using this parameter allows you to change the selection from a soft, as close as possible match to a hard, exact match. """ if type(versions) == str: versions = [versions] global _selected if _selected is not None: # A version was previously selected, ensure that it matches # this new request for ver in versions: if _selected.Score(_wxPackageInfo(ver), optionsRequired) > 0: return # otherwise, raise an exception raise VersionError("A previously selected wx version does not match the new request.") # If we get here then this is the first time wxversion is used, # ensure that wxPython hasn't been imported yet. if sys.modules.has_key('wx') or sys.modules.has_key('wxPython'): raise AlreadyImportedError("wxversion.select() must be called before wxPython is imported") # Look for a matching version and manipulate the sys.path as # needed to allow it to be imported. installed = _find_installed(True) bestMatch = _get_best_match(installed, versions, optionsRequired) if bestMatch is None: raise VersionError("Requested version of wxPython not found") sys.path.insert(0, bestMatch.pathname) # q.v. Bug #1409256 path64 = re.sub('/lib/','/lib64/',bestMatch.pathname) if os.path.isdir(path64): sys.path.insert(0, path64) _selected = bestMatch
[ "def", "select", "(", "versions", ",", "optionsRequired", "=", "False", ")", ":", "if", "type", "(", "versions", ")", "==", "str", ":", "versions", "=", "[", "versions", "]", "global", "_selected", "if", "_selected", "is", "not", "None", ":", "# A versio...
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 beginning of the application before wxPython is imported. :param versions: Specifies the version to look for, it can either be a string or a list of strings. Each string is compared to the installed wxPythons and the best match is inserted into the sys.path, allowing an 'import wx' to find that version. The version string is composed of the dotted version number (at least 2 of the 4 components) optionally followed by hyphen ('-') separated options (wx port, unicode/ansi, flavour, etc.) A match is determined by how much of the installed version matches what is given in the version parameter. If the version number components don't match then the score is zero, otherwise the score is increased for every specified optional component that is specified and that matches. Please note, however, that it is possible for a match to be selected that doesn't exactly match the versions requested. The only component that is required to be matched is the version number. If you need to require a match on the other components as well, then please use the optional ``optionsRequired`` parameter described next. :param optionsRequired: Allows you to specify that the other components of the version string (such as the port name or character type) are also required to be present for an installed version to be considered a match. Using this parameter allows you to change the selection from a soft, as close as possible match to a hard, exact match.
[ "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",...
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/lib/MacOS/wxversion.py#L89-L159
train
230,395
ArduPilot/MAVProxy
MAVProxy/modules/lib/MacOS/wxversion.py
ensureMinimal
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 user and will offer to open their web browser to the wxPython downloads page, and will then exit the application. """ assert type(minVersion) == str # ensure that wxPython hasn't been imported yet. if sys.modules.has_key('wx') or sys.modules.has_key('wxPython'): raise AlreadyImportedError("wxversion.ensureMinimal() must be called before wxPython is imported") bestMatch = None minv = _wxPackageInfo(minVersion) # check the default version first defaultPath = _find_default() if defaultPath: defv = _wxPackageInfo(defaultPath, True) if defv >= minv and minv.CheckOptions(defv, optionsRequired): bestMatch = defv # if still no match then check look at all installed versions if bestMatch is None: installed = _find_installed() # The list is in reverse sorted order, so find the first # one that is big enough and optionally matches the # options for inst in installed: if inst >= minv and minv.CheckOptions(inst, optionsRequired): bestMatch = inst break # if still no match then prompt the user if bestMatch is None: if _EM_DEBUG: # We'll do it this way just for the test code below raise VersionError("Requested version of wxPython not found") import wx, webbrowser versions = "\n".join([" "+ver for ver in getInstalled()]) app = wx.App() result = wx.MessageBox("This application requires a version of wxPython " "greater than or equal to %s, but a matching version " "was not found.\n\n" "You currently have these version(s) installed:\n%s\n\n" "Would you like to download a new version of wxPython?\n" % (minVersion, versions), "wxPython Upgrade Needed", style=wx.YES_NO) if result == wx.YES: webbrowser.open(UPDATE_URL) app.MainLoop() sys.exit() sys.path.insert(0, bestMatch.pathname) # q.v. Bug #1409256 path64 = re.sub('/lib/','/lib64/',bestMatch.pathname) if os.path.isdir(path64): sys.path.insert(0, path64) global _selected _selected = bestMatch
python
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 user and will offer to open their web browser to the wxPython downloads page, and will then exit the application. """ assert type(minVersion) == str # ensure that wxPython hasn't been imported yet. if sys.modules.has_key('wx') or sys.modules.has_key('wxPython'): raise AlreadyImportedError("wxversion.ensureMinimal() must be called before wxPython is imported") bestMatch = None minv = _wxPackageInfo(minVersion) # check the default version first defaultPath = _find_default() if defaultPath: defv = _wxPackageInfo(defaultPath, True) if defv >= minv and minv.CheckOptions(defv, optionsRequired): bestMatch = defv # if still no match then check look at all installed versions if bestMatch is None: installed = _find_installed() # The list is in reverse sorted order, so find the first # one that is big enough and optionally matches the # options for inst in installed: if inst >= minv and minv.CheckOptions(inst, optionsRequired): bestMatch = inst break # if still no match then prompt the user if bestMatch is None: if _EM_DEBUG: # We'll do it this way just for the test code below raise VersionError("Requested version of wxPython not found") import wx, webbrowser versions = "\n".join([" "+ver for ver in getInstalled()]) app = wx.App() result = wx.MessageBox("This application requires a version of wxPython " "greater than or equal to %s, but a matching version " "was not found.\n\n" "You currently have these version(s) installed:\n%s\n\n" "Would you like to download a new version of wxPython?\n" % (minVersion, versions), "wxPython Upgrade Needed", style=wx.YES_NO) if result == wx.YES: webbrowser.open(UPDATE_URL) app.MainLoop() sys.exit() sys.path.insert(0, bestMatch.pathname) # q.v. Bug #1409256 path64 = re.sub('/lib/','/lib64/',bestMatch.pathname) if os.path.isdir(path64): sys.path.insert(0, path64) global _selected _selected = bestMatch
[ "def", "ensureMinimal", "(", "minVersion", ",", "optionsRequired", "=", "False", ")", ":", "assert", "type", "(", "minVersion", ")", "==", "str", "# ensure that wxPython hasn't been imported yet.", "if", "sys", ".", "modules", ".", "has_key", "(", "'wx'", ")", "...
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 user and will offer to open their web browser to the wxPython downloads page, and will then exit the application.
[ "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", ">", "...
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/lib/MacOS/wxversion.py#L168-L230
train
230,396
ArduPilot/MAVProxy
MAVProxy/modules/lib/MacOS/wxversion.py
checkInstalled
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`, either a string or a list of strings specifying the version(s) to check for. :param optionsRequired: Same as in `select`. """ if type(versions) == str: versions = [versions] installed = _find_installed() bestMatch = _get_best_match(installed, versions, optionsRequired) return bestMatch is not None
python
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`, either a string or a list of strings specifying the version(s) to check for. :param optionsRequired: Same as in `select`. """ if type(versions) == str: versions = [versions] installed = _find_installed() bestMatch = _get_best_match(installed, versions, optionsRequired) return bestMatch is not None
[ "def", "checkInstalled", "(", "versions", ",", "optionsRequired", "=", "False", ")", ":", "if", "type", "(", "versions", ")", "==", "str", ":", "versions", "=", "[", "versions", "]", "installed", "=", "_find_installed", "(", ")", "bestMatch", "=", "_get_be...
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`, either a string or a list of strings specifying the version(s) to check for. :param optionsRequired: Same as in `select`.
[ "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", ...
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/lib/MacOS/wxversion.py#L235-L251
train
230,397
ArduPilot/MAVProxy
MAVProxy/modules/lib/MacOS/wxversion.py
getInstalled
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
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]
[ "def", "getInstalled", "(", ")", ":", "installed", "=", "_find_installed", "(", ")", "return", "[", "os", ".", "path", ".", "basename", "(", "p", ".", "pathname", ")", "[", "3", ":", "]", "for", "p", "in", "installed", "]" ]
Returns a list of strings representing the installed wxPython versions that are found on the system.
[ "Returns", "a", "list", "of", "strings", "representing", "the", "installed", "wxPython", "versions", "that", "are", "found", "on", "the", "system", "." ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/lib/MacOS/wxversion.py#L255-L261
train
230,398
ArduPilot/MAVProxy
MAVProxy/tools/MAVExplorer.py
flightmode_colours
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 if idx >= len(flightmode_colours): idx = 0 return mapping
python
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 if idx >= len(flightmode_colours): idx = 0 return mapping
[ "def", "flightmode_colours", "(", ")", ":", "from", "MAVProxy", ".", "modules", ".", "lib", ".", "grapher", "import", "flightmode_colours", "mapping", "=", "{", "}", "idx", "=", "0", "for", "(", "mode", ",", "t0", ",", "t1", ")", "in", "flightmodes", "...
return mapping of flight mode to colours
[ "return", "mapping", "of", "flight", "mode", "to", "colours" ]
f50bdeff33064876f7dc8dc4683d278ff47f75d5
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/tools/MAVExplorer.py#L279-L290
train
230,399