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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_terrain.py | TerrainModule.cmd_terrain_check | def cmd_terrain_check(self, args):
'''check a piece of terrain data'''
if len(args) >= 2:
latlon = (float(args[0]), float(args[1]))
else:
try:
latlon = self.module('map').click_position
except Exception:
print("No map available")
return
if latlon is None:
print("No map click position available")
return
self.check_lat = int(latlon[0]*1e7)
self.check_lon = int(latlon[1]*1e7)
self.master.mav.terrain_check_send(self.check_lat, self.check_lon) | python | def cmd_terrain_check(self, args):
'''check a piece of terrain data'''
if len(args) >= 2:
latlon = (float(args[0]), float(args[1]))
else:
try:
latlon = self.module('map').click_position
except Exception:
print("No map available")
return
if latlon is None:
print("No map click position available")
return
self.check_lat = int(latlon[0]*1e7)
self.check_lon = int(latlon[1]*1e7)
self.master.mav.terrain_check_send(self.check_lat, self.check_lon) | [
"def",
"cmd_terrain_check",
"(",
"self",
",",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
">=",
"2",
":",
"latlon",
"=",
"(",
"float",
"(",
"args",
"[",
"0",
"]",
")",
",",
"float",
"(",
"args",
"[",
"1",
"]",
")",
")",
"else",
":",
"try... | check a piece of terrain data | [
"check",
"a",
"piece",
"of",
"terrain",
"data"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_terrain.py#L49-L64 | train | 230,600 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_terrain.py | TerrainModule.idle_task | def idle_task(self):
'''called when idle'''
if self.current_request is None:
return
if time.time() - self.last_send_time < 0.2:
# limit to 5 per second
return
self.send_terrain_data() | python | def idle_task(self):
'''called when idle'''
if self.current_request is None:
return
if time.time() - self.last_send_time < 0.2:
# limit to 5 per second
return
self.send_terrain_data() | [
"def",
"idle_task",
"(",
"self",
")",
":",
"if",
"self",
".",
"current_request",
"is",
"None",
":",
"return",
"if",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"last_send_time",
"<",
"0.2",
":",
"# limit to 5 per second",
"return",
"self",
".",
"sen... | called when idle | [
"called",
"when",
"idle"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_terrain.py#L134-L141 | train | 230,601 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_mode.py | ModeModule.unknown_command | def unknown_command(self, args):
'''handle mode switch by mode name as command'''
mode_mapping = self.master.mode_mapping()
mode = args[0].upper()
if mode in mode_mapping:
self.master.set_mode(mode_mapping[mode])
return True
return False | python | def unknown_command(self, args):
'''handle mode switch by mode name as command'''
mode_mapping = self.master.mode_mapping()
mode = args[0].upper()
if mode in mode_mapping:
self.master.set_mode(mode_mapping[mode])
return True
return False | [
"def",
"unknown_command",
"(",
"self",
",",
"args",
")",
":",
"mode_mapping",
"=",
"self",
".",
"master",
".",
"mode_mapping",
"(",
")",
"mode",
"=",
"args",
"[",
"0",
"]",
".",
"upper",
"(",
")",
"if",
"mode",
"in",
"mode_mapping",
":",
"self",
".",... | handle mode switch by mode name as command | [
"handle",
"mode",
"switch",
"by",
"mode",
"name",
"as",
"command"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_mode.py#L41-L48 | train | 230,602 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_mode.py | ModeModule.cmd_guided | def cmd_guided(self, args):
'''set GUIDED target'''
if len(args) != 1 and len(args) != 3:
print("Usage: guided ALTITUDE | guided LAT LON ALTITUDE")
return
if len(args) == 3:
latitude = float(args[0])
longitude = float(args[1])
altitude = float(args[2])
latlon = (latitude, longitude)
else:
try:
latlon = self.module('map').click_position
except Exception:
print("No map available")
return
if latlon is None:
print("No map click position available")
return
altitude = float(args[0])
print("Guided %s %s" % (str(latlon), str(altitude)))
self.master.mav.mission_item_send (self.settings.target_system,
self.settings.target_component,
0,
self.module('wp').get_default_frame(),
mavutil.mavlink.MAV_CMD_NAV_WAYPOINT,
2, 0, 0, 0, 0, 0,
latlon[0], latlon[1], altitude) | python | def cmd_guided(self, args):
'''set GUIDED target'''
if len(args) != 1 and len(args) != 3:
print("Usage: guided ALTITUDE | guided LAT LON ALTITUDE")
return
if len(args) == 3:
latitude = float(args[0])
longitude = float(args[1])
altitude = float(args[2])
latlon = (latitude, longitude)
else:
try:
latlon = self.module('map').click_position
except Exception:
print("No map available")
return
if latlon is None:
print("No map click position available")
return
altitude = float(args[0])
print("Guided %s %s" % (str(latlon), str(altitude)))
self.master.mav.mission_item_send (self.settings.target_system,
self.settings.target_component,
0,
self.module('wp').get_default_frame(),
mavutil.mavlink.MAV_CMD_NAV_WAYPOINT,
2, 0, 0, 0, 0, 0,
latlon[0], latlon[1], altitude) | [
"def",
"cmd_guided",
"(",
"self",
",",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"!=",
"1",
"and",
"len",
"(",
"args",
")",
"!=",
"3",
":",
"print",
"(",
"\"Usage: guided ALTITUDE | guided LAT LON ALTITUDE\"",
")",
"return",
"if",
"len",
"(",
"arg... | set GUIDED target | [
"set",
"GUIDED",
"target"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_mode.py#L50-L79 | train | 230,603 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_HIL.py | HILModule.check_sim_in | def check_sim_in(self):
'''check for FDM packets from runsim'''
try:
pkt = self.sim_in.recv(17*8 + 4)
except socket.error as e:
if not e.errno in [ errno.EAGAIN, errno.EWOULDBLOCK ]:
raise
return
if len(pkt) != 17*8 + 4:
# wrong size, discard it
print("wrong size %u" % len(pkt))
return
(latitude, longitude, altitude, heading, v_north, v_east, v_down,
ax, ay, az,
phidot, thetadot, psidot,
roll, pitch, yaw,
vcas, check) = struct.unpack('<17dI', pkt)
(p, q, r) = self.convert_body_frame(radians(roll), radians(pitch), radians(phidot), radians(thetadot), radians(psidot))
try:
self.hil_state_msg = self.master.mav.hil_state_encode(int(time.time()*1e6),
radians(roll),
radians(pitch),
radians(yaw),
p,
q,
r,
int(latitude*1.0e7),
int(longitude*1.0e7),
int(altitude*1.0e3),
int(v_north*100),
int(v_east*100),
0,
int(ax*1000/9.81),
int(ay*1000/9.81),
int(az*1000/9.81))
except Exception:
return | python | def check_sim_in(self):
'''check for FDM packets from runsim'''
try:
pkt = self.sim_in.recv(17*8 + 4)
except socket.error as e:
if not e.errno in [ errno.EAGAIN, errno.EWOULDBLOCK ]:
raise
return
if len(pkt) != 17*8 + 4:
# wrong size, discard it
print("wrong size %u" % len(pkt))
return
(latitude, longitude, altitude, heading, v_north, v_east, v_down,
ax, ay, az,
phidot, thetadot, psidot,
roll, pitch, yaw,
vcas, check) = struct.unpack('<17dI', pkt)
(p, q, r) = self.convert_body_frame(radians(roll), radians(pitch), radians(phidot), radians(thetadot), radians(psidot))
try:
self.hil_state_msg = self.master.mav.hil_state_encode(int(time.time()*1e6),
radians(roll),
radians(pitch),
radians(yaw),
p,
q,
r,
int(latitude*1.0e7),
int(longitude*1.0e7),
int(altitude*1.0e3),
int(v_north*100),
int(v_east*100),
0,
int(ax*1000/9.81),
int(ay*1000/9.81),
int(az*1000/9.81))
except Exception:
return | [
"def",
"check_sim_in",
"(",
"self",
")",
":",
"try",
":",
"pkt",
"=",
"self",
".",
"sim_in",
".",
"recv",
"(",
"17",
"*",
"8",
"+",
"4",
")",
"except",
"socket",
".",
"error",
"as",
"e",
":",
"if",
"not",
"e",
".",
"errno",
"in",
"[",
"errno",
... | check for FDM packets from runsim | [
"check",
"for",
"FDM",
"packets",
"from",
"runsim"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_HIL.py#L53-L90 | train | 230,604 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_HIL.py | HILModule.check_sim_out | def check_sim_out(self):
'''check if we should send new servos to flightgear'''
now = time.time()
if now - self.last_sim_send_time < 0.02 or self.rc_channels_scaled is None:
return
self.last_sim_send_time = now
servos = []
for ch in range(1,9):
servos.append(self.scale_channel(ch, getattr(self.rc_channels_scaled, 'chan%u_scaled' % ch)))
servos.extend([0,0,0, 0,0,0])
buf = struct.pack('<14H', *servos)
try:
self.sim_out.send(buf)
except socket.error as e:
if not e.errno in [ errno.ECONNREFUSED ]:
raise
return | python | def check_sim_out(self):
'''check if we should send new servos to flightgear'''
now = time.time()
if now - self.last_sim_send_time < 0.02 or self.rc_channels_scaled is None:
return
self.last_sim_send_time = now
servos = []
for ch in range(1,9):
servos.append(self.scale_channel(ch, getattr(self.rc_channels_scaled, 'chan%u_scaled' % ch)))
servos.extend([0,0,0, 0,0,0])
buf = struct.pack('<14H', *servos)
try:
self.sim_out.send(buf)
except socket.error as e:
if not e.errno in [ errno.ECONNREFUSED ]:
raise
return | [
"def",
"check_sim_out",
"(",
"self",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"if",
"now",
"-",
"self",
".",
"last_sim_send_time",
"<",
"0.02",
"or",
"self",
".",
"rc_channels_scaled",
"is",
"None",
":",
"return",
"self",
".",
"last_sim_send_... | check if we should send new servos to flightgear | [
"check",
"if",
"we",
"should",
"send",
"new",
"servos",
"to",
"flightgear"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_HIL.py#L95-L112 | train | 230,605 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_HIL.py | HILModule.check_apm_out | def check_apm_out(self):
'''check if we should send new data to the APM'''
now = time.time()
if now - self.last_apm_send_time < 0.02:
return
self.last_apm_send_time = now
if self.hil_state_msg is not None:
self.master.mav.send(self.hil_state_msg) | python | def check_apm_out(self):
'''check if we should send new data to the APM'''
now = time.time()
if now - self.last_apm_send_time < 0.02:
return
self.last_apm_send_time = now
if self.hil_state_msg is not None:
self.master.mav.send(self.hil_state_msg) | [
"def",
"check_apm_out",
"(",
"self",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"if",
"now",
"-",
"self",
".",
"last_apm_send_time",
"<",
"0.02",
":",
"return",
"self",
".",
"last_apm_send_time",
"=",
"now",
"if",
"self",
".",
"hil_state_msg",
... | check if we should send new data to the APM | [
"check",
"if",
"we",
"should",
"send",
"new",
"data",
"to",
"the",
"APM"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_HIL.py#L115-L122 | train | 230,606 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_HIL.py | HILModule.convert_body_frame | def convert_body_frame(self, phi, theta, phiDot, thetaDot, psiDot):
'''convert a set of roll rates from earth frame to body frame'''
p = phiDot - psiDot*math.sin(theta)
q = math.cos(phi)*thetaDot + math.sin(phi)*psiDot*math.cos(theta)
r = math.cos(phi)*psiDot*math.cos(theta) - math.sin(phi)*thetaDot
return (p, q, r) | python | def convert_body_frame(self, phi, theta, phiDot, thetaDot, psiDot):
'''convert a set of roll rates from earth frame to body frame'''
p = phiDot - psiDot*math.sin(theta)
q = math.cos(phi)*thetaDot + math.sin(phi)*psiDot*math.cos(theta)
r = math.cos(phi)*psiDot*math.cos(theta) - math.sin(phi)*thetaDot
return (p, q, r) | [
"def",
"convert_body_frame",
"(",
"self",
",",
"phi",
",",
"theta",
",",
"phiDot",
",",
"thetaDot",
",",
"psiDot",
")",
":",
"p",
"=",
"phiDot",
"-",
"psiDot",
"*",
"math",
".",
"sin",
"(",
"theta",
")",
"q",
"=",
"math",
".",
"cos",
"(",
"phi",
... | convert a set of roll rates from earth frame to body frame | [
"convert",
"a",
"set",
"of",
"roll",
"rates",
"from",
"earth",
"frame",
"to",
"body",
"frame"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_HIL.py#L124-L129 | train | 230,607 |
ArduPilot/MAVProxy | MAVProxy/modules/lib/mp_settings.py | MPSettings.append | def append(self, v):
'''add a new setting'''
if isinstance(v, MPSetting):
setting = v
else:
(name,type,default) = v
label = name
tab = None
if len(v) > 3:
label = v[3]
if len(v) > 4:
tab = v[4]
setting = MPSetting(name, type, default, label=label, tab=tab)
# when a tab name is set, cascade it to future settings
if setting.tab is None:
setting.tab = self._default_tab
else:
self._default_tab = setting.tab
self._vars[setting.name] = setting
self._keys.append(setting.name)
self._last_change = time.time() | python | def append(self, v):
'''add a new setting'''
if isinstance(v, MPSetting):
setting = v
else:
(name,type,default) = v
label = name
tab = None
if len(v) > 3:
label = v[3]
if len(v) > 4:
tab = v[4]
setting = MPSetting(name, type, default, label=label, tab=tab)
# when a tab name is set, cascade it to future settings
if setting.tab is None:
setting.tab = self._default_tab
else:
self._default_tab = setting.tab
self._vars[setting.name] = setting
self._keys.append(setting.name)
self._last_change = time.time() | [
"def",
"append",
"(",
"self",
",",
"v",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"MPSetting",
")",
":",
"setting",
"=",
"v",
"else",
":",
"(",
"name",
",",
"type",
",",
"default",
")",
"=",
"v",
"label",
"=",
"name",
"tab",
"=",
"None",
"if... | add a new setting | [
"add",
"a",
"new",
"setting"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/lib/mp_settings.py#L80-L101 | train | 230,608 |
ArduPilot/MAVProxy | MAVProxy/modules/lib/mp_settings.py | MPSettings.get | def get(self, name):
'''get a setting'''
if not name in self._vars:
raise AttributeError
setting = self._vars[name]
return setting.value | python | def get(self, name):
'''get a setting'''
if not name in self._vars:
raise AttributeError
setting = self._vars[name]
return setting.value | [
"def",
"get",
"(",
"self",
",",
"name",
")",
":",
"if",
"not",
"name",
"in",
"self",
".",
"_vars",
":",
"raise",
"AttributeError",
"setting",
"=",
"self",
".",
"_vars",
"[",
"name",
"]",
"return",
"setting",
".",
"value"
] | get a setting | [
"get",
"a",
"setting"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/lib/mp_settings.py#L134-L139 | train | 230,609 |
ArduPilot/MAVProxy | MAVProxy/modules/lib/mp_settings.py | MPSettings.command | def command(self, args):
'''control options from cmdline'''
if len(args) == 0:
self.show_all()
return
if getattr(self, args[0], [None]) == [None]:
print("Unknown setting '%s'" % args[0])
return
if len(args) == 1:
self.show(args[0])
else:
self.set(args[0], args[1]) | python | def command(self, args):
'''control options from cmdline'''
if len(args) == 0:
self.show_all()
return
if getattr(self, args[0], [None]) == [None]:
print("Unknown setting '%s'" % args[0])
return
if len(args) == 1:
self.show(args[0])
else:
self.set(args[0], args[1]) | [
"def",
"command",
"(",
"self",
",",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"self",
".",
"show_all",
"(",
")",
"return",
"if",
"getattr",
"(",
"self",
",",
"args",
"[",
"0",
"]",
",",
"[",
"None",
"]",
")",
"==",
"[",... | control options from cmdline | [
"control",
"options",
"from",
"cmdline"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/lib/mp_settings.py#L158-L169 | train | 230,610 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_arm.py | ArmModule.all_checks_enabled | def all_checks_enabled(self):
''' returns true if the UAV is skipping any arming checks'''
arming_mask = int(self.get_mav_param("ARMING_CHECK",0))
if arming_mask == 1:
return True
for bit in arming_masks.values():
if not arming_mask & bit and bit != 1:
return False
return True | python | def all_checks_enabled(self):
''' returns true if the UAV is skipping any arming checks'''
arming_mask = int(self.get_mav_param("ARMING_CHECK",0))
if arming_mask == 1:
return True
for bit in arming_masks.values():
if not arming_mask & bit and bit != 1:
return False
return True | [
"def",
"all_checks_enabled",
"(",
"self",
")",
":",
"arming_mask",
"=",
"int",
"(",
"self",
".",
"get_mav_param",
"(",
"\"ARMING_CHECK\"",
",",
"0",
")",
")",
"if",
"arming_mask",
"==",
"1",
":",
"return",
"True",
"for",
"bit",
"in",
"arming_masks",
".",
... | returns true if the UAV is skipping any arming checks | [
"returns",
"true",
"if",
"the",
"UAV",
"is",
"skipping",
"any",
"arming",
"checks"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_arm.py#L144-L152 | train | 230,611 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_param.py | ParamState.handle_px4_param_value | def handle_px4_param_value(self, m):
'''special handling for the px4 style of PARAM_VALUE'''
if m.param_type == mavutil.mavlink.MAV_PARAM_TYPE_REAL32:
# already right type
return m.param_value
is_px4_params = False
if m.get_srcComponent() in [mavutil.mavlink.MAV_COMP_ID_UDP_BRIDGE]:
# ESP8266 uses PX4 style parameters
is_px4_params = True
sysid = m.get_srcSystem()
if self.autopilot_type_by_sysid.get(sysid,-1) in [mavutil.mavlink.MAV_AUTOPILOT_PX4]:
is_px4_params = True
if not is_px4_params:
return m.param_value
# try to extract px4 param value
value = m.param_value
try:
v = struct.pack(">f", value)
except Exception:
return value
if m.param_type == mavutil.mavlink.MAV_PARAM_TYPE_UINT8:
value, = struct.unpack(">B", v[3:])
elif m.param_type == mavutil.mavlink.MAV_PARAM_TYPE_INT8:
value, = struct.unpack(">b", v[3:])
elif m.param_type == mavutil.mavlink.MAV_PARAM_TYPE_UINT16:
value, = struct.unpack(">H", v[2:])
elif m.param_type == mavutil.mavlink.MAV_PARAM_TYPE_INT16:
value, = struct.unpack(">h", v[2:])
elif m.param_type == mavutil.mavlink.MAV_PARAM_TYPE_UINT32:
value, = struct.unpack(">I", v[0:])
elif m.param_type == mavutil.mavlink.MAV_PARAM_TYPE_INT32:
value, = struct.unpack(">i", v[0:])
# can't pack other types
# remember type for param set
self.param_types[m.param_id.upper()] = m.param_type
return value | python | def handle_px4_param_value(self, m):
'''special handling for the px4 style of PARAM_VALUE'''
if m.param_type == mavutil.mavlink.MAV_PARAM_TYPE_REAL32:
# already right type
return m.param_value
is_px4_params = False
if m.get_srcComponent() in [mavutil.mavlink.MAV_COMP_ID_UDP_BRIDGE]:
# ESP8266 uses PX4 style parameters
is_px4_params = True
sysid = m.get_srcSystem()
if self.autopilot_type_by_sysid.get(sysid,-1) in [mavutil.mavlink.MAV_AUTOPILOT_PX4]:
is_px4_params = True
if not is_px4_params:
return m.param_value
# try to extract px4 param value
value = m.param_value
try:
v = struct.pack(">f", value)
except Exception:
return value
if m.param_type == mavutil.mavlink.MAV_PARAM_TYPE_UINT8:
value, = struct.unpack(">B", v[3:])
elif m.param_type == mavutil.mavlink.MAV_PARAM_TYPE_INT8:
value, = struct.unpack(">b", v[3:])
elif m.param_type == mavutil.mavlink.MAV_PARAM_TYPE_UINT16:
value, = struct.unpack(">H", v[2:])
elif m.param_type == mavutil.mavlink.MAV_PARAM_TYPE_INT16:
value, = struct.unpack(">h", v[2:])
elif m.param_type == mavutil.mavlink.MAV_PARAM_TYPE_UINT32:
value, = struct.unpack(">I", v[0:])
elif m.param_type == mavutil.mavlink.MAV_PARAM_TYPE_INT32:
value, = struct.unpack(">i", v[0:])
# can't pack other types
# remember type for param set
self.param_types[m.param_id.upper()] = m.param_type
return value | [
"def",
"handle_px4_param_value",
"(",
"self",
",",
"m",
")",
":",
"if",
"m",
".",
"param_type",
"==",
"mavutil",
".",
"mavlink",
".",
"MAV_PARAM_TYPE_REAL32",
":",
"# already right type",
"return",
"m",
".",
"param_value",
"is_px4_params",
"=",
"False",
"if",
... | special handling for the px4 style of PARAM_VALUE | [
"special",
"handling",
"for",
"the",
"px4",
"style",
"of",
"PARAM_VALUE"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_param.py#L28-L64 | train | 230,612 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_param.py | ParamState.param_help_download | def param_help_download(self):
'''download XML files for parameters'''
files = []
for vehicle in ['APMrover2', 'ArduCopter', 'ArduPlane', 'ArduSub', 'AntennaTracker']:
url = 'http://autotest.ardupilot.org/Parameters/%s/apm.pdef.xml' % vehicle
path = mp_util.dot_mavproxy("%s.xml" % vehicle)
files.append((url, path))
url = 'http://autotest.ardupilot.org/%s-defaults.parm' % vehicle
if vehicle != 'AntennaTracker':
# defaults not generated for AntennaTracker ATM
path = mp_util.dot_mavproxy("%s-defaults.parm" % vehicle)
files.append((url, path))
try:
child = multiproc.Process(target=mp_util.download_files, args=(files,))
child.start()
except Exception as e:
print(e) | python | def param_help_download(self):
'''download XML files for parameters'''
files = []
for vehicle in ['APMrover2', 'ArduCopter', 'ArduPlane', 'ArduSub', 'AntennaTracker']:
url = 'http://autotest.ardupilot.org/Parameters/%s/apm.pdef.xml' % vehicle
path = mp_util.dot_mavproxy("%s.xml" % vehicle)
files.append((url, path))
url = 'http://autotest.ardupilot.org/%s-defaults.parm' % vehicle
if vehicle != 'AntennaTracker':
# defaults not generated for AntennaTracker ATM
path = mp_util.dot_mavproxy("%s-defaults.parm" % vehicle)
files.append((url, path))
try:
child = multiproc.Process(target=mp_util.download_files, args=(files,))
child.start()
except Exception as e:
print(e) | [
"def",
"param_help_download",
"(",
"self",
")",
":",
"files",
"=",
"[",
"]",
"for",
"vehicle",
"in",
"[",
"'APMrover2'",
",",
"'ArduCopter'",
",",
"'ArduPlane'",
",",
"'ArduSub'",
",",
"'AntennaTracker'",
"]",
":",
"url",
"=",
"'http://autotest.ardupilot.org/Par... | download XML files for parameters | [
"download",
"XML",
"files",
"for",
"parameters"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_param.py#L121-L137 | train | 230,613 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_param.py | ParamState.param_help_tree | def param_help_tree(self):
'''return a "help tree", a map between a parameter and its metadata. May return None if help is not available'''
if self.xml_filepath is not None:
print("param: using xml_filepath=%s" % self.xml_filepath)
path = self.xml_filepath
else:
if self.vehicle_name is None:
print("Unknown vehicle type")
return None
path = mp_util.dot_mavproxy("%s.xml" % self.vehicle_name)
if not os.path.exists(path):
print("Please run 'param download' first (vehicle_name=%s)" % self.vehicle_name)
return None
if not os.path.exists(path):
print("Param XML (%s) does not exist" % path)
return None
xml = open(path,'rb').read()
from lxml import objectify
objectify.enable_recursive_str()
tree = objectify.fromstring(xml)
htree = {}
for p in tree.vehicles.parameters.param:
n = p.get('name').split(':')[1]
htree[n] = p
for lib in tree.libraries.parameters:
for p in lib.param:
n = p.get('name')
htree[n] = p
return htree | python | def param_help_tree(self):
'''return a "help tree", a map between a parameter and its metadata. May return None if help is not available'''
if self.xml_filepath is not None:
print("param: using xml_filepath=%s" % self.xml_filepath)
path = self.xml_filepath
else:
if self.vehicle_name is None:
print("Unknown vehicle type")
return None
path = mp_util.dot_mavproxy("%s.xml" % self.vehicle_name)
if not os.path.exists(path):
print("Please run 'param download' first (vehicle_name=%s)" % self.vehicle_name)
return None
if not os.path.exists(path):
print("Param XML (%s) does not exist" % path)
return None
xml = open(path,'rb').read()
from lxml import objectify
objectify.enable_recursive_str()
tree = objectify.fromstring(xml)
htree = {}
for p in tree.vehicles.parameters.param:
n = p.get('name').split(':')[1]
htree[n] = p
for lib in tree.libraries.parameters:
for p in lib.param:
n = p.get('name')
htree[n] = p
return htree | [
"def",
"param_help_tree",
"(",
"self",
")",
":",
"if",
"self",
".",
"xml_filepath",
"is",
"not",
"None",
":",
"print",
"(",
"\"param: using xml_filepath=%s\"",
"%",
"self",
".",
"xml_filepath",
")",
"path",
"=",
"self",
".",
"xml_filepath",
"else",
":",
"if"... | return a "help tree", a map between a parameter and its metadata. May return None if help is not available | [
"return",
"a",
"help",
"tree",
"a",
"map",
"between",
"a",
"parameter",
"and",
"its",
"metadata",
".",
"May",
"return",
"None",
"if",
"help",
"is",
"not",
"available"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_param.py#L142-L170 | train | 230,614 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_param.py | ParamState.param_apropos | def param_apropos(self, args):
'''search parameter help for a keyword, list those parameters'''
if len(args) == 0:
print("Usage: param apropos keyword")
return
htree = self.param_help_tree()
if htree is None:
return
contains = {}
for keyword in args:
for param in htree.keys():
if str(htree[param]).find(keyword) != -1:
contains[param] = True
for param in contains.keys():
print("%s" % (param,)) | python | def param_apropos(self, args):
'''search parameter help for a keyword, list those parameters'''
if len(args) == 0:
print("Usage: param apropos keyword")
return
htree = self.param_help_tree()
if htree is None:
return
contains = {}
for keyword in args:
for param in htree.keys():
if str(htree[param]).find(keyword) != -1:
contains[param] = True
for param in contains.keys():
print("%s" % (param,)) | [
"def",
"param_apropos",
"(",
"self",
",",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"print",
"(",
"\"Usage: param apropos keyword\"",
")",
"return",
"htree",
"=",
"self",
".",
"param_help_tree",
"(",
")",
"if",
"htree",
"is",
"None... | search parameter help for a keyword, list those parameters | [
"search",
"parameter",
"help",
"for",
"a",
"keyword",
"list",
"those",
"parameters"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_param.py#L175-L191 | train | 230,615 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_param.py | ParamModule.get_component_id_list | def get_component_id_list(self, system_id):
'''get list of component IDs with parameters for a given system ID'''
ret = []
for (s,c) in self.mpstate.mav_param_by_sysid.keys():
if s == system_id:
ret.append(c)
return ret | python | def get_component_id_list(self, system_id):
'''get list of component IDs with parameters for a given system ID'''
ret = []
for (s,c) in self.mpstate.mav_param_by_sysid.keys():
if s == system_id:
ret.append(c)
return ret | [
"def",
"get_component_id_list",
"(",
"self",
",",
"system_id",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"(",
"s",
",",
"c",
")",
"in",
"self",
".",
"mpstate",
".",
"mav_param_by_sysid",
".",
"keys",
"(",
")",
":",
"if",
"s",
"==",
"system_id",
":",
"... | get list of component IDs with parameters for a given system ID | [
"get",
"list",
"of",
"component",
"IDs",
"with",
"parameters",
"for",
"a",
"given",
"system",
"ID"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_param.py#L371-L377 | train | 230,616 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_param.py | ParamModule.get_sysid | def get_sysid(self):
'''get sysid tuple to use for parameters'''
component = self.target_component
if component == 0:
component = 1
return (self.target_system, component) | python | def get_sysid(self):
'''get sysid tuple to use for parameters'''
component = self.target_component
if component == 0:
component = 1
return (self.target_system, component) | [
"def",
"get_sysid",
"(",
"self",
")",
":",
"component",
"=",
"self",
".",
"target_component",
"if",
"component",
"==",
"0",
":",
"component",
"=",
"1",
"return",
"(",
"self",
".",
"target_system",
",",
"component",
")"
] | get sysid tuple to use for parameters | [
"get",
"sysid",
"tuple",
"to",
"use",
"for",
"parameters"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_param.py#L398-L403 | train | 230,617 |
ArduPilot/MAVProxy | MAVProxy/modules/lib/optparse_gui/__init__.py | OptionParser.parse_args | def parse_args( self, args = None, values = None ):
'''
multiprocessing wrapper around _parse_args
'''
q = multiproc.Queue()
p = multiproc.Process(target=self._parse_args, args=(q, args, values))
p.start()
ret = q.get()
p.join()
return ret | python | def parse_args( self, args = None, values = None ):
'''
multiprocessing wrapper around _parse_args
'''
q = multiproc.Queue()
p = multiproc.Process(target=self._parse_args, args=(q, args, values))
p.start()
ret = q.get()
p.join()
return ret | [
"def",
"parse_args",
"(",
"self",
",",
"args",
"=",
"None",
",",
"values",
"=",
"None",
")",
":",
"q",
"=",
"multiproc",
".",
"Queue",
"(",
")",
"p",
"=",
"multiproc",
".",
"Process",
"(",
"target",
"=",
"self",
".",
"_parse_args",
",",
"args",
"="... | multiprocessing wrapper around _parse_args | [
"multiprocessing",
"wrapper",
"around",
"_parse_args"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/lib/optparse_gui/__init__.py#L206-L215 | train | 230,618 |
ArduPilot/MAVProxy | MAVProxy/modules/lib/optparse_gui/__init__.py | OptionParser._parse_args | def _parse_args( self, q, args, values):
'''
This is the heart of it all - overrides optparse.OptionParser.parse_args
@param arg is irrelevant and thus ignored,
it is here only for interface compatibility
'''
if wx.GetApp() is None:
self.app = wx.App( False )
# preprocess command line arguments and set to defaults
option_values, args = self.SUPER.parse_args(self, args, values)
for option in self.option_list:
if option.dest and hasattr(option_values, option.dest):
default = getattr(option_values, option.dest)
if default is not None:
option.default = default
dlg = OptparseDialog( option_parser = self, title=self.get_description() )
if args:
dlg.args_ctrl.Value = ' '.join(args)
dlg_result = dlg.ShowModal()
if wx.ID_OK != dlg_result:
raise UserCancelledError( 'User has canceled' )
if values is None:
values = self.get_default_values()
option_values, args = dlg.getOptionsAndArgs()
for option, value in option_values.iteritems():
if ( 'store_true' == option.action ) and ( value is False ):
setattr( values, option.dest, False )
continue
if ( 'store_false' == option.action ) and ( value is True ):
setattr( values, option.dest, False )
continue
if option.takes_value() is False:
value = None
option.process( option, value, values, self )
q.put((values, args)) | python | def _parse_args( self, q, args, values):
'''
This is the heart of it all - overrides optparse.OptionParser.parse_args
@param arg is irrelevant and thus ignored,
it is here only for interface compatibility
'''
if wx.GetApp() is None:
self.app = wx.App( False )
# preprocess command line arguments and set to defaults
option_values, args = self.SUPER.parse_args(self, args, values)
for option in self.option_list:
if option.dest and hasattr(option_values, option.dest):
default = getattr(option_values, option.dest)
if default is not None:
option.default = default
dlg = OptparseDialog( option_parser = self, title=self.get_description() )
if args:
dlg.args_ctrl.Value = ' '.join(args)
dlg_result = dlg.ShowModal()
if wx.ID_OK != dlg_result:
raise UserCancelledError( 'User has canceled' )
if values is None:
values = self.get_default_values()
option_values, args = dlg.getOptionsAndArgs()
for option, value in option_values.iteritems():
if ( 'store_true' == option.action ) and ( value is False ):
setattr( values, option.dest, False )
continue
if ( 'store_false' == option.action ) and ( value is True ):
setattr( values, option.dest, False )
continue
if option.takes_value() is False:
value = None
option.process( option, value, values, self )
q.put((values, args)) | [
"def",
"_parse_args",
"(",
"self",
",",
"q",
",",
"args",
",",
"values",
")",
":",
"if",
"wx",
".",
"GetApp",
"(",
")",
"is",
"None",
":",
"self",
".",
"app",
"=",
"wx",
".",
"App",
"(",
"False",
")",
"# preprocess command line arguments and set to defau... | This is the heart of it all - overrides optparse.OptionParser.parse_args
@param arg is irrelevant and thus ignored,
it is here only for interface compatibility | [
"This",
"is",
"the",
"heart",
"of",
"it",
"all",
"-",
"overrides",
"optparse",
".",
"OptionParser",
".",
"parse_args"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/lib/optparse_gui/__init__.py#L217-L261 | train | 230,619 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_genobstacles.py | DNFZ.distance_from | def distance_from(self, lat, lon):
'''get distance from a point'''
lat1 = self.pkt['I105']['Lat']['val']
lon1 = self.pkt['I105']['Lon']['val']
return mp_util.gps_distance(lat1, lon1, lat, lon) | python | def distance_from(self, lat, lon):
'''get distance from a point'''
lat1 = self.pkt['I105']['Lat']['val']
lon1 = self.pkt['I105']['Lon']['val']
return mp_util.gps_distance(lat1, lon1, lat, lon) | [
"def",
"distance_from",
"(",
"self",
",",
"lat",
",",
"lon",
")",
":",
"lat1",
"=",
"self",
".",
"pkt",
"[",
"'I105'",
"]",
"[",
"'Lat'",
"]",
"[",
"'val'",
"]",
"lon1",
"=",
"self",
".",
"pkt",
"[",
"'I105'",
"]",
"[",
"'Lon'",
"]",
"[",
"'val... | get distance from a point | [
"get",
"distance",
"from",
"a",
"point"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_genobstacles.py#L65-L69 | train | 230,620 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_genobstacles.py | DNFZ.randpos | def randpos(self):
'''random initial position'''
self.setpos(gen_settings.home_lat, gen_settings.home_lon)
self.move(random.uniform(0, 360), random.uniform(0, gen_settings.region_width)) | python | def randpos(self):
'''random initial position'''
self.setpos(gen_settings.home_lat, gen_settings.home_lon)
self.move(random.uniform(0, 360), random.uniform(0, gen_settings.region_width)) | [
"def",
"randpos",
"(",
"self",
")",
":",
"self",
".",
"setpos",
"(",
"gen_settings",
".",
"home_lat",
",",
"gen_settings",
".",
"home_lon",
")",
"self",
".",
"move",
"(",
"random",
".",
"uniform",
"(",
"0",
",",
"360",
")",
",",
"random",
".",
"unifo... | random initial position | [
"random",
"initial",
"position"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_genobstacles.py#L75-L78 | train | 230,621 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_genobstacles.py | DNFZ.ground_height | def ground_height(self):
'''return height above ground in feet'''
lat = self.pkt['I105']['Lat']['val']
lon = self.pkt['I105']['Lon']['val']
global ElevationMap
ret = ElevationMap.GetElevation(lat, lon)
ret -= gen_settings.wgs84_to_AMSL
return ret * 3.2807 | python | def ground_height(self):
'''return height above ground in feet'''
lat = self.pkt['I105']['Lat']['val']
lon = self.pkt['I105']['Lon']['val']
global ElevationMap
ret = ElevationMap.GetElevation(lat, lon)
ret -= gen_settings.wgs84_to_AMSL
return ret * 3.2807 | [
"def",
"ground_height",
"(",
"self",
")",
":",
"lat",
"=",
"self",
".",
"pkt",
"[",
"'I105'",
"]",
"[",
"'Lat'",
"]",
"[",
"'val'",
"]",
"lon",
"=",
"self",
".",
"pkt",
"[",
"'I105'",
"]",
"[",
"'Lon'",
"]",
"[",
"'val'",
"]",
"global",
"Elevatio... | return height above ground in feet | [
"return",
"height",
"above",
"ground",
"in",
"feet"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_genobstacles.py#L80-L87 | train | 230,622 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_genobstacles.py | DNFZ.move | def move(self, bearing, distance):
'''move position by bearing and distance'''
lat = self.pkt['I105']['Lat']['val']
lon = self.pkt['I105']['Lon']['val']
(lat, lon) = mp_util.gps_newpos(lat, lon, bearing, distance)
self.setpos(lat, lon) | python | def move(self, bearing, distance):
'''move position by bearing and distance'''
lat = self.pkt['I105']['Lat']['val']
lon = self.pkt['I105']['Lon']['val']
(lat, lon) = mp_util.gps_newpos(lat, lon, bearing, distance)
self.setpos(lat, lon) | [
"def",
"move",
"(",
"self",
",",
"bearing",
",",
"distance",
")",
":",
"lat",
"=",
"self",
".",
"pkt",
"[",
"'I105'",
"]",
"[",
"'Lat'",
"]",
"[",
"'val'",
"]",
"lon",
"=",
"self",
".",
"pkt",
"[",
"'I105'",
"]",
"[",
"'Lon'",
"]",
"[",
"'val'"... | move position by bearing and distance | [
"move",
"position",
"by",
"bearing",
"and",
"distance"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_genobstacles.py#L93-L98 | train | 230,623 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_genobstacles.py | Aircraft.update | def update(self, deltat=1.0):
'''fly a square circuit'''
DNFZ.update(self, deltat)
self.dist_flown += self.speed * deltat
if self.dist_flown > self.circuit_width:
self.desired_heading = self.heading + 90
self.dist_flown = 0
if self.getalt() < self.ground_height() or self.getalt() > self.ground_height() + 2000:
self.randpos()
self.randalt() | python | def update(self, deltat=1.0):
'''fly a square circuit'''
DNFZ.update(self, deltat)
self.dist_flown += self.speed * deltat
if self.dist_flown > self.circuit_width:
self.desired_heading = self.heading + 90
self.dist_flown = 0
if self.getalt() < self.ground_height() or self.getalt() > self.ground_height() + 2000:
self.randpos()
self.randalt() | [
"def",
"update",
"(",
"self",
",",
"deltat",
"=",
"1.0",
")",
":",
"DNFZ",
".",
"update",
"(",
"self",
",",
"deltat",
")",
"self",
".",
"dist_flown",
"+=",
"self",
".",
"speed",
"*",
"deltat",
"if",
"self",
".",
"dist_flown",
">",
"self",
".",
"cir... | fly a square circuit | [
"fly",
"a",
"square",
"circuit"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_genobstacles.py#L180-L189 | train | 230,624 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_genobstacles.py | BirdOfPrey.update | def update(self, deltat=1.0):
'''fly circles, then dive'''
DNFZ.update(self, deltat)
self.time_circling += deltat
self.setheading(self.heading + self.turn_rate * deltat)
self.move(self.drift_heading, self.drift_speed)
if self.getalt() > self.max_alt or self.getalt() < self.ground_height():
if self.getalt() > self.ground_height():
self.setclimbrate(self.dive_rate)
else:
self.setclimbrate(self.climb_rate)
if self.getalt() < self.ground_height():
self.setalt(self.ground_height())
if self.distance_from_home() > gen_settings.region_width:
self.randpos()
self.randalt() | python | def update(self, deltat=1.0):
'''fly circles, then dive'''
DNFZ.update(self, deltat)
self.time_circling += deltat
self.setheading(self.heading + self.turn_rate * deltat)
self.move(self.drift_heading, self.drift_speed)
if self.getalt() > self.max_alt or self.getalt() < self.ground_height():
if self.getalt() > self.ground_height():
self.setclimbrate(self.dive_rate)
else:
self.setclimbrate(self.climb_rate)
if self.getalt() < self.ground_height():
self.setalt(self.ground_height())
if self.distance_from_home() > gen_settings.region_width:
self.randpos()
self.randalt() | [
"def",
"update",
"(",
"self",
",",
"deltat",
"=",
"1.0",
")",
":",
"DNFZ",
".",
"update",
"(",
"self",
",",
"deltat",
")",
"self",
".",
"time_circling",
"+=",
"deltat",
"self",
".",
"setheading",
"(",
"self",
".",
"heading",
"+",
"self",
".",
"turn_r... | fly circles, then dive | [
"fly",
"circles",
"then",
"dive"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_genobstacles.py#L209-L224 | train | 230,625 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_genobstacles.py | BirdMigrating.update | def update(self, deltat=1.0):
'''fly in long curves'''
DNFZ.update(self, deltat)
if (self.distance_from_home() > gen_settings.region_width or
self.getalt() < self.ground_height() or
self.getalt() > self.ground_height() + 1000):
self.randpos()
self.randalt() | python | def update(self, deltat=1.0):
'''fly in long curves'''
DNFZ.update(self, deltat)
if (self.distance_from_home() > gen_settings.region_width or
self.getalt() < self.ground_height() or
self.getalt() > self.ground_height() + 1000):
self.randpos()
self.randalt() | [
"def",
"update",
"(",
"self",
",",
"deltat",
"=",
"1.0",
")",
":",
"DNFZ",
".",
"update",
"(",
"self",
",",
"deltat",
")",
"if",
"(",
"self",
".",
"distance_from_home",
"(",
")",
">",
"gen_settings",
".",
"region_width",
"or",
"self",
".",
"getalt",
... | fly in long curves | [
"fly",
"in",
"long",
"curves"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_genobstacles.py#L234-L241 | train | 230,626 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_genobstacles.py | Weather.update | def update(self, deltat=1.0):
'''straight lines, with short life'''
DNFZ.update(self, deltat)
self.lifetime -= deltat
if self.lifetime <= 0:
self.randpos()
self.lifetime = random.uniform(300,600) | python | def update(self, deltat=1.0):
'''straight lines, with short life'''
DNFZ.update(self, deltat)
self.lifetime -= deltat
if self.lifetime <= 0:
self.randpos()
self.lifetime = random.uniform(300,600) | [
"def",
"update",
"(",
"self",
",",
"deltat",
"=",
"1.0",
")",
":",
"DNFZ",
".",
"update",
"(",
"self",
",",
"deltat",
")",
"self",
".",
"lifetime",
"-=",
"deltat",
"if",
"self",
".",
"lifetime",
"<=",
"0",
":",
"self",
".",
"randpos",
"(",
")",
"... | straight lines, with short life | [
"straight",
"lines",
"with",
"short",
"life"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_genobstacles.py#L252-L258 | train | 230,627 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_genobstacles.py | GenobstaclesModule.cmd_dropobject | def cmd_dropobject(self, obj):
'''drop an object on the map'''
latlon = self.module('map').click_position
if self.last_click is not None and self.last_click == latlon:
return
self.last_click = latlon
if latlon is not None:
obj.setpos(latlon[0], latlon[1])
self.aircraft.append(obj) | python | def cmd_dropobject(self, obj):
'''drop an object on the map'''
latlon = self.module('map').click_position
if self.last_click is not None and self.last_click == latlon:
return
self.last_click = latlon
if latlon is not None:
obj.setpos(latlon[0], latlon[1])
self.aircraft.append(obj) | [
"def",
"cmd_dropobject",
"(",
"self",
",",
"obj",
")",
":",
"latlon",
"=",
"self",
".",
"module",
"(",
"'map'",
")",
".",
"click_position",
"if",
"self",
".",
"last_click",
"is",
"not",
"None",
"and",
"self",
".",
"last_click",
"==",
"latlon",
":",
"re... | drop an object on the map | [
"drop",
"an",
"object",
"on",
"the",
"map"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_genobstacles.py#L291-L299 | train | 230,628 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_genobstacles.py | GenobstaclesModule.cmd_genobstacles | def cmd_genobstacles(self, args):
'''genobstacles command parser'''
usage = "usage: genobstacles <start|stop|restart|clearall|status|set>"
if len(args) == 0:
print(usage)
return
if args[0] == "set":
gen_settings.command(args[1:])
elif args[0] == "start":
if self.have_home:
self.start()
else:
self.pending_start = True
elif args[0] == "stop":
self.stop()
self.pending_start = False
elif args[0] == "restart":
self.stop()
self.start()
elif args[0] == "status":
print(self.status())
elif args[0] == "remove":
latlon = self.module('map').click_position
if self.last_click is not None and self.last_click == latlon:
return
self.last_click = latlon
if latlon is not None:
closest = None
closest_distance = 1000
for a in self.aircraft:
dist = a.distance_from(latlon[0], latlon[1])
if dist < closest_distance:
closest_distance = dist
closest = a
if closest is not None:
self.aircraft.remove(closest)
else:
print("No obstacle found at click point")
elif args[0] == "dropcloud":
self.cmd_dropobject(Weather())
elif args[0] == "dropeagle":
self.cmd_dropobject(BirdOfPrey())
elif args[0] == "dropbird":
self.cmd_dropobject(BirdMigrating())
elif args[0] == "dropplane":
self.cmd_dropobject(Aircraft())
elif args[0] == "clearall":
self.clearall()
else:
print(usage) | python | def cmd_genobstacles(self, args):
'''genobstacles command parser'''
usage = "usage: genobstacles <start|stop|restart|clearall|status|set>"
if len(args) == 0:
print(usage)
return
if args[0] == "set":
gen_settings.command(args[1:])
elif args[0] == "start":
if self.have_home:
self.start()
else:
self.pending_start = True
elif args[0] == "stop":
self.stop()
self.pending_start = False
elif args[0] == "restart":
self.stop()
self.start()
elif args[0] == "status":
print(self.status())
elif args[0] == "remove":
latlon = self.module('map').click_position
if self.last_click is not None and self.last_click == latlon:
return
self.last_click = latlon
if latlon is not None:
closest = None
closest_distance = 1000
for a in self.aircraft:
dist = a.distance_from(latlon[0], latlon[1])
if dist < closest_distance:
closest_distance = dist
closest = a
if closest is not None:
self.aircraft.remove(closest)
else:
print("No obstacle found at click point")
elif args[0] == "dropcloud":
self.cmd_dropobject(Weather())
elif args[0] == "dropeagle":
self.cmd_dropobject(BirdOfPrey())
elif args[0] == "dropbird":
self.cmd_dropobject(BirdMigrating())
elif args[0] == "dropplane":
self.cmd_dropobject(Aircraft())
elif args[0] == "clearall":
self.clearall()
else:
print(usage) | [
"def",
"cmd_genobstacles",
"(",
"self",
",",
"args",
")",
":",
"usage",
"=",
"\"usage: genobstacles <start|stop|restart|clearall|status|set>\"",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"print",
"(",
"usage",
")",
"return",
"if",
"args",
"[",
"0",
"]",
... | genobstacles command parser | [
"genobstacles",
"command",
"parser"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_genobstacles.py#L309-L359 | train | 230,629 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_genobstacles.py | GenobstaclesModule.start | def start(self):
'''start sending packets'''
if self.sock is not None:
self.sock.close()
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.connect(('', gen_settings.port))
global track_count
self.aircraft = []
track_count = 0
self.last_t = 0
# some fixed wing aircraft
for i in range(gen_settings.num_aircraft):
self.aircraft.append(Aircraft(random.uniform(10, 100), 2000.0))
# some birds of prey
for i in range(gen_settings.num_bird_prey):
self.aircraft.append(BirdOfPrey())
# some migrating birds
for i in range(gen_settings.num_bird_migratory):
self.aircraft.append(BirdMigrating())
# some weather systems
for i in range(gen_settings.num_weather):
self.aircraft.append(Weather())
print("Started on port %u" % gen_settings.port) | python | def start(self):
'''start sending packets'''
if self.sock is not None:
self.sock.close()
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.connect(('', gen_settings.port))
global track_count
self.aircraft = []
track_count = 0
self.last_t = 0
# some fixed wing aircraft
for i in range(gen_settings.num_aircraft):
self.aircraft.append(Aircraft(random.uniform(10, 100), 2000.0))
# some birds of prey
for i in range(gen_settings.num_bird_prey):
self.aircraft.append(BirdOfPrey())
# some migrating birds
for i in range(gen_settings.num_bird_migratory):
self.aircraft.append(BirdMigrating())
# some weather systems
for i in range(gen_settings.num_weather):
self.aircraft.append(Weather())
print("Started on port %u" % gen_settings.port) | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"sock",
"is",
"not",
"None",
":",
"self",
".",
"sock",
".",
"close",
"(",
")",
"self",
".",
"sock",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_D... | start sending packets | [
"start",
"sending",
"packets"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_genobstacles.py#L361-L389 | train | 230,630 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_genobstacles.py | GenobstaclesModule.mavlink_packet | def mavlink_packet(self, m):
'''trigger sends from ATTITUDE packets'''
if not self.have_home and m.get_type() == 'GPS_RAW_INT' and m.fix_type >= 3:
gen_settings.home_lat = m.lat * 1.0e-7
gen_settings.home_lon = m.lon * 1.0e-7
self.have_home = True
if self.pending_start:
self.start()
if m.get_type() != 'ATTITUDE':
return
t = self.get_time()
dt = t - self.last_t
if dt < 0 or dt > 10:
self.last_t = t
return
if dt > 10 or dt < 0.9:
return
self.last_t = t
for a in self.aircraft:
if not gen_settings.stop:
a.update(1.0)
self.pkt_queue.append(a.pickled())
while len(self.pkt_queue) > len(self.aircraft)*2:
self.pkt_queue.pop(0)
if self.module('map') is not None and not self.menu_added_map:
self.menu_added_map = True
self.module('map').add_menu(self.menu) | python | def mavlink_packet(self, m):
'''trigger sends from ATTITUDE packets'''
if not self.have_home and m.get_type() == 'GPS_RAW_INT' and m.fix_type >= 3:
gen_settings.home_lat = m.lat * 1.0e-7
gen_settings.home_lon = m.lon * 1.0e-7
self.have_home = True
if self.pending_start:
self.start()
if m.get_type() != 'ATTITUDE':
return
t = self.get_time()
dt = t - self.last_t
if dt < 0 or dt > 10:
self.last_t = t
return
if dt > 10 or dt < 0.9:
return
self.last_t = t
for a in self.aircraft:
if not gen_settings.stop:
a.update(1.0)
self.pkt_queue.append(a.pickled())
while len(self.pkt_queue) > len(self.aircraft)*2:
self.pkt_queue.pop(0)
if self.module('map') is not None and not self.menu_added_map:
self.menu_added_map = True
self.module('map').add_menu(self.menu) | [
"def",
"mavlink_packet",
"(",
"self",
",",
"m",
")",
":",
"if",
"not",
"self",
".",
"have_home",
"and",
"m",
".",
"get_type",
"(",
")",
"==",
"'GPS_RAW_INT'",
"and",
"m",
".",
"fix_type",
">=",
"3",
":",
"gen_settings",
".",
"home_lat",
"=",
"m",
"."... | trigger sends from ATTITUDE packets | [
"trigger",
"sends",
"from",
"ATTITUDE",
"packets"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_genobstacles.py#L409-L436 | train | 230,631 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_adsb.py | ADSBVehicle.update | def update(self, state, tnow):
'''update the threat state'''
self.state = state
self.update_time = tnow | python | def update(self, state, tnow):
'''update the threat state'''
self.state = state
self.update_time = tnow | [
"def",
"update",
"(",
"self",
",",
"state",
",",
"tnow",
")",
":",
"self",
".",
"state",
"=",
"state",
"self",
".",
"update_time",
"=",
"tnow"
] | update the threat state | [
"update",
"the",
"threat",
"state"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_adsb.py#L50-L53 | train | 230,632 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_adsb.py | ADSBModule.cmd_ADSB | def cmd_ADSB(self, args):
'''adsb command parser'''
usage = "usage: adsb <set>"
if len(args) == 0:
print(usage)
return
if args[0] == "status":
print("total threat count: %u active threat count: %u" %
(len(self.threat_vehicles), len(self.active_threat_ids)))
for id in self.threat_vehicles.keys():
print("id: %s distance: %.2f m callsign: %s alt: %.2f" % (id,
self.threat_vehicles[id].distance,
self.threat_vehicles[id].state['callsign'],
self.threat_vehicles[id].state['altitude']))
elif args[0] == "set":
self.ADSB_settings.command(args[1:])
else:
print(usage) | python | def cmd_ADSB(self, args):
'''adsb command parser'''
usage = "usage: adsb <set>"
if len(args) == 0:
print(usage)
return
if args[0] == "status":
print("total threat count: %u active threat count: %u" %
(len(self.threat_vehicles), len(self.active_threat_ids)))
for id in self.threat_vehicles.keys():
print("id: %s distance: %.2f m callsign: %s alt: %.2f" % (id,
self.threat_vehicles[id].distance,
self.threat_vehicles[id].state['callsign'],
self.threat_vehicles[id].state['altitude']))
elif args[0] == "set":
self.ADSB_settings.command(args[1:])
else:
print(usage) | [
"def",
"cmd_ADSB",
"(",
"self",
",",
"args",
")",
":",
"usage",
"=",
"\"usage: adsb <set>\"",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"print",
"(",
"usage",
")",
"return",
"if",
"args",
"[",
"0",
"]",
"==",
"\"status\"",
":",
"print",
"(",
"... | adsb command parser | [
"adsb",
"command",
"parser"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_adsb.py#L79-L97 | train | 230,633 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_adsb.py | ADSBModule.update_threat_distances | def update_threat_distances(self, latlonalt):
'''update the distance between threats and vehicle'''
for id in self.threat_vehicles.keys():
threat_latlonalt = (self.threat_vehicles[id].state['lat'] * 1e-7,
self.threat_vehicles[id].state['lon'] * 1e-7,
self.threat_vehicles[id].state['altitude'])
self.threat_vehicles[id].h_distance = self.get_h_distance(latlonalt, threat_latlonalt)
self.threat_vehicles[id].v_distance = self.get_v_distance(latlonalt, threat_latlonalt)
# calculate and set the total distance between threat and vehicle
self.threat_vehicles[id].distance = sqrt(
self.threat_vehicles[id].h_distance**2 + (self.threat_vehicles[id].v_distance)**2) | python | def update_threat_distances(self, latlonalt):
'''update the distance between threats and vehicle'''
for id in self.threat_vehicles.keys():
threat_latlonalt = (self.threat_vehicles[id].state['lat'] * 1e-7,
self.threat_vehicles[id].state['lon'] * 1e-7,
self.threat_vehicles[id].state['altitude'])
self.threat_vehicles[id].h_distance = self.get_h_distance(latlonalt, threat_latlonalt)
self.threat_vehicles[id].v_distance = self.get_v_distance(latlonalt, threat_latlonalt)
# calculate and set the total distance between threat and vehicle
self.threat_vehicles[id].distance = sqrt(
self.threat_vehicles[id].h_distance**2 + (self.threat_vehicles[id].v_distance)**2) | [
"def",
"update_threat_distances",
"(",
"self",
",",
"latlonalt",
")",
":",
"for",
"id",
"in",
"self",
".",
"threat_vehicles",
".",
"keys",
"(",
")",
":",
"threat_latlonalt",
"=",
"(",
"self",
".",
"threat_vehicles",
"[",
"id",
"]",
".",
"state",
"[",
"'l... | update the distance between threats and vehicle | [
"update",
"the",
"distance",
"between",
"threats",
"and",
"vehicle"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_adsb.py#L122-L134 | train | 230,634 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_adsb.py | ADSBModule.check_threat_timeout | def check_threat_timeout(self):
'''check and handle threat time out'''
for id in self.threat_vehicles.keys():
if self.threat_vehicles[id].update_time == 0:
self.threat_vehicles[id].update_time = self.get_time()
dt = self.get_time() - self.threat_vehicles[id].update_time
if dt > self.ADSB_settings.timeout:
# if the threat has timed out...
del self.threat_vehicles[id] # remove the threat from the dict
for mp in self.module_matching('map*'):
# remove the threat from the map
mp.map.remove_object(id)
mp.map.remove_object(id+":circle")
# we've modified the dict we're iterating over, so
# we'll get any more timed-out threats next time we're
# called:
return | python | def check_threat_timeout(self):
'''check and handle threat time out'''
for id in self.threat_vehicles.keys():
if self.threat_vehicles[id].update_time == 0:
self.threat_vehicles[id].update_time = self.get_time()
dt = self.get_time() - self.threat_vehicles[id].update_time
if dt > self.ADSB_settings.timeout:
# if the threat has timed out...
del self.threat_vehicles[id] # remove the threat from the dict
for mp in self.module_matching('map*'):
# remove the threat from the map
mp.map.remove_object(id)
mp.map.remove_object(id+":circle")
# we've modified the dict we're iterating over, so
# we'll get any more timed-out threats next time we're
# called:
return | [
"def",
"check_threat_timeout",
"(",
"self",
")",
":",
"for",
"id",
"in",
"self",
".",
"threat_vehicles",
".",
"keys",
"(",
")",
":",
"if",
"self",
".",
"threat_vehicles",
"[",
"id",
"]",
".",
"update_time",
"==",
"0",
":",
"self",
".",
"threat_vehicles",... | check and handle threat time out | [
"check",
"and",
"handle",
"threat",
"time",
"out"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_adsb.py#L160-L176 | train | 230,635 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_gopro.py | GoProModule.cmd_gopro_status | def cmd_gopro_status(self, args):
'''show gopro status'''
master = self.master
if 'GOPRO_HEARTBEAT' in master.messages:
print(master.messages['GOPRO_HEARTBEAT'])
else:
print("No GOPRO_HEARTBEAT messages") | python | def cmd_gopro_status(self, args):
'''show gopro status'''
master = self.master
if 'GOPRO_HEARTBEAT' in master.messages:
print(master.messages['GOPRO_HEARTBEAT'])
else:
print("No GOPRO_HEARTBEAT messages") | [
"def",
"cmd_gopro_status",
"(",
"self",
",",
"args",
")",
":",
"master",
"=",
"self",
".",
"master",
"if",
"'GOPRO_HEARTBEAT'",
"in",
"master",
".",
"messages",
":",
"print",
"(",
"master",
".",
"messages",
"[",
"'GOPRO_HEARTBEAT'",
"]",
")",
"else",
":",
... | show gopro status | [
"show",
"gopro",
"status"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_gopro.py#L76-L82 | train | 230,636 |
ArduPilot/MAVProxy | MAVProxy/modules/lib/wxconsole_ui.py | ConsoleFrame.on_text_url | def on_text_url(self, event):
'''handle double clicks on URL text'''
try:
import webbrowser
except ImportError:
return
mouse_event = event.GetMouseEvent()
if mouse_event.LeftDClick():
url_start = event.GetURLStart()
url_end = event.GetURLEnd()
url = self.control.GetRange(url_start, url_end)
try:
# attempt to use google-chrome
browser_controller = webbrowser.get('google-chrome')
browser_controller.open_new_tab(url)
except webbrowser.Error:
# use the system configured default browser
webbrowser.open_new_tab(url) | python | def on_text_url(self, event):
'''handle double clicks on URL text'''
try:
import webbrowser
except ImportError:
return
mouse_event = event.GetMouseEvent()
if mouse_event.LeftDClick():
url_start = event.GetURLStart()
url_end = event.GetURLEnd()
url = self.control.GetRange(url_start, url_end)
try:
# attempt to use google-chrome
browser_controller = webbrowser.get('google-chrome')
browser_controller.open_new_tab(url)
except webbrowser.Error:
# use the system configured default browser
webbrowser.open_new_tab(url) | [
"def",
"on_text_url",
"(",
"self",
",",
"event",
")",
":",
"try",
":",
"import",
"webbrowser",
"except",
"ImportError",
":",
"return",
"mouse_event",
"=",
"event",
".",
"GetMouseEvent",
"(",
")",
"if",
"mouse_event",
".",
"LeftDClick",
"(",
")",
":",
"url_... | handle double clicks on URL text | [
"handle",
"double",
"clicks",
"on",
"URL",
"text"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/lib/wxconsole_ui.py#L55-L72 | train | 230,637 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_heliplane.py | HeliPlaneModule.update_channels | def update_channels(self):
'''update which channels provide input'''
self.interlock_channel = -1
self.override_channel = -1
self.zero_I_channel = -1
self.no_vtol_channel = -1
# output channels
self.rsc_out_channel = 9
self.fwd_thr_channel = 10
for ch in range(1,16):
option = self.get_mav_param("RC%u_OPTION" % ch, 0)
if option == 32:
self.interlock_channel = ch;
elif option == 63:
self.override_channel = ch;
elif option == 64:
self.zero_I_channel = ch;
elif option == 65:
self.override_channel = ch;
elif option == 66:
self.no_vtol_channel = ch;
function = self.get_mav_param("SERVO%u_FUNCTION" % ch, 0)
if function == 32:
self.rsc_out_channel = ch
if function == 70:
self.fwd_thr_channel = ch | python | def update_channels(self):
'''update which channels provide input'''
self.interlock_channel = -1
self.override_channel = -1
self.zero_I_channel = -1
self.no_vtol_channel = -1
# output channels
self.rsc_out_channel = 9
self.fwd_thr_channel = 10
for ch in range(1,16):
option = self.get_mav_param("RC%u_OPTION" % ch, 0)
if option == 32:
self.interlock_channel = ch;
elif option == 63:
self.override_channel = ch;
elif option == 64:
self.zero_I_channel = ch;
elif option == 65:
self.override_channel = ch;
elif option == 66:
self.no_vtol_channel = ch;
function = self.get_mav_param("SERVO%u_FUNCTION" % ch, 0)
if function == 32:
self.rsc_out_channel = ch
if function == 70:
self.fwd_thr_channel = ch | [
"def",
"update_channels",
"(",
"self",
")",
":",
"self",
".",
"interlock_channel",
"=",
"-",
"1",
"self",
".",
"override_channel",
"=",
"-",
"1",
"self",
".",
"zero_I_channel",
"=",
"-",
"1",
"self",
".",
"no_vtol_channel",
"=",
"-",
"1",
"# output channel... | update which channels provide input | [
"update",
"which",
"channels",
"provide",
"input"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_heliplane.py#L102-L130 | train | 230,638 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_rally.py | RallyModule.rallyloader | def rallyloader(self):
'''rally loader by system ID'''
if not self.target_system in self.rallyloader_by_sysid:
self.rallyloader_by_sysid[self.target_system] = mavwp.MAVRallyLoader(self.settings.target_system,
self.settings.target_component)
return self.rallyloader_by_sysid[self.target_system] | python | def rallyloader(self):
'''rally loader by system ID'''
if not self.target_system in self.rallyloader_by_sysid:
self.rallyloader_by_sysid[self.target_system] = mavwp.MAVRallyLoader(self.settings.target_system,
self.settings.target_component)
return self.rallyloader_by_sysid[self.target_system] | [
"def",
"rallyloader",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"target_system",
"in",
"self",
".",
"rallyloader_by_sysid",
":",
"self",
".",
"rallyloader_by_sysid",
"[",
"self",
".",
"target_system",
"]",
"=",
"mavwp",
".",
"MAVRallyLoader",
"(",
"se... | rally loader by system ID | [
"rally",
"loader",
"by",
"system",
"ID"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_rally.py#L45-L50 | train | 230,639 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_dataflash_logger.py | dataflash_logger.packet_is_for_me | def packet_is_for_me(self, m):
'''returns true if this packet is appropriately addressed'''
if m.target_system != self.master.mav.srcSystem:
return False
if m.target_component != self.master.mav.srcComponent:
return False
# if have a sender we can also check the source address:
if self.sender is not None:
if (m.get_srcSystem(), m.get_srcComponent()) != self.sender:
return False
return True | python | def packet_is_for_me(self, m):
'''returns true if this packet is appropriately addressed'''
if m.target_system != self.master.mav.srcSystem:
return False
if m.target_component != self.master.mav.srcComponent:
return False
# if have a sender we can also check the source address:
if self.sender is not None:
if (m.get_srcSystem(), m.get_srcComponent()) != self.sender:
return False
return True | [
"def",
"packet_is_for_me",
"(",
"self",
",",
"m",
")",
":",
"if",
"m",
".",
"target_system",
"!=",
"self",
".",
"master",
".",
"mav",
".",
"srcSystem",
":",
"return",
"False",
"if",
"m",
".",
"target_component",
"!=",
"self",
".",
"master",
".",
"mav",... | returns true if this packet is appropriately addressed | [
"returns",
"true",
"if",
"this",
"packet",
"is",
"appropriately",
"addressed"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_dataflash_logger.py#L261-L271 | train | 230,640 |
ArduPilot/MAVProxy | MAVProxy/modules/lib/MacOS/backend_wxagg.py | _convert_agg_to_wx_image | def _convert_agg_to_wx_image(agg, bbox):
"""
Convert the region of the agg buffer bounded by bbox to a wx.Image. If
bbox is None, the entire buffer is converted.
Note: agg must be a backend_agg.RendererAgg instance.
"""
if bbox is None:
# agg => rgb -> image
image = wx.EmptyImage(int(agg.width), int(agg.height))
image.SetData(agg.tostring_rgb())
return image
else:
# agg => rgba buffer -> bitmap => clipped bitmap => image
return wx.ImageFromBitmap(_WX28_clipped_agg_as_bitmap(agg, bbox)) | python | def _convert_agg_to_wx_image(agg, bbox):
"""
Convert the region of the agg buffer bounded by bbox to a wx.Image. If
bbox is None, the entire buffer is converted.
Note: agg must be a backend_agg.RendererAgg instance.
"""
if bbox is None:
# agg => rgb -> image
image = wx.EmptyImage(int(agg.width), int(agg.height))
image.SetData(agg.tostring_rgb())
return image
else:
# agg => rgba buffer -> bitmap => clipped bitmap => image
return wx.ImageFromBitmap(_WX28_clipped_agg_as_bitmap(agg, bbox)) | [
"def",
"_convert_agg_to_wx_image",
"(",
"agg",
",",
"bbox",
")",
":",
"if",
"bbox",
"is",
"None",
":",
"# agg => rgb -> image",
"image",
"=",
"wx",
".",
"EmptyImage",
"(",
"int",
"(",
"agg",
".",
"width",
")",
",",
"int",
"(",
"agg",
".",
"height",
")"... | Convert the region of the agg buffer bounded by bbox to a wx.Image. If
bbox is None, the entire buffer is converted.
Note: agg must be a backend_agg.RendererAgg instance. | [
"Convert",
"the",
"region",
"of",
"the",
"agg",
"buffer",
"bounded",
"by",
"bbox",
"to",
"a",
"wx",
".",
"Image",
".",
"If",
"bbox",
"is",
"None",
"the",
"entire",
"buffer",
"is",
"converted",
"."
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/lib/MacOS/backend_wxagg.py#L128-L142 | train | 230,641 |
ArduPilot/MAVProxy | MAVProxy/modules/lib/MacOS/backend_wxagg.py | _convert_agg_to_wx_bitmap | def _convert_agg_to_wx_bitmap(agg, bbox):
"""
Convert the region of the agg buffer bounded by bbox to a wx.Bitmap. If
bbox is None, the entire buffer is converted.
Note: agg must be a backend_agg.RendererAgg instance.
"""
if bbox is None:
# agg => rgba buffer -> bitmap
return wx.BitmapFromBufferRGBA(int(agg.width), int(agg.height),
agg.buffer_rgba())
else:
# agg => rgba buffer -> bitmap => clipped bitmap
return _WX28_clipped_agg_as_bitmap(agg, bbox) | python | def _convert_agg_to_wx_bitmap(agg, bbox):
"""
Convert the region of the agg buffer bounded by bbox to a wx.Bitmap. If
bbox is None, the entire buffer is converted.
Note: agg must be a backend_agg.RendererAgg instance.
"""
if bbox is None:
# agg => rgba buffer -> bitmap
return wx.BitmapFromBufferRGBA(int(agg.width), int(agg.height),
agg.buffer_rgba())
else:
# agg => rgba buffer -> bitmap => clipped bitmap
return _WX28_clipped_agg_as_bitmap(agg, bbox) | [
"def",
"_convert_agg_to_wx_bitmap",
"(",
"agg",
",",
"bbox",
")",
":",
"if",
"bbox",
"is",
"None",
":",
"# agg => rgba buffer -> bitmap",
"return",
"wx",
".",
"BitmapFromBufferRGBA",
"(",
"int",
"(",
"agg",
".",
"width",
")",
",",
"int",
"(",
"agg",
".",
"... | Convert the region of the agg buffer bounded by bbox to a wx.Bitmap. If
bbox is None, the entire buffer is converted.
Note: agg must be a backend_agg.RendererAgg instance. | [
"Convert",
"the",
"region",
"of",
"the",
"agg",
"buffer",
"bounded",
"by",
"bbox",
"to",
"a",
"wx",
".",
"Bitmap",
".",
"If",
"bbox",
"is",
"None",
"the",
"entire",
"buffer",
"is",
"converted",
"."
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/lib/MacOS/backend_wxagg.py#L145-L158 | train | 230,642 |
ArduPilot/MAVProxy | MAVProxy/modules/lib/MacOS/backend_wxagg.py | _WX28_clipped_agg_as_bitmap | def _WX28_clipped_agg_as_bitmap(agg, bbox):
"""
Convert the region of a the agg buffer bounded by bbox to a wx.Bitmap.
Note: agg must be a backend_agg.RendererAgg instance.
"""
l, b, width, height = bbox.bounds
r = l + width
t = b + height
srcBmp = wx.BitmapFromBufferRGBA(int(agg.width), int(agg.height),
agg.buffer_rgba())
srcDC = wx.MemoryDC()
srcDC.SelectObject(srcBmp)
destBmp = wx.EmptyBitmap(int(width), int(height))
destDC = wx.MemoryDC()
destDC.SelectObject(destBmp)
destDC.BeginDrawing()
x = int(l)
y = int(int(agg.height) - t)
destDC.Blit(0, 0, int(width), int(height), srcDC, x, y)
destDC.EndDrawing()
srcDC.SelectObject(wx.NullBitmap)
destDC.SelectObject(wx.NullBitmap)
return destBmp | python | def _WX28_clipped_agg_as_bitmap(agg, bbox):
"""
Convert the region of a the agg buffer bounded by bbox to a wx.Bitmap.
Note: agg must be a backend_agg.RendererAgg instance.
"""
l, b, width, height = bbox.bounds
r = l + width
t = b + height
srcBmp = wx.BitmapFromBufferRGBA(int(agg.width), int(agg.height),
agg.buffer_rgba())
srcDC = wx.MemoryDC()
srcDC.SelectObject(srcBmp)
destBmp = wx.EmptyBitmap(int(width), int(height))
destDC = wx.MemoryDC()
destDC.SelectObject(destBmp)
destDC.BeginDrawing()
x = int(l)
y = int(int(agg.height) - t)
destDC.Blit(0, 0, int(width), int(height), srcDC, x, y)
destDC.EndDrawing()
srcDC.SelectObject(wx.NullBitmap)
destDC.SelectObject(wx.NullBitmap)
return destBmp | [
"def",
"_WX28_clipped_agg_as_bitmap",
"(",
"agg",
",",
"bbox",
")",
":",
"l",
",",
"b",
",",
"width",
",",
"height",
"=",
"bbox",
".",
"bounds",
"r",
"=",
"l",
"+",
"width",
"t",
"=",
"b",
"+",
"height",
"srcBmp",
"=",
"wx",
".",
"BitmapFromBufferRGB... | Convert the region of a the agg buffer bounded by bbox to a wx.Bitmap.
Note: agg must be a backend_agg.RendererAgg instance. | [
"Convert",
"the",
"region",
"of",
"a",
"the",
"agg",
"buffer",
"bounded",
"by",
"bbox",
"to",
"a",
"wx",
".",
"Bitmap",
"."
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/lib/MacOS/backend_wxagg.py#L161-L189 | train | 230,643 |
ArduPilot/MAVProxy | MAVProxy/modules/lib/MacOS/backend_wxagg.py | FigureCanvasWxAgg.draw | def draw(self, drawDC=None):
"""
Render the figure using agg.
"""
DEBUG_MSG("draw()", 1, self)
FigureCanvasAgg.draw(self)
self.bitmap = _convert_agg_to_wx_bitmap(self.get_renderer(), None)
self._isDrawn = True
self.gui_repaint(drawDC=drawDC) | python | def draw(self, drawDC=None):
"""
Render the figure using agg.
"""
DEBUG_MSG("draw()", 1, self)
FigureCanvasAgg.draw(self)
self.bitmap = _convert_agg_to_wx_bitmap(self.get_renderer(), None)
self._isDrawn = True
self.gui_repaint(drawDC=drawDC) | [
"def",
"draw",
"(",
"self",
",",
"drawDC",
"=",
"None",
")",
":",
"DEBUG_MSG",
"(",
"\"draw()\"",
",",
"1",
",",
"self",
")",
"FigureCanvasAgg",
".",
"draw",
"(",
"self",
")",
"self",
".",
"bitmap",
"=",
"_convert_agg_to_wx_bitmap",
"(",
"self",
".",
"... | Render the figure using agg. | [
"Render",
"the",
"figure",
"using",
"agg",
"."
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/lib/MacOS/backend_wxagg.py#L39-L48 | train | 230,644 |
ArduPilot/MAVProxy | MAVProxy/modules/lib/MacOS/backend_wxagg.py | FigureCanvasWxAgg.blit | def blit(self, bbox=None):
"""
Transfer the region of the agg buffer defined by bbox to the display.
If bbox is None, the entire buffer is transferred.
"""
if bbox is None:
self.bitmap = _convert_agg_to_wx_bitmap(self.get_renderer(), None)
self.gui_repaint()
return
l, b, w, h = bbox.bounds
r = l + w
t = b + h
x = int(l)
y = int(self.bitmap.GetHeight() - t)
srcBmp = _convert_agg_to_wx_bitmap(self.get_renderer(), None)
srcDC = wx.MemoryDC()
srcDC.SelectObject(srcBmp)
destDC = wx.MemoryDC()
destDC.SelectObject(self.bitmap)
destDC.BeginDrawing()
destDC.Blit(x, y, int(w), int(h), srcDC, x, y)
destDC.EndDrawing()
destDC.SelectObject(wx.NullBitmap)
srcDC.SelectObject(wx.NullBitmap)
self.gui_repaint() | python | def blit(self, bbox=None):
"""
Transfer the region of the agg buffer defined by bbox to the display.
If bbox is None, the entire buffer is transferred.
"""
if bbox is None:
self.bitmap = _convert_agg_to_wx_bitmap(self.get_renderer(), None)
self.gui_repaint()
return
l, b, w, h = bbox.bounds
r = l + w
t = b + h
x = int(l)
y = int(self.bitmap.GetHeight() - t)
srcBmp = _convert_agg_to_wx_bitmap(self.get_renderer(), None)
srcDC = wx.MemoryDC()
srcDC.SelectObject(srcBmp)
destDC = wx.MemoryDC()
destDC.SelectObject(self.bitmap)
destDC.BeginDrawing()
destDC.Blit(x, y, int(w), int(h), srcDC, x, y)
destDC.EndDrawing()
destDC.SelectObject(wx.NullBitmap)
srcDC.SelectObject(wx.NullBitmap)
self.gui_repaint() | [
"def",
"blit",
"(",
"self",
",",
"bbox",
"=",
"None",
")",
":",
"if",
"bbox",
"is",
"None",
":",
"self",
".",
"bitmap",
"=",
"_convert_agg_to_wx_bitmap",
"(",
"self",
".",
"get_renderer",
"(",
")",
",",
"None",
")",
"self",
".",
"gui_repaint",
"(",
"... | Transfer the region of the agg buffer defined by bbox to the display.
If bbox is None, the entire buffer is transferred. | [
"Transfer",
"the",
"region",
"of",
"the",
"agg",
"buffer",
"defined",
"by",
"bbox",
"to",
"the",
"display",
".",
"If",
"bbox",
"is",
"None",
"the",
"entire",
"buffer",
"is",
"transferred",
"."
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/lib/MacOS/backend_wxagg.py#L50-L79 | train | 230,645 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_antenna.py | AntennaModule.cmd_antenna | def cmd_antenna(self, args):
'''set gcs location'''
if len(args) != 2:
if self.gcs_location is None:
print("GCS location not set")
else:
print("GCS location %s" % str(self.gcs_location))
return
self.gcs_location = (float(args[0]), float(args[1])) | python | def cmd_antenna(self, args):
'''set gcs location'''
if len(args) != 2:
if self.gcs_location is None:
print("GCS location not set")
else:
print("GCS location %s" % str(self.gcs_location))
return
self.gcs_location = (float(args[0]), float(args[1])) | [
"def",
"cmd_antenna",
"(",
"self",
",",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"!=",
"2",
":",
"if",
"self",
".",
"gcs_location",
"is",
"None",
":",
"print",
"(",
"\"GCS location not set\"",
")",
"else",
":",
"print",
"(",
"\"GCS location %s\""... | set gcs location | [
"set",
"gcs",
"location"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_antenna.py#L20-L28 | train | 230,646 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_signing.py | SigningModule.passphrase_to_key | def passphrase_to_key(self, passphrase):
'''convert a passphrase to a 32 byte key'''
import hashlib
h = hashlib.new('sha256')
h.update(passphrase)
return h.digest() | python | def passphrase_to_key(self, passphrase):
'''convert a passphrase to a 32 byte key'''
import hashlib
h = hashlib.new('sha256')
h.update(passphrase)
return h.digest() | [
"def",
"passphrase_to_key",
"(",
"self",
",",
"passphrase",
")",
":",
"import",
"hashlib",
"h",
"=",
"hashlib",
".",
"new",
"(",
"'sha256'",
")",
"h",
".",
"update",
"(",
"passphrase",
")",
"return",
"h",
".",
"digest",
"(",
")"
] | convert a passphrase to a 32 byte key | [
"convert",
"a",
"passphrase",
"to",
"a",
"32",
"byte",
"key"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_signing.py#L39-L44 | train | 230,647 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_signing.py | SigningModule.cmd_signing_setup | def cmd_signing_setup(self, args):
'''setup signing key on board'''
if len(args) == 0:
print("usage: signing setup passphrase")
return
if not self.master.mavlink20():
print("You must be using MAVLink2 for signing")
return
passphrase = args[0]
key = self.passphrase_to_key(passphrase)
secret_key = []
for b in key:
secret_key.append(ord(b))
epoch_offset = 1420070400
now = max(time.time(), epoch_offset)
initial_timestamp = int((now - epoch_offset)*1e5)
self.master.mav.setup_signing_send(self.target_system, self.target_component,
secret_key, initial_timestamp)
print("Sent secret_key")
self.cmd_signing_key([passphrase]) | python | def cmd_signing_setup(self, args):
'''setup signing key on board'''
if len(args) == 0:
print("usage: signing setup passphrase")
return
if not self.master.mavlink20():
print("You must be using MAVLink2 for signing")
return
passphrase = args[0]
key = self.passphrase_to_key(passphrase)
secret_key = []
for b in key:
secret_key.append(ord(b))
epoch_offset = 1420070400
now = max(time.time(), epoch_offset)
initial_timestamp = int((now - epoch_offset)*1e5)
self.master.mav.setup_signing_send(self.target_system, self.target_component,
secret_key, initial_timestamp)
print("Sent secret_key")
self.cmd_signing_key([passphrase]) | [
"def",
"cmd_signing_setup",
"(",
"self",
",",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"print",
"(",
"\"usage: signing setup passphrase\"",
")",
"return",
"if",
"not",
"self",
".",
"master",
".",
"mavlink20",
"(",
")",
":",
"print... | setup signing key on board | [
"setup",
"signing",
"key",
"on",
"board"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_signing.py#L46-L66 | train | 230,648 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_signing.py | SigningModule.allow_unsigned | def allow_unsigned(self, mav, msgId):
'''see if an unsigned packet should be allowed'''
if self.allow is None:
self.allow = {
mavutil.mavlink.MAVLINK_MSG_ID_RADIO : True,
mavutil.mavlink.MAVLINK_MSG_ID_RADIO_STATUS : True
}
if msgId in self.allow:
return True
if self.settings.allow_unsigned:
return True
return False | python | def allow_unsigned(self, mav, msgId):
'''see if an unsigned packet should be allowed'''
if self.allow is None:
self.allow = {
mavutil.mavlink.MAVLINK_MSG_ID_RADIO : True,
mavutil.mavlink.MAVLINK_MSG_ID_RADIO_STATUS : True
}
if msgId in self.allow:
return True
if self.settings.allow_unsigned:
return True
return False | [
"def",
"allow_unsigned",
"(",
"self",
",",
"mav",
",",
"msgId",
")",
":",
"if",
"self",
".",
"allow",
"is",
"None",
":",
"self",
".",
"allow",
"=",
"{",
"mavutil",
".",
"mavlink",
".",
"MAVLINK_MSG_ID_RADIO",
":",
"True",
",",
"mavutil",
".",
"mavlink"... | see if an unsigned packet should be allowed | [
"see",
"if",
"an",
"unsigned",
"packet",
"should",
"be",
"allowed"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_signing.py#L69-L80 | train | 230,649 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_signing.py | SigningModule.cmd_signing_key | def cmd_signing_key(self, args):
'''set signing key on connection'''
if len(args) == 0:
print("usage: signing setup passphrase")
return
if not self.master.mavlink20():
print("You must be using MAVLink2 for signing")
return
passphrase = args[0]
key = self.passphrase_to_key(passphrase)
self.master.setup_signing(key, sign_outgoing=True, allow_unsigned_callback=self.allow_unsigned)
print("Setup signing key") | python | def cmd_signing_key(self, args):
'''set signing key on connection'''
if len(args) == 0:
print("usage: signing setup passphrase")
return
if not self.master.mavlink20():
print("You must be using MAVLink2 for signing")
return
passphrase = args[0]
key = self.passphrase_to_key(passphrase)
self.master.setup_signing(key, sign_outgoing=True, allow_unsigned_callback=self.allow_unsigned)
print("Setup signing key") | [
"def",
"cmd_signing_key",
"(",
"self",
",",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"print",
"(",
"\"usage: signing setup passphrase\"",
")",
"return",
"if",
"not",
"self",
".",
"master",
".",
"mavlink20",
"(",
")",
":",
"print",... | set signing key on connection | [
"set",
"signing",
"key",
"on",
"connection"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_signing.py#L82-L93 | train | 230,650 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_signing.py | SigningModule.cmd_signing_remove | def cmd_signing_remove(self, args):
'''remove signing from server'''
if not self.master.mavlink20():
print("You must be using MAVLink2 for signing")
return
self.master.mav.setup_signing_send(self.target_system, self.target_component, [0]*32, 0)
self.master.disable_signing()
print("Removed signing") | python | def cmd_signing_remove(self, args):
'''remove signing from server'''
if not self.master.mavlink20():
print("You must be using MAVLink2 for signing")
return
self.master.mav.setup_signing_send(self.target_system, self.target_component, [0]*32, 0)
self.master.disable_signing()
print("Removed signing") | [
"def",
"cmd_signing_remove",
"(",
"self",
",",
"args",
")",
":",
"if",
"not",
"self",
".",
"master",
".",
"mavlink20",
"(",
")",
":",
"print",
"(",
"\"You must be using MAVLink2 for signing\"",
")",
"return",
"self",
".",
"master",
".",
"mav",
".",
"setup_si... | remove signing from server | [
"remove",
"signing",
"from",
"server"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_signing.py#L100-L107 | train | 230,651 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_output.py | OutputModule.cmd_output | def cmd_output(self, args):
'''handle output commands'''
if len(args) < 1 or args[0] == "list":
self.cmd_output_list()
elif args[0] == "add":
if len(args) != 2:
print("Usage: output add OUTPUT")
return
self.cmd_output_add(args[1:])
elif args[0] == "remove":
if len(args) != 2:
print("Usage: output remove OUTPUT")
return
self.cmd_output_remove(args[1:])
elif args[0] == "sysid":
if len(args) != 3:
print("Usage: output sysid SYSID OUTPUT")
return
self.cmd_output_sysid(args[1:])
else:
print("usage: output <list|add|remove|sysid>") | python | def cmd_output(self, args):
'''handle output commands'''
if len(args) < 1 or args[0] == "list":
self.cmd_output_list()
elif args[0] == "add":
if len(args) != 2:
print("Usage: output add OUTPUT")
return
self.cmd_output_add(args[1:])
elif args[0] == "remove":
if len(args) != 2:
print("Usage: output remove OUTPUT")
return
self.cmd_output_remove(args[1:])
elif args[0] == "sysid":
if len(args) != 3:
print("Usage: output sysid SYSID OUTPUT")
return
self.cmd_output_sysid(args[1:])
else:
print("usage: output <list|add|remove|sysid>") | [
"def",
"cmd_output",
"(",
"self",
",",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"<",
"1",
"or",
"args",
"[",
"0",
"]",
"==",
"\"list\"",
":",
"self",
".",
"cmd_output_list",
"(",
")",
"elif",
"args",
"[",
"0",
"]",
"==",
"\"add\"",
":",
... | handle output commands | [
"handle",
"output",
"commands"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_output.py#L21-L41 | train | 230,652 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_output.py | OutputModule.cmd_output_add | def cmd_output_add(self, args):
'''add new output'''
device = args[0]
print("Adding output %s" % device)
try:
conn = mavutil.mavlink_connection(device, input=False, source_system=self.settings.source_system)
conn.mav.srcComponent = self.settings.source_component
except Exception:
print("Failed to connect to %s" % device)
return
self.mpstate.mav_outputs.append(conn)
try:
mp_util.child_fd_list_add(conn.port.fileno())
except Exception:
pass | python | def cmd_output_add(self, args):
'''add new output'''
device = args[0]
print("Adding output %s" % device)
try:
conn = mavutil.mavlink_connection(device, input=False, source_system=self.settings.source_system)
conn.mav.srcComponent = self.settings.source_component
except Exception:
print("Failed to connect to %s" % device)
return
self.mpstate.mav_outputs.append(conn)
try:
mp_util.child_fd_list_add(conn.port.fileno())
except Exception:
pass | [
"def",
"cmd_output_add",
"(",
"self",
",",
"args",
")",
":",
"device",
"=",
"args",
"[",
"0",
"]",
"print",
"(",
"\"Adding output %s\"",
"%",
"device",
")",
"try",
":",
"conn",
"=",
"mavutil",
".",
"mavlink_connection",
"(",
"device",
",",
"input",
"=",
... | add new output | [
"add",
"new",
"output"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_output.py#L55-L69 | train | 230,653 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_output.py | OutputModule.cmd_output_sysid | def cmd_output_sysid(self, args):
'''add new output for a specific MAVLink sysID'''
sysid = int(args[0])
device = args[1]
print("Adding output %s for sysid %u" % (device, sysid))
try:
conn = mavutil.mavlink_connection(device, input=False, source_system=self.settings.source_system)
conn.mav.srcComponent = self.settings.source_component
except Exception:
print("Failed to connect to %s" % device)
return
try:
mp_util.child_fd_list_add(conn.port.fileno())
except Exception:
pass
if sysid in self.mpstate.sysid_outputs:
self.mpstate.sysid_outputs[sysid].close()
self.mpstate.sysid_outputs[sysid] = conn | python | def cmd_output_sysid(self, args):
'''add new output for a specific MAVLink sysID'''
sysid = int(args[0])
device = args[1]
print("Adding output %s for sysid %u" % (device, sysid))
try:
conn = mavutil.mavlink_connection(device, input=False, source_system=self.settings.source_system)
conn.mav.srcComponent = self.settings.source_component
except Exception:
print("Failed to connect to %s" % device)
return
try:
mp_util.child_fd_list_add(conn.port.fileno())
except Exception:
pass
if sysid in self.mpstate.sysid_outputs:
self.mpstate.sysid_outputs[sysid].close()
self.mpstate.sysid_outputs[sysid] = conn | [
"def",
"cmd_output_sysid",
"(",
"self",
",",
"args",
")",
":",
"sysid",
"=",
"int",
"(",
"args",
"[",
"0",
"]",
")",
"device",
"=",
"args",
"[",
"1",
"]",
"print",
"(",
"\"Adding output %s for sysid %u\"",
"%",
"(",
"device",
",",
"sysid",
")",
")",
... | add new output for a specific MAVLink sysID | [
"add",
"new",
"output",
"for",
"a",
"specific",
"MAVLink",
"sysID"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_output.py#L71-L88 | train | 230,654 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_output.py | OutputModule.cmd_output_remove | def cmd_output_remove(self, args):
'''remove an output'''
device = args[0]
for i in range(len(self.mpstate.mav_outputs)):
conn = self.mpstate.mav_outputs[i]
if str(i) == device or conn.address == device:
print("Removing output %s" % conn.address)
try:
mp_util.child_fd_list_add(conn.port.fileno())
except Exception:
pass
conn.close()
self.mpstate.mav_outputs.pop(i)
return | python | def cmd_output_remove(self, args):
'''remove an output'''
device = args[0]
for i in range(len(self.mpstate.mav_outputs)):
conn = self.mpstate.mav_outputs[i]
if str(i) == device or conn.address == device:
print("Removing output %s" % conn.address)
try:
mp_util.child_fd_list_add(conn.port.fileno())
except Exception:
pass
conn.close()
self.mpstate.mav_outputs.pop(i)
return | [
"def",
"cmd_output_remove",
"(",
"self",
",",
"args",
")",
":",
"device",
"=",
"args",
"[",
"0",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"mpstate",
".",
"mav_outputs",
")",
")",
":",
"conn",
"=",
"self",
".",
"mpstate",
".",
... | remove an output | [
"remove",
"an",
"output"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_output.py#L90-L103 | train | 230,655 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_map/mp_slipmap.py | MPSlipMap.set_center | def set_center(self, lat, lon):
'''set center of view'''
self.object_queue.put(SlipCenter((lat,lon))) | python | def set_center(self, lat, lon):
'''set center of view'''
self.object_queue.put(SlipCenter((lat,lon))) | [
"def",
"set_center",
"(",
"self",
",",
"lat",
",",
"lon",
")",
":",
"self",
".",
"object_queue",
".",
"put",
"(",
"SlipCenter",
"(",
"(",
"lat",
",",
"lon",
")",
")",
")"
] | set center of view | [
"set",
"center",
"of",
"view"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_map/mp_slipmap.py#L125-L127 | train | 230,656 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_map/mp_slipmap.py | MPSlipMap.get_event | def get_event(self):
'''return next event or None'''
if self.event_queue.qsize() == 0:
return None
evt = self.event_queue.get()
while isinstance(evt, win_layout.WinLayout):
win_layout.set_layout(evt, self.set_layout)
if self.event_queue.qsize() == 0:
return None
evt = self.event_queue.get()
return evt | python | def get_event(self):
'''return next event or None'''
if self.event_queue.qsize() == 0:
return None
evt = self.event_queue.get()
while isinstance(evt, win_layout.WinLayout):
win_layout.set_layout(evt, self.set_layout)
if self.event_queue.qsize() == 0:
return None
evt = self.event_queue.get()
return evt | [
"def",
"get_event",
"(",
"self",
")",
":",
"if",
"self",
".",
"event_queue",
".",
"qsize",
"(",
")",
"==",
"0",
":",
"return",
"None",
"evt",
"=",
"self",
".",
"event_queue",
".",
"get",
"(",
")",
"while",
"isinstance",
"(",
"evt",
",",
"win_layout",... | return next event or None | [
"return",
"next",
"event",
"or",
"None"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_map/mp_slipmap.py#L153-L163 | train | 230,657 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_layout.py | LayoutModule.cmd_layout | def cmd_layout(self, args):
'''handle layout command'''
from MAVProxy.modules.lib import win_layout
if len(args) < 1:
print("usage: layout <save|load>")
return
if args[0] == "load":
win_layout.load_layout(self.mpstate.settings.vehicle_name)
elif args[0] == "save":
win_layout.save_layout(self.mpstate.settings.vehicle_name) | python | def cmd_layout(self, args):
'''handle layout command'''
from MAVProxy.modules.lib import win_layout
if len(args) < 1:
print("usage: layout <save|load>")
return
if args[0] == "load":
win_layout.load_layout(self.mpstate.settings.vehicle_name)
elif args[0] == "save":
win_layout.save_layout(self.mpstate.settings.vehicle_name) | [
"def",
"cmd_layout",
"(",
"self",
",",
"args",
")",
":",
"from",
"MAVProxy",
".",
"modules",
".",
"lib",
"import",
"win_layout",
"if",
"len",
"(",
"args",
")",
"<",
"1",
":",
"print",
"(",
"\"usage: layout <save|load>\"",
")",
"return",
"if",
"args",
"["... | handle layout command | [
"handle",
"layout",
"command"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_layout.py#L13-L22 | train | 230,658 |
ArduPilot/MAVProxy | MAVProxy/modules/lib/mp_util.py | download_files | def download_files(files):
'''download an array of files'''
for (url, file) in files:
print("Downloading %s as %s" % (url, file))
data = download_url(url)
if data is None:
continue
try:
open(file, mode='wb').write(data)
except Exception as e:
print("Failed to save to %s : %s" % (file, e)) | python | def download_files(files):
'''download an array of files'''
for (url, file) in files:
print("Downloading %s as %s" % (url, file))
data = download_url(url)
if data is None:
continue
try:
open(file, mode='wb').write(data)
except Exception as e:
print("Failed to save to %s : %s" % (file, e)) | [
"def",
"download_files",
"(",
"files",
")",
":",
"for",
"(",
"url",
",",
"file",
")",
"in",
"files",
":",
"print",
"(",
"\"Downloading %s as %s\"",
"%",
"(",
"url",
",",
"file",
")",
")",
"data",
"=",
"download_url",
"(",
"url",
")",
"if",
"data",
"i... | download an array of files | [
"download",
"an",
"array",
"of",
"files"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/lib/mp_util.py#L265-L275 | train | 230,659 |
ArduPilot/MAVProxy | MAVProxy/modules/lib/mp_util.py | null_term | def null_term(str):
'''null terminate a string for py3'''
if sys.version_info.major < 3:
return str
if isinstance(str, bytes):
str = str.decode("utf-8")
idx = str.find("\0")
if idx != -1:
str = str[:idx]
return str | python | def null_term(str):
'''null terminate a string for py3'''
if sys.version_info.major < 3:
return str
if isinstance(str, bytes):
str = str.decode("utf-8")
idx = str.find("\0")
if idx != -1:
str = str[:idx]
return str | [
"def",
"null_term",
"(",
"str",
")",
":",
"if",
"sys",
".",
"version_info",
".",
"major",
"<",
"3",
":",
"return",
"str",
"if",
"isinstance",
"(",
"str",
",",
"bytes",
")",
":",
"str",
"=",
"str",
".",
"decode",
"(",
"\"utf-8\"",
")",
"idx",
"=",
... | null terminate a string for py3 | [
"null",
"terminate",
"a",
"string",
"for",
"py3"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/lib/mp_util.py#L316-L325 | train | 230,660 |
ArduPilot/MAVProxy | MAVProxy/modules/lib/mp_util.py | decode_devid | def decode_devid(devid, pname):
'''decode one device ID. Used for 'devid' command in mavproxy and MAVExplorer'''
devid = int(devid)
if devid == 0:
return
bus_type=devid & 0x07
bus=(devid>>3) & 0x1F
address=(devid>>8)&0xFF
devtype=(devid>>16)
bustypes = {
1: "I2C",
2: "SPI",
3: "UAVCAN",
4: "SITL"
}
compass_types = {
0x01 : "DEVTYPE_HMC5883_OLD",
0x07 : "DEVTYPE_HMC5883",
0x02 : "DEVTYPE_LSM303D",
0x04 : "DEVTYPE_AK8963 ",
0x05 : "DEVTYPE_BMM150 ",
0x06 : "DEVTYPE_LSM9DS1",
0x08 : "DEVTYPE_LIS3MDL",
0x09 : "DEVTYPE_AK09916",
0x0A : "DEVTYPE_IST8310",
0x0B : "DEVTYPE_ICM20948",
0x0C : "DEVTYPE_MMC3416",
0x0D : "DEVTYPE_QMC5883L",
0x0E : "DEVTYPE_MAG3110",
0x0F : "DEVTYPE_SITL",
0x10 : "DEVTYPE_IST8308",
0x11 : "DEVTYPE_RM3100",
}
imu_types = {
0x09 : "DEVTYPE_BMI160",
0x10 : "DEVTYPE_L3G4200D",
0x11 : "DEVTYPE_ACC_LSM303D",
0x12 : "DEVTYPE_ACC_BMA180",
0x13 : "DEVTYPE_ACC_MPU6000",
0x16 : "DEVTYPE_ACC_MPU9250",
0x17 : "DEVTYPE_ACC_IIS328DQ",
0x21 : "DEVTYPE_GYR_MPU6000",
0x22 : "DEVTYPE_GYR_L3GD20",
0x24 : "DEVTYPE_GYR_MPU9250",
0x25 : "DEVTYPE_GYR_I3G4250D",
0x26 : "DEVTYPE_GYR_LSM9DS1",
0x27 : "DEVTYPE_INS_ICM20789",
0x28 : "DEVTYPE_INS_ICM20689",
0x29 : "DEVTYPE_INS_BMI055",
0x2A : "DEVTYPE_SITL",
0x2B : "DEVTYPE_INS_BMI088",
0x2C : "DEVTYPE_INS_ICM20948",
0x2D : "DEVTYPE_INS_ICM20648",
0x2E : "DEVTYPE_INS_ICM20649",
0x2F : "DEVTYPE_INS_ICM20602",
}
decoded_devname = ""
if pname.startswith("COMPASS"):
decoded_devname = compass_types.get(devtype, "UNKNOWN")
if pname.startswith("INS"):
decoded_devname = imu_types.get(devtype, "UNKNOWN")
print("%s: bus_type:%s(%u) bus:%u address:%u(0x%x) devtype:%u(0x%x) %s" % (
pname,
bustypes.get(bus_type,"UNKNOWN"), bus_type,
bus, address, address, devtype, devtype, decoded_devname)) | python | def decode_devid(devid, pname):
'''decode one device ID. Used for 'devid' command in mavproxy and MAVExplorer'''
devid = int(devid)
if devid == 0:
return
bus_type=devid & 0x07
bus=(devid>>3) & 0x1F
address=(devid>>8)&0xFF
devtype=(devid>>16)
bustypes = {
1: "I2C",
2: "SPI",
3: "UAVCAN",
4: "SITL"
}
compass_types = {
0x01 : "DEVTYPE_HMC5883_OLD",
0x07 : "DEVTYPE_HMC5883",
0x02 : "DEVTYPE_LSM303D",
0x04 : "DEVTYPE_AK8963 ",
0x05 : "DEVTYPE_BMM150 ",
0x06 : "DEVTYPE_LSM9DS1",
0x08 : "DEVTYPE_LIS3MDL",
0x09 : "DEVTYPE_AK09916",
0x0A : "DEVTYPE_IST8310",
0x0B : "DEVTYPE_ICM20948",
0x0C : "DEVTYPE_MMC3416",
0x0D : "DEVTYPE_QMC5883L",
0x0E : "DEVTYPE_MAG3110",
0x0F : "DEVTYPE_SITL",
0x10 : "DEVTYPE_IST8308",
0x11 : "DEVTYPE_RM3100",
}
imu_types = {
0x09 : "DEVTYPE_BMI160",
0x10 : "DEVTYPE_L3G4200D",
0x11 : "DEVTYPE_ACC_LSM303D",
0x12 : "DEVTYPE_ACC_BMA180",
0x13 : "DEVTYPE_ACC_MPU6000",
0x16 : "DEVTYPE_ACC_MPU9250",
0x17 : "DEVTYPE_ACC_IIS328DQ",
0x21 : "DEVTYPE_GYR_MPU6000",
0x22 : "DEVTYPE_GYR_L3GD20",
0x24 : "DEVTYPE_GYR_MPU9250",
0x25 : "DEVTYPE_GYR_I3G4250D",
0x26 : "DEVTYPE_GYR_LSM9DS1",
0x27 : "DEVTYPE_INS_ICM20789",
0x28 : "DEVTYPE_INS_ICM20689",
0x29 : "DEVTYPE_INS_BMI055",
0x2A : "DEVTYPE_SITL",
0x2B : "DEVTYPE_INS_BMI088",
0x2C : "DEVTYPE_INS_ICM20948",
0x2D : "DEVTYPE_INS_ICM20648",
0x2E : "DEVTYPE_INS_ICM20649",
0x2F : "DEVTYPE_INS_ICM20602",
}
decoded_devname = ""
if pname.startswith("COMPASS"):
decoded_devname = compass_types.get(devtype, "UNKNOWN")
if pname.startswith("INS"):
decoded_devname = imu_types.get(devtype, "UNKNOWN")
print("%s: bus_type:%s(%u) bus:%u address:%u(0x%x) devtype:%u(0x%x) %s" % (
pname,
bustypes.get(bus_type,"UNKNOWN"), bus_type,
bus, address, address, devtype, devtype, decoded_devname)) | [
"def",
"decode_devid",
"(",
"devid",
",",
"pname",
")",
":",
"devid",
"=",
"int",
"(",
"devid",
")",
"if",
"devid",
"==",
"0",
":",
"return",
"bus_type",
"=",
"devid",
"&",
"0x07",
"bus",
"=",
"(",
"devid",
">>",
"3",
")",
"&",
"0x1F",
"address",
... | decode one device ID. Used for 'devid' command in mavproxy and MAVExplorer | [
"decode",
"one",
"device",
"ID",
".",
"Used",
"for",
"devid",
"command",
"in",
"mavproxy",
"and",
"MAVExplorer"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/lib/mp_util.py#L328-L400 | train | 230,661 |
django-auth-ldap/django-auth-ldap | django_auth_ldap/backend.py | _LDAPUser._authenticate_user_dn | def _authenticate_user_dn(self, password):
"""
Binds to the LDAP server with the user's DN and password. Raises
AuthenticationFailed on failure.
"""
if self.dn is None:
raise self.AuthenticationFailed("failed to map the username to a DN.")
try:
sticky = self.settings.BIND_AS_AUTHENTICATING_USER
self._bind_as(self.dn, password, sticky=sticky)
except ldap.INVALID_CREDENTIALS:
raise self.AuthenticationFailed("user DN/password rejected by LDAP server.") | python | def _authenticate_user_dn(self, password):
"""
Binds to the LDAP server with the user's DN and password. Raises
AuthenticationFailed on failure.
"""
if self.dn is None:
raise self.AuthenticationFailed("failed to map the username to a DN.")
try:
sticky = self.settings.BIND_AS_AUTHENTICATING_USER
self._bind_as(self.dn, password, sticky=sticky)
except ldap.INVALID_CREDENTIALS:
raise self.AuthenticationFailed("user DN/password rejected by LDAP server.") | [
"def",
"_authenticate_user_dn",
"(",
"self",
",",
"password",
")",
":",
"if",
"self",
".",
"dn",
"is",
"None",
":",
"raise",
"self",
".",
"AuthenticationFailed",
"(",
"\"failed to map the username to a DN.\"",
")",
"try",
":",
"sticky",
"=",
"self",
".",
"sett... | Binds to the LDAP server with the user's DN and password. Raises
AuthenticationFailed on failure. | [
"Binds",
"to",
"the",
"LDAP",
"server",
"with",
"the",
"user",
"s",
"DN",
"and",
"password",
".",
"Raises",
"AuthenticationFailed",
"on",
"failure",
"."
] | 9ce3c2825527f8faa1793958b041816e63d839af | https://github.com/django-auth-ldap/django-auth-ldap/blob/9ce3c2825527f8faa1793958b041816e63d839af/django_auth_ldap/backend.py#L471-L484 | train | 230,662 |
django-auth-ldap/django-auth-ldap | django_auth_ldap/backend.py | _LDAPUser._load_user_dn | def _load_user_dn(self):
"""
Populates self._user_dn with the distinguished name of our user.
This will either construct the DN from a template in
AUTH_LDAP_USER_DN_TEMPLATE or connect to the server and search for it.
If we have to search, we'll cache the DN.
"""
if self._using_simple_bind_mode():
self._user_dn = self._construct_simple_user_dn()
else:
if self.settings.CACHE_TIMEOUT > 0:
cache_key = valid_cache_key(
"django_auth_ldap.user_dn.{}".format(self._username)
)
self._user_dn = cache.get_or_set(
cache_key, self._search_for_user_dn, self.settings.CACHE_TIMEOUT
)
else:
self._user_dn = self._search_for_user_dn() | python | def _load_user_dn(self):
"""
Populates self._user_dn with the distinguished name of our user.
This will either construct the DN from a template in
AUTH_LDAP_USER_DN_TEMPLATE or connect to the server and search for it.
If we have to search, we'll cache the DN.
"""
if self._using_simple_bind_mode():
self._user_dn = self._construct_simple_user_dn()
else:
if self.settings.CACHE_TIMEOUT > 0:
cache_key = valid_cache_key(
"django_auth_ldap.user_dn.{}".format(self._username)
)
self._user_dn = cache.get_or_set(
cache_key, self._search_for_user_dn, self.settings.CACHE_TIMEOUT
)
else:
self._user_dn = self._search_for_user_dn() | [
"def",
"_load_user_dn",
"(",
"self",
")",
":",
"if",
"self",
".",
"_using_simple_bind_mode",
"(",
")",
":",
"self",
".",
"_user_dn",
"=",
"self",
".",
"_construct_simple_user_dn",
"(",
")",
"else",
":",
"if",
"self",
".",
"settings",
".",
"CACHE_TIMEOUT",
... | Populates self._user_dn with the distinguished name of our user.
This will either construct the DN from a template in
AUTH_LDAP_USER_DN_TEMPLATE or connect to the server and search for it.
If we have to search, we'll cache the DN. | [
"Populates",
"self",
".",
"_user_dn",
"with",
"the",
"distinguished",
"name",
"of",
"our",
"user",
"."
] | 9ce3c2825527f8faa1793958b041816e63d839af | https://github.com/django-auth-ldap/django-auth-ldap/blob/9ce3c2825527f8faa1793958b041816e63d839af/django_auth_ldap/backend.py#L496-L516 | train | 230,663 |
django-auth-ldap/django-auth-ldap | django_auth_ldap/backend.py | _LDAPUser._search_for_user_dn | def _search_for_user_dn(self):
"""
Searches the directory for a user matching AUTH_LDAP_USER_SEARCH.
Populates self._user_dn and self._user_attrs.
"""
search = self.settings.USER_SEARCH
if search is None:
raise ImproperlyConfigured(
"AUTH_LDAP_USER_SEARCH must be an LDAPSearch instance."
)
results = search.execute(self.connection, {"user": self._username})
if results is not None and len(results) == 1:
(user_dn, self._user_attrs) = next(iter(results))
else:
user_dn = None
return user_dn | python | def _search_for_user_dn(self):
"""
Searches the directory for a user matching AUTH_LDAP_USER_SEARCH.
Populates self._user_dn and self._user_attrs.
"""
search = self.settings.USER_SEARCH
if search is None:
raise ImproperlyConfigured(
"AUTH_LDAP_USER_SEARCH must be an LDAPSearch instance."
)
results = search.execute(self.connection, {"user": self._username})
if results is not None and len(results) == 1:
(user_dn, self._user_attrs) = next(iter(results))
else:
user_dn = None
return user_dn | [
"def",
"_search_for_user_dn",
"(",
"self",
")",
":",
"search",
"=",
"self",
".",
"settings",
".",
"USER_SEARCH",
"if",
"search",
"is",
"None",
":",
"raise",
"ImproperlyConfigured",
"(",
"\"AUTH_LDAP_USER_SEARCH must be an LDAPSearch instance.\"",
")",
"results",
"=",
... | Searches the directory for a user matching AUTH_LDAP_USER_SEARCH.
Populates self._user_dn and self._user_attrs. | [
"Searches",
"the",
"directory",
"for",
"a",
"user",
"matching",
"AUTH_LDAP_USER_SEARCH",
".",
"Populates",
"self",
".",
"_user_dn",
"and",
"self",
".",
"_user_attrs",
"."
] | 9ce3c2825527f8faa1793958b041816e63d839af | https://github.com/django-auth-ldap/django-auth-ldap/blob/9ce3c2825527f8faa1793958b041816e63d839af/django_auth_ldap/backend.py#L526-L543 | train | 230,664 |
django-auth-ldap/django-auth-ldap | django_auth_ldap/backend.py | _LDAPUser._normalize_group_dns | def _normalize_group_dns(self, group_dns):
"""
Converts one or more group DNs to an LDAPGroupQuery.
group_dns may be a string, a non-empty list or tuple of strings, or an
LDAPGroupQuery. The result will be an LDAPGroupQuery. A list or tuple
will be joined with the | operator.
"""
if isinstance(group_dns, LDAPGroupQuery):
query = group_dns
elif isinstance(group_dns, str):
query = LDAPGroupQuery(group_dns)
elif isinstance(group_dns, (list, tuple)) and len(group_dns) > 0:
query = reduce(operator.or_, map(LDAPGroupQuery, group_dns))
else:
raise ValueError(group_dns)
return query | python | def _normalize_group_dns(self, group_dns):
"""
Converts one or more group DNs to an LDAPGroupQuery.
group_dns may be a string, a non-empty list or tuple of strings, or an
LDAPGroupQuery. The result will be an LDAPGroupQuery. A list or tuple
will be joined with the | operator.
"""
if isinstance(group_dns, LDAPGroupQuery):
query = group_dns
elif isinstance(group_dns, str):
query = LDAPGroupQuery(group_dns)
elif isinstance(group_dns, (list, tuple)) and len(group_dns) > 0:
query = reduce(operator.or_, map(LDAPGroupQuery, group_dns))
else:
raise ValueError(group_dns)
return query | [
"def",
"_normalize_group_dns",
"(",
"self",
",",
"group_dns",
")",
":",
"if",
"isinstance",
"(",
"group_dns",
",",
"LDAPGroupQuery",
")",
":",
"query",
"=",
"group_dns",
"elif",
"isinstance",
"(",
"group_dns",
",",
"str",
")",
":",
"query",
"=",
"LDAPGroupQu... | Converts one or more group DNs to an LDAPGroupQuery.
group_dns may be a string, a non-empty list or tuple of strings, or an
LDAPGroupQuery. The result will be an LDAPGroupQuery. A list or tuple
will be joined with the | operator. | [
"Converts",
"one",
"or",
"more",
"group",
"DNs",
"to",
"an",
"LDAPGroupQuery",
"."
] | 9ce3c2825527f8faa1793958b041816e63d839af | https://github.com/django-auth-ldap/django-auth-ldap/blob/9ce3c2825527f8faa1793958b041816e63d839af/django_auth_ldap/backend.py#L668-L686 | train | 230,665 |
django-auth-ldap/django-auth-ldap | django_auth_ldap/backend.py | _LDAPUser._normalize_mirror_settings | def _normalize_mirror_settings(self):
"""
Validates the group mirroring settings and converts them as necessary.
"""
def malformed_mirror_groups_except():
return ImproperlyConfigured(
"{} must be a collection of group names".format(
self.settings._name("MIRROR_GROUPS_EXCEPT")
)
)
def malformed_mirror_groups():
return ImproperlyConfigured(
"{} must be True or a collection of group names".format(
self.settings._name("MIRROR_GROUPS")
)
)
mge = self.settings.MIRROR_GROUPS_EXCEPT
mg = self.settings.MIRROR_GROUPS
if mge is not None:
if isinstance(mge, (set, frozenset)):
pass
elif isinstance(mge, (list, tuple)):
mge = self.settings.MIRROR_GROUPS_EXCEPT = frozenset(mge)
else:
raise malformed_mirror_groups_except()
if not all(isinstance(value, str) for value in mge):
raise malformed_mirror_groups_except()
elif mg:
warnings.warn(
ConfigurationWarning(
"Ignoring {} in favor of {}".format(
self.settings._name("MIRROR_GROUPS"),
self.settings._name("MIRROR_GROUPS_EXCEPT"),
)
)
)
mg = self.settings.MIRROR_GROUPS = None
if mg is not None:
if isinstance(mg, (bool, set, frozenset)):
pass
elif isinstance(mg, (list, tuple)):
mg = self.settings.MIRROR_GROUPS = frozenset(mg)
else:
raise malformed_mirror_groups()
if isinstance(mg, (set, frozenset)) and (
not all(isinstance(value, str) for value in mg)
):
raise malformed_mirror_groups() | python | def _normalize_mirror_settings(self):
"""
Validates the group mirroring settings and converts them as necessary.
"""
def malformed_mirror_groups_except():
return ImproperlyConfigured(
"{} must be a collection of group names".format(
self.settings._name("MIRROR_GROUPS_EXCEPT")
)
)
def malformed_mirror_groups():
return ImproperlyConfigured(
"{} must be True or a collection of group names".format(
self.settings._name("MIRROR_GROUPS")
)
)
mge = self.settings.MIRROR_GROUPS_EXCEPT
mg = self.settings.MIRROR_GROUPS
if mge is not None:
if isinstance(mge, (set, frozenset)):
pass
elif isinstance(mge, (list, tuple)):
mge = self.settings.MIRROR_GROUPS_EXCEPT = frozenset(mge)
else:
raise malformed_mirror_groups_except()
if not all(isinstance(value, str) for value in mge):
raise malformed_mirror_groups_except()
elif mg:
warnings.warn(
ConfigurationWarning(
"Ignoring {} in favor of {}".format(
self.settings._name("MIRROR_GROUPS"),
self.settings._name("MIRROR_GROUPS_EXCEPT"),
)
)
)
mg = self.settings.MIRROR_GROUPS = None
if mg is not None:
if isinstance(mg, (bool, set, frozenset)):
pass
elif isinstance(mg, (list, tuple)):
mg = self.settings.MIRROR_GROUPS = frozenset(mg)
else:
raise malformed_mirror_groups()
if isinstance(mg, (set, frozenset)) and (
not all(isinstance(value, str) for value in mg)
):
raise malformed_mirror_groups() | [
"def",
"_normalize_mirror_settings",
"(",
"self",
")",
":",
"def",
"malformed_mirror_groups_except",
"(",
")",
":",
"return",
"ImproperlyConfigured",
"(",
"\"{} must be a collection of group names\"",
".",
"format",
"(",
"self",
".",
"settings",
".",
"_name",
"(",
"\"... | Validates the group mirroring settings and converts them as necessary. | [
"Validates",
"the",
"group",
"mirroring",
"settings",
"and",
"converts",
"them",
"as",
"necessary",
"."
] | 9ce3c2825527f8faa1793958b041816e63d839af | https://github.com/django-auth-ldap/django-auth-ldap/blob/9ce3c2825527f8faa1793958b041816e63d839af/django_auth_ldap/backend.py#L688-L742 | train | 230,666 |
django-auth-ldap/django-auth-ldap | django_auth_ldap/backend.py | _LDAPUser._get_groups | def _get_groups(self):
"""
Returns an _LDAPUserGroups object, which can determine group
membership.
"""
if self._groups is None:
self._groups = _LDAPUserGroups(self)
return self._groups | python | def _get_groups(self):
"""
Returns an _LDAPUserGroups object, which can determine group
membership.
"""
if self._groups is None:
self._groups = _LDAPUserGroups(self)
return self._groups | [
"def",
"_get_groups",
"(",
"self",
")",
":",
"if",
"self",
".",
"_groups",
"is",
"None",
":",
"self",
".",
"_groups",
"=",
"_LDAPUserGroups",
"(",
"self",
")",
"return",
"self",
".",
"_groups"
] | Returns an _LDAPUserGroups object, which can determine group
membership. | [
"Returns",
"an",
"_LDAPUserGroups",
"object",
"which",
"can",
"determine",
"group",
"membership",
"."
] | 9ce3c2825527f8faa1793958b041816e63d839af | https://github.com/django-auth-ldap/django-auth-ldap/blob/9ce3c2825527f8faa1793958b041816e63d839af/django_auth_ldap/backend.py#L801-L809 | train | 230,667 |
django-auth-ldap/django-auth-ldap | django_auth_ldap/backend.py | _LDAPUser._bind | def _bind(self):
"""
Binds to the LDAP server with AUTH_LDAP_BIND_DN and
AUTH_LDAP_BIND_PASSWORD.
"""
self._bind_as(self.settings.BIND_DN, self.settings.BIND_PASSWORD, sticky=True) | python | def _bind(self):
"""
Binds to the LDAP server with AUTH_LDAP_BIND_DN and
AUTH_LDAP_BIND_PASSWORD.
"""
self._bind_as(self.settings.BIND_DN, self.settings.BIND_PASSWORD, sticky=True) | [
"def",
"_bind",
"(",
"self",
")",
":",
"self",
".",
"_bind_as",
"(",
"self",
".",
"settings",
".",
"BIND_DN",
",",
"self",
".",
"settings",
".",
"BIND_PASSWORD",
",",
"sticky",
"=",
"True",
")"
] | Binds to the LDAP server with AUTH_LDAP_BIND_DN and
AUTH_LDAP_BIND_PASSWORD. | [
"Binds",
"to",
"the",
"LDAP",
"server",
"with",
"AUTH_LDAP_BIND_DN",
"and",
"AUTH_LDAP_BIND_PASSWORD",
"."
] | 9ce3c2825527f8faa1793958b041816e63d839af | https://github.com/django-auth-ldap/django-auth-ldap/blob/9ce3c2825527f8faa1793958b041816e63d839af/django_auth_ldap/backend.py#L815-L820 | train | 230,668 |
django-auth-ldap/django-auth-ldap | django_auth_ldap/backend.py | _LDAPUser._bind_as | def _bind_as(self, bind_dn, bind_password, sticky=False):
"""
Binds to the LDAP server with the given credentials. This does not trap
exceptions.
If sticky is True, then we will consider the connection to be bound for
the life of this object. If False, then the caller only wishes to test
the credentials, after which the connection will be considered unbound.
"""
self._get_connection().simple_bind_s(bind_dn, bind_password)
self._connection_bound = sticky | python | def _bind_as(self, bind_dn, bind_password, sticky=False):
"""
Binds to the LDAP server with the given credentials. This does not trap
exceptions.
If sticky is True, then we will consider the connection to be bound for
the life of this object. If False, then the caller only wishes to test
the credentials, after which the connection will be considered unbound.
"""
self._get_connection().simple_bind_s(bind_dn, bind_password)
self._connection_bound = sticky | [
"def",
"_bind_as",
"(",
"self",
",",
"bind_dn",
",",
"bind_password",
",",
"sticky",
"=",
"False",
")",
":",
"self",
".",
"_get_connection",
"(",
")",
".",
"simple_bind_s",
"(",
"bind_dn",
",",
"bind_password",
")",
"self",
".",
"_connection_bound",
"=",
"... | Binds to the LDAP server with the given credentials. This does not trap
exceptions.
If sticky is True, then we will consider the connection to be bound for
the life of this object. If False, then the caller only wishes to test
the credentials, after which the connection will be considered unbound. | [
"Binds",
"to",
"the",
"LDAP",
"server",
"with",
"the",
"given",
"credentials",
".",
"This",
"does",
"not",
"trap",
"exceptions",
"."
] | 9ce3c2825527f8faa1793958b041816e63d839af | https://github.com/django-auth-ldap/django-auth-ldap/blob/9ce3c2825527f8faa1793958b041816e63d839af/django_auth_ldap/backend.py#L822-L833 | train | 230,669 |
django-auth-ldap/django-auth-ldap | django_auth_ldap/backend.py | _LDAPUserGroups._init_group_settings | def _init_group_settings(self):
"""
Loads the settings we need to deal with groups.
Raises ImproperlyConfigured if anything's not right.
"""
self._group_type = self.settings.GROUP_TYPE
if self._group_type is None:
raise ImproperlyConfigured(
"AUTH_LDAP_GROUP_TYPE must be an LDAPGroupType instance."
)
self._group_search = self.settings.GROUP_SEARCH
if self._group_search is None:
raise ImproperlyConfigured(
"AUTH_LDAP_GROUP_SEARCH must be an LDAPSearch instance."
) | python | def _init_group_settings(self):
"""
Loads the settings we need to deal with groups.
Raises ImproperlyConfigured if anything's not right.
"""
self._group_type = self.settings.GROUP_TYPE
if self._group_type is None:
raise ImproperlyConfigured(
"AUTH_LDAP_GROUP_TYPE must be an LDAPGroupType instance."
)
self._group_search = self.settings.GROUP_SEARCH
if self._group_search is None:
raise ImproperlyConfigured(
"AUTH_LDAP_GROUP_SEARCH must be an LDAPSearch instance."
) | [
"def",
"_init_group_settings",
"(",
"self",
")",
":",
"self",
".",
"_group_type",
"=",
"self",
".",
"settings",
".",
"GROUP_TYPE",
"if",
"self",
".",
"_group_type",
"is",
"None",
":",
"raise",
"ImproperlyConfigured",
"(",
"\"AUTH_LDAP_GROUP_TYPE must be an LDAPGroup... | Loads the settings we need to deal with groups.
Raises ImproperlyConfigured if anything's not right. | [
"Loads",
"the",
"settings",
"we",
"need",
"to",
"deal",
"with",
"groups",
"."
] | 9ce3c2825527f8faa1793958b041816e63d839af | https://github.com/django-auth-ldap/django-auth-ldap/blob/9ce3c2825527f8faa1793958b041816e63d839af/django_auth_ldap/backend.py#L882-L899 | train | 230,670 |
django-auth-ldap/django-auth-ldap | django_auth_ldap/backend.py | _LDAPUserGroups.get_group_names | def get_group_names(self):
"""
Returns the set of Django group names that this user belongs to by
virtue of LDAP group memberships.
"""
if self._group_names is None:
self._load_cached_attr("_group_names")
if self._group_names is None:
group_infos = self._get_group_infos()
self._group_names = {
self._group_type.group_name_from_info(group_info)
for group_info in group_infos
}
self._cache_attr("_group_names")
return self._group_names | python | def get_group_names(self):
"""
Returns the set of Django group names that this user belongs to by
virtue of LDAP group memberships.
"""
if self._group_names is None:
self._load_cached_attr("_group_names")
if self._group_names is None:
group_infos = self._get_group_infos()
self._group_names = {
self._group_type.group_name_from_info(group_info)
for group_info in group_infos
}
self._cache_attr("_group_names")
return self._group_names | [
"def",
"get_group_names",
"(",
"self",
")",
":",
"if",
"self",
".",
"_group_names",
"is",
"None",
":",
"self",
".",
"_load_cached_attr",
"(",
"\"_group_names\"",
")",
"if",
"self",
".",
"_group_names",
"is",
"None",
":",
"group_infos",
"=",
"self",
".",
"_... | Returns the set of Django group names that this user belongs to by
virtue of LDAP group memberships. | [
"Returns",
"the",
"set",
"of",
"Django",
"group",
"names",
"that",
"this",
"user",
"belongs",
"to",
"by",
"virtue",
"of",
"LDAP",
"group",
"memberships",
"."
] | 9ce3c2825527f8faa1793958b041816e63d839af | https://github.com/django-auth-ldap/django-auth-ldap/blob/9ce3c2825527f8faa1793958b041816e63d839af/django_auth_ldap/backend.py#L901-L917 | train | 230,671 |
django-auth-ldap/django-auth-ldap | django_auth_ldap/backend.py | _LDAPUserGroups.is_member_of | def is_member_of(self, group_dn):
"""
Returns true if our user is a member of the given group.
"""
is_member = None
# Normalize the DN
group_dn = group_dn.lower()
# If we have self._group_dns, we'll use it. Otherwise, we'll try to
# avoid the cost of loading it.
if self._group_dns is None:
is_member = self._group_type.is_member(self._ldap_user, group_dn)
if is_member is None:
is_member = group_dn in self.get_group_dns()
logger.debug(
"{} is{}a member of {}".format(
self._ldap_user.dn, is_member and " " or " not ", group_dn
)
)
return is_member | python | def is_member_of(self, group_dn):
"""
Returns true if our user is a member of the given group.
"""
is_member = None
# Normalize the DN
group_dn = group_dn.lower()
# If we have self._group_dns, we'll use it. Otherwise, we'll try to
# avoid the cost of loading it.
if self._group_dns is None:
is_member = self._group_type.is_member(self._ldap_user, group_dn)
if is_member is None:
is_member = group_dn in self.get_group_dns()
logger.debug(
"{} is{}a member of {}".format(
self._ldap_user.dn, is_member and " " or " not ", group_dn
)
)
return is_member | [
"def",
"is_member_of",
"(",
"self",
",",
"group_dn",
")",
":",
"is_member",
"=",
"None",
"# Normalize the DN",
"group_dn",
"=",
"group_dn",
".",
"lower",
"(",
")",
"# If we have self._group_dns, we'll use it. Otherwise, we'll try to",
"# avoid the cost of loading it.",
"if"... | Returns true if our user is a member of the given group. | [
"Returns",
"true",
"if",
"our",
"user",
"is",
"a",
"member",
"of",
"the",
"given",
"group",
"."
] | 9ce3c2825527f8faa1793958b041816e63d839af | https://github.com/django-auth-ldap/django-auth-ldap/blob/9ce3c2825527f8faa1793958b041816e63d839af/django_auth_ldap/backend.py#L919-L942 | train | 230,672 |
django-auth-ldap/django-auth-ldap | django_auth_ldap/config.py | _LDAPConfig.get_ldap | def get_ldap(cls, global_options=None):
"""
Returns the configured ldap module.
"""
# Apply global LDAP options once
if not cls._ldap_configured and global_options is not None:
for opt, value in global_options.items():
ldap.set_option(opt, value)
cls._ldap_configured = True
return ldap | python | def get_ldap(cls, global_options=None):
"""
Returns the configured ldap module.
"""
# Apply global LDAP options once
if not cls._ldap_configured and global_options is not None:
for opt, value in global_options.items():
ldap.set_option(opt, value)
cls._ldap_configured = True
return ldap | [
"def",
"get_ldap",
"(",
"cls",
",",
"global_options",
"=",
"None",
")",
":",
"# Apply global LDAP options once",
"if",
"not",
"cls",
".",
"_ldap_configured",
"and",
"global_options",
"is",
"not",
"None",
":",
"for",
"opt",
",",
"value",
"in",
"global_options",
... | Returns the configured ldap module. | [
"Returns",
"the",
"configured",
"ldap",
"module",
"."
] | 9ce3c2825527f8faa1793958b041816e63d839af | https://github.com/django-auth-ldap/django-auth-ldap/blob/9ce3c2825527f8faa1793958b041816e63d839af/django_auth_ldap/config.py#L54-L65 | train | 230,673 |
django-auth-ldap/django-auth-ldap | django_auth_ldap/config.py | LDAPSearch.search_with_additional_terms | def search_with_additional_terms(self, term_dict, escape=True):
"""
Returns a new search object with additional search terms and-ed to the
filter string. term_dict maps attribute names to assertion values. If
you don't want the values escaped, pass escape=False.
"""
term_strings = [self.filterstr]
for name, value in term_dict.items():
if escape:
value = self.ldap.filter.escape_filter_chars(value)
term_strings.append("({}={})".format(name, value))
filterstr = "(&{})".format("".join(term_strings))
return self.__class__(
self.base_dn, self.scope, filterstr, attrlist=self.attrlist
) | python | def search_with_additional_terms(self, term_dict, escape=True):
"""
Returns a new search object with additional search terms and-ed to the
filter string. term_dict maps attribute names to assertion values. If
you don't want the values escaped, pass escape=False.
"""
term_strings = [self.filterstr]
for name, value in term_dict.items():
if escape:
value = self.ldap.filter.escape_filter_chars(value)
term_strings.append("({}={})".format(name, value))
filterstr = "(&{})".format("".join(term_strings))
return self.__class__(
self.base_dn, self.scope, filterstr, attrlist=self.attrlist
) | [
"def",
"search_with_additional_terms",
"(",
"self",
",",
"term_dict",
",",
"escape",
"=",
"True",
")",
":",
"term_strings",
"=",
"[",
"self",
".",
"filterstr",
"]",
"for",
"name",
",",
"value",
"in",
"term_dict",
".",
"items",
"(",
")",
":",
"if",
"escap... | Returns a new search object with additional search terms and-ed to the
filter string. term_dict maps attribute names to assertion values. If
you don't want the values escaped, pass escape=False. | [
"Returns",
"a",
"new",
"search",
"object",
"with",
"additional",
"search",
"terms",
"and",
"-",
"ed",
"to",
"the",
"filter",
"string",
".",
"term_dict",
"maps",
"attribute",
"names",
"to",
"assertion",
"values",
".",
"If",
"you",
"don",
"t",
"want",
"the",... | 9ce3c2825527f8faa1793958b041816e63d839af | https://github.com/django-auth-ldap/django-auth-ldap/blob/9ce3c2825527f8faa1793958b041816e63d839af/django_auth_ldap/config.py#L105-L122 | train | 230,674 |
django-auth-ldap/django-auth-ldap | django_auth_ldap/config.py | PosixGroupType.user_groups | def user_groups(self, ldap_user, group_search):
"""
Searches for any group that is either the user's primary or contains the
user as a member.
"""
groups = []
try:
user_uid = ldap_user.attrs["uid"][0]
if "gidNumber" in ldap_user.attrs:
user_gid = ldap_user.attrs["gidNumber"][0]
filterstr = "(|(gidNumber={})(memberUid={}))".format(
self.ldap.filter.escape_filter_chars(user_gid),
self.ldap.filter.escape_filter_chars(user_uid),
)
else:
filterstr = "(memberUid={})".format(
self.ldap.filter.escape_filter_chars(user_uid)
)
search = group_search.search_with_additional_term_string(filterstr)
groups = search.execute(ldap_user.connection)
except (KeyError, IndexError):
pass
return groups | python | def user_groups(self, ldap_user, group_search):
"""
Searches for any group that is either the user's primary or contains the
user as a member.
"""
groups = []
try:
user_uid = ldap_user.attrs["uid"][0]
if "gidNumber" in ldap_user.attrs:
user_gid = ldap_user.attrs["gidNumber"][0]
filterstr = "(|(gidNumber={})(memberUid={}))".format(
self.ldap.filter.escape_filter_chars(user_gid),
self.ldap.filter.escape_filter_chars(user_uid),
)
else:
filterstr = "(memberUid={})".format(
self.ldap.filter.escape_filter_chars(user_uid)
)
search = group_search.search_with_additional_term_string(filterstr)
groups = search.execute(ldap_user.connection)
except (KeyError, IndexError):
pass
return groups | [
"def",
"user_groups",
"(",
"self",
",",
"ldap_user",
",",
"group_search",
")",
":",
"groups",
"=",
"[",
"]",
"try",
":",
"user_uid",
"=",
"ldap_user",
".",
"attrs",
"[",
"\"uid\"",
"]",
"[",
"0",
"]",
"if",
"\"gidNumber\"",
"in",
"ldap_user",
".",
"att... | Searches for any group that is either the user's primary or contains the
user as a member. | [
"Searches",
"for",
"any",
"group",
"that",
"is",
"either",
"the",
"user",
"s",
"primary",
"or",
"contains",
"the",
"user",
"as",
"a",
"member",
"."
] | 9ce3c2825527f8faa1793958b041816e63d839af | https://github.com/django-auth-ldap/django-auth-ldap/blob/9ce3c2825527f8faa1793958b041816e63d839af/django_auth_ldap/config.py#L402-L428 | train | 230,675 |
django-auth-ldap/django-auth-ldap | django_auth_ldap/config.py | PosixGroupType.is_member | def is_member(self, ldap_user, group_dn):
"""
Returns True if the group is the user's primary group or if the user is
listed in the group's memberUid attribute.
"""
try:
user_uid = ldap_user.attrs["uid"][0]
try:
is_member = ldap_user.connection.compare_s(
group_dn, "memberUid", user_uid.encode()
)
except (ldap.UNDEFINED_TYPE, ldap.NO_SUCH_ATTRIBUTE):
is_member = False
if not is_member:
try:
user_gid = ldap_user.attrs["gidNumber"][0]
is_member = ldap_user.connection.compare_s(
group_dn, "gidNumber", user_gid.encode()
)
except (ldap.UNDEFINED_TYPE, ldap.NO_SUCH_ATTRIBUTE):
is_member = False
except (KeyError, IndexError):
is_member = False
return is_member | python | def is_member(self, ldap_user, group_dn):
"""
Returns True if the group is the user's primary group or if the user is
listed in the group's memberUid attribute.
"""
try:
user_uid = ldap_user.attrs["uid"][0]
try:
is_member = ldap_user.connection.compare_s(
group_dn, "memberUid", user_uid.encode()
)
except (ldap.UNDEFINED_TYPE, ldap.NO_SUCH_ATTRIBUTE):
is_member = False
if not is_member:
try:
user_gid = ldap_user.attrs["gidNumber"][0]
is_member = ldap_user.connection.compare_s(
group_dn, "gidNumber", user_gid.encode()
)
except (ldap.UNDEFINED_TYPE, ldap.NO_SUCH_ATTRIBUTE):
is_member = False
except (KeyError, IndexError):
is_member = False
return is_member | [
"def",
"is_member",
"(",
"self",
",",
"ldap_user",
",",
"group_dn",
")",
":",
"try",
":",
"user_uid",
"=",
"ldap_user",
".",
"attrs",
"[",
"\"uid\"",
"]",
"[",
"0",
"]",
"try",
":",
"is_member",
"=",
"ldap_user",
".",
"connection",
".",
"compare_s",
"(... | Returns True if the group is the user's primary group or if the user is
listed in the group's memberUid attribute. | [
"Returns",
"True",
"if",
"the",
"group",
"is",
"the",
"user",
"s",
"primary",
"group",
"or",
"if",
"the",
"user",
"is",
"listed",
"in",
"the",
"group",
"s",
"memberUid",
"attribute",
"."
] | 9ce3c2825527f8faa1793958b041816e63d839af | https://github.com/django-auth-ldap/django-auth-ldap/blob/9ce3c2825527f8faa1793958b041816e63d839af/django_auth_ldap/config.py#L430-L456 | train | 230,676 |
django-auth-ldap/django-auth-ldap | django_auth_ldap/config.py | NestedMemberDNGroupType.user_groups | def user_groups(self, ldap_user, group_search):
"""
This searches for all of a user's groups from the bottom up. In other
words, it returns the groups that the user belongs to, the groups that
those groups belong to, etc. Circular references will be detected and
pruned.
"""
group_info_map = {} # Maps group_dn to group_info of groups we've found
member_dn_set = {ldap_user.dn} # Member DNs to search with next
handled_dn_set = set() # Member DNs that we've already searched with
while len(member_dn_set) > 0:
group_infos = self.find_groups_with_any_member(
member_dn_set, group_search, ldap_user.connection
)
new_group_info_map = {info[0]: info for info in group_infos}
group_info_map.update(new_group_info_map)
handled_dn_set.update(member_dn_set)
# Get ready for the next iteration. To avoid cycles, we make sure
# never to search with the same member DN twice.
member_dn_set = set(new_group_info_map.keys()) - handled_dn_set
return group_info_map.values() | python | def user_groups(self, ldap_user, group_search):
"""
This searches for all of a user's groups from the bottom up. In other
words, it returns the groups that the user belongs to, the groups that
those groups belong to, etc. Circular references will be detected and
pruned.
"""
group_info_map = {} # Maps group_dn to group_info of groups we've found
member_dn_set = {ldap_user.dn} # Member DNs to search with next
handled_dn_set = set() # Member DNs that we've already searched with
while len(member_dn_set) > 0:
group_infos = self.find_groups_with_any_member(
member_dn_set, group_search, ldap_user.connection
)
new_group_info_map = {info[0]: info for info in group_infos}
group_info_map.update(new_group_info_map)
handled_dn_set.update(member_dn_set)
# Get ready for the next iteration. To avoid cycles, we make sure
# never to search with the same member DN twice.
member_dn_set = set(new_group_info_map.keys()) - handled_dn_set
return group_info_map.values() | [
"def",
"user_groups",
"(",
"self",
",",
"ldap_user",
",",
"group_search",
")",
":",
"group_info_map",
"=",
"{",
"}",
"# Maps group_dn to group_info of groups we've found",
"member_dn_set",
"=",
"{",
"ldap_user",
".",
"dn",
"}",
"# Member DNs to search with next",
"handl... | This searches for all of a user's groups from the bottom up. In other
words, it returns the groups that the user belongs to, the groups that
those groups belong to, etc. Circular references will be detected and
pruned. | [
"This",
"searches",
"for",
"all",
"of",
"a",
"user",
"s",
"groups",
"from",
"the",
"bottom",
"up",
".",
"In",
"other",
"words",
"it",
"returns",
"the",
"groups",
"that",
"the",
"user",
"belongs",
"to",
"the",
"groups",
"that",
"those",
"groups",
"belong"... | 9ce3c2825527f8faa1793958b041816e63d839af | https://github.com/django-auth-ldap/django-auth-ldap/blob/9ce3c2825527f8faa1793958b041816e63d839af/django_auth_ldap/config.py#L509-L532 | train | 230,677 |
django-auth-ldap/django-auth-ldap | django_auth_ldap/config.py | LDAPGroupQuery.aggregator | def aggregator(self):
"""
Returns a function for aggregating a sequence of sub-results.
"""
if self.connector == self.AND:
aggregator = all
elif self.connector == self.OR:
aggregator = any
else:
raise ValueError(self.connector)
return aggregator | python | def aggregator(self):
"""
Returns a function for aggregating a sequence of sub-results.
"""
if self.connector == self.AND:
aggregator = all
elif self.connector == self.OR:
aggregator = any
else:
raise ValueError(self.connector)
return aggregator | [
"def",
"aggregator",
"(",
"self",
")",
":",
"if",
"self",
".",
"connector",
"==",
"self",
".",
"AND",
":",
"aggregator",
"=",
"all",
"elif",
"self",
".",
"connector",
"==",
"self",
".",
"OR",
":",
"aggregator",
"=",
"any",
"else",
":",
"raise",
"Valu... | Returns a function for aggregating a sequence of sub-results. | [
"Returns",
"a",
"function",
"for",
"aggregating",
"a",
"sequence",
"of",
"sub",
"-",
"results",
"."
] | 9ce3c2825527f8faa1793958b041816e63d839af | https://github.com/django-auth-ldap/django-auth-ldap/blob/9ce3c2825527f8faa1793958b041816e63d839af/django_auth_ldap/config.py#L682-L693 | train | 230,678 |
django-auth-ldap/django-auth-ldap | django_auth_ldap/config.py | LDAPGroupQuery._resolve_children | def _resolve_children(self, ldap_user, groups):
"""
Generates the query result for each child.
"""
for child in self.children:
if isinstance(child, LDAPGroupQuery):
yield child.resolve(ldap_user, groups)
else:
yield groups.is_member_of(child) | python | def _resolve_children(self, ldap_user, groups):
"""
Generates the query result for each child.
"""
for child in self.children:
if isinstance(child, LDAPGroupQuery):
yield child.resolve(ldap_user, groups)
else:
yield groups.is_member_of(child) | [
"def",
"_resolve_children",
"(",
"self",
",",
"ldap_user",
",",
"groups",
")",
":",
"for",
"child",
"in",
"self",
".",
"children",
":",
"if",
"isinstance",
"(",
"child",
",",
"LDAPGroupQuery",
")",
":",
"yield",
"child",
".",
"resolve",
"(",
"ldap_user",
... | Generates the query result for each child. | [
"Generates",
"the",
"query",
"result",
"for",
"each",
"child",
"."
] | 9ce3c2825527f8faa1793958b041816e63d839af | https://github.com/django-auth-ldap/django-auth-ldap/blob/9ce3c2825527f8faa1793958b041816e63d839af/django_auth_ldap/config.py#L695-L703 | train | 230,679 |
regebro/hovercraft | hovercraft/position.py | gather_positions | def gather_positions(tree):
"""Makes a list of positions and position commands from the tree"""
pos = {'data-x': 'r0',
'data-y': 'r0',
'data-z': 'r0',
'data-rotate-x': 'r0',
'data-rotate-y': 'r0',
'data-rotate-z': 'r0',
'data-scale': 'r0',
'is_path': False
}
steps = 0
default_movement = True
for step in tree.findall('step'):
steps += 1
for key in POSITION_ATTRIBS:
value = step.get(key)
if value is not None:
# We have a new value
default_movement = False # No longer use the default movement
pos[key] = value
elif pos[key] and not pos[key].startswith('r'):
# The old value was absolute and no new value, so stop
pos[key] = 'r0'
# We had no new value, and the old value was a relative
# movement, so we just keep moving.
if steps == 1 and pos['data-scale'] == 'r0':
# No scale given for first slide, it needs to start at 1
pos['data-scale'] = '1'
if default_movement and steps != 1:
# No positioning has been given, use default:
pos['data-x'] = 'r%s' % DEFAULT_MOVEMENT
if 'data-rotate' in step.attrib:
# data-rotate is an alias for data-rotate-z
pos['data-rotate-z'] = step.get('data-rotate')
del step.attrib['data-rotate']
if 'hovercraft-path' in step.attrib:
# Path given x and y will be calculated from the path
default_movement = False # No longer use the default movement
pos['is_path'] = True
# Add the path spec
pos['path'] = step.attrib['hovercraft-path']
yield pos.copy()
# And get rid of it for the next step
del pos['path']
else:
if 'data-x' in step.attrib or 'data-y' in step.attrib:
# No longer using a path
pos['is_path'] = False
yield pos.copy() | python | def gather_positions(tree):
"""Makes a list of positions and position commands from the tree"""
pos = {'data-x': 'r0',
'data-y': 'r0',
'data-z': 'r0',
'data-rotate-x': 'r0',
'data-rotate-y': 'r0',
'data-rotate-z': 'r0',
'data-scale': 'r0',
'is_path': False
}
steps = 0
default_movement = True
for step in tree.findall('step'):
steps += 1
for key in POSITION_ATTRIBS:
value = step.get(key)
if value is not None:
# We have a new value
default_movement = False # No longer use the default movement
pos[key] = value
elif pos[key] and not pos[key].startswith('r'):
# The old value was absolute and no new value, so stop
pos[key] = 'r0'
# We had no new value, and the old value was a relative
# movement, so we just keep moving.
if steps == 1 and pos['data-scale'] == 'r0':
# No scale given for first slide, it needs to start at 1
pos['data-scale'] = '1'
if default_movement and steps != 1:
# No positioning has been given, use default:
pos['data-x'] = 'r%s' % DEFAULT_MOVEMENT
if 'data-rotate' in step.attrib:
# data-rotate is an alias for data-rotate-z
pos['data-rotate-z'] = step.get('data-rotate')
del step.attrib['data-rotate']
if 'hovercraft-path' in step.attrib:
# Path given x and y will be calculated from the path
default_movement = False # No longer use the default movement
pos['is_path'] = True
# Add the path spec
pos['path'] = step.attrib['hovercraft-path']
yield pos.copy()
# And get rid of it for the next step
del pos['path']
else:
if 'data-x' in step.attrib or 'data-y' in step.attrib:
# No longer using a path
pos['is_path'] = False
yield pos.copy() | [
"def",
"gather_positions",
"(",
"tree",
")",
":",
"pos",
"=",
"{",
"'data-x'",
":",
"'r0'",
",",
"'data-y'",
":",
"'r0'",
",",
"'data-z'",
":",
"'r0'",
",",
"'data-rotate-x'",
":",
"'r0'",
",",
"'data-rotate-y'",
":",
"'r0'",
",",
"'data-rotate-z'",
":",
... | Makes a list of positions and position commands from the tree | [
"Makes",
"a",
"list",
"of",
"positions",
"and",
"position",
"commands",
"from",
"the",
"tree"
] | d9f63bfdfe1519c4d7a81697ee066e49dc26a30b | https://github.com/regebro/hovercraft/blob/d9f63bfdfe1519c4d7a81697ee066e49dc26a30b/hovercraft/position.py#L10-L67 | train | 230,680 |
regebro/hovercraft | hovercraft/position.py | calculate_positions | def calculate_positions(positions):
"""Calculates position information"""
current_position = {'data-x': 0,
'data-y': 0,
'data-z': 0,
'data-rotate-x': 0,
'data-rotate-y': 0,
'data-rotate-z': 0,
'data-scale': 1,
}
positer = iter(positions)
position = next(positer)
_update_position(current_position, position)
while True:
if 'path' in position:
# Start of a new path!
path = position['path']
# Follow the path specification
first_point = _pos_to_cord(current_position)
# Paths that end in Z or z are closed.
closed_path = path.strip()[-1].upper() == 'Z'
path = parse_path(path)
# Find out how many positions should be calculated:
count = 1
last = False
deferred_positions = []
while True:
try:
position = next(positer)
deferred_positions.append(position)
except StopIteration:
last = True # This path goes to the end
break
if not position.get('is_path') or 'path' in position:
# The end of the path, or the start of a new one
break
count += 1
if count < 2:
raise AssertionError("The path specification is only used for "
"one slide, which makes it pointless.")
if closed_path:
# This path closes in on itself. Skip the last part, so that
# the first and last step doesn't overlap.
endcount = count + 1
else:
endcount = count
multiplier = (endcount * DEFAULT_MOVEMENT) / path.length()
offset = path.point(0)
path_iter = iter(deferred_positions)
for x in range(count):
point = path.point(x / (endcount - 1))
point = ((point - offset) * multiplier) + first_point
current_position.update(_coord_to_pos(point))
rotation = _path_angle(path, x / (endcount - 1))
current_position['data-rotate-z'] = rotation
yield current_position.copy()
try:
position = next(path_iter)
except StopIteration:
last = True
break
_update_position(current_position, position)
if last:
break
continue
yield current_position.copy()
try:
position = next(positer)
except StopIteration:
break
_update_position(current_position, position) | python | def calculate_positions(positions):
"""Calculates position information"""
current_position = {'data-x': 0,
'data-y': 0,
'data-z': 0,
'data-rotate-x': 0,
'data-rotate-y': 0,
'data-rotate-z': 0,
'data-scale': 1,
}
positer = iter(positions)
position = next(positer)
_update_position(current_position, position)
while True:
if 'path' in position:
# Start of a new path!
path = position['path']
# Follow the path specification
first_point = _pos_to_cord(current_position)
# Paths that end in Z or z are closed.
closed_path = path.strip()[-1].upper() == 'Z'
path = parse_path(path)
# Find out how many positions should be calculated:
count = 1
last = False
deferred_positions = []
while True:
try:
position = next(positer)
deferred_positions.append(position)
except StopIteration:
last = True # This path goes to the end
break
if not position.get('is_path') or 'path' in position:
# The end of the path, or the start of a new one
break
count += 1
if count < 2:
raise AssertionError("The path specification is only used for "
"one slide, which makes it pointless.")
if closed_path:
# This path closes in on itself. Skip the last part, so that
# the first and last step doesn't overlap.
endcount = count + 1
else:
endcount = count
multiplier = (endcount * DEFAULT_MOVEMENT) / path.length()
offset = path.point(0)
path_iter = iter(deferred_positions)
for x in range(count):
point = path.point(x / (endcount - 1))
point = ((point - offset) * multiplier) + first_point
current_position.update(_coord_to_pos(point))
rotation = _path_angle(path, x / (endcount - 1))
current_position['data-rotate-z'] = rotation
yield current_position.copy()
try:
position = next(path_iter)
except StopIteration:
last = True
break
_update_position(current_position, position)
if last:
break
continue
yield current_position.copy()
try:
position = next(positer)
except StopIteration:
break
_update_position(current_position, position) | [
"def",
"calculate_positions",
"(",
"positions",
")",
":",
"current_position",
"=",
"{",
"'data-x'",
":",
"0",
",",
"'data-y'",
":",
"0",
",",
"'data-z'",
":",
"0",
",",
"'data-rotate-x'",
":",
"0",
",",
"'data-rotate-y'",
":",
"0",
",",
"'data-rotate-z'",
... | Calculates position information | [
"Calculates",
"position",
"information"
] | d9f63bfdfe1519c4d7a81697ee066e49dc26a30b | https://github.com/regebro/hovercraft/blob/d9f63bfdfe1519c4d7a81697ee066e49dc26a30b/hovercraft/position.py#L131-L216 | train | 230,681 |
regebro/hovercraft | hovercraft/position.py | update_positions | def update_positions(tree, positions):
"""Updates the tree with new positions"""
for step, pos in zip(tree.findall('step'), positions):
for key in sorted(pos):
value = pos.get(key)
if key.endswith("-rel"):
abs_key = key[:key.index("-rel")]
if value is not None:
els = tree.findall(".//*[@id='" + value + "']")
for el in els :
pos[abs_key] = num(el.get(abs_key)) + pos.get(abs_key)
step.attrib[abs_key] = str(pos.get(abs_key))
else:
step.attrib[key] = str(pos[key])
if 'hovercraft-path' in step.attrib:
del step.attrib['hovercraft-path'] | python | def update_positions(tree, positions):
"""Updates the tree with new positions"""
for step, pos in zip(tree.findall('step'), positions):
for key in sorted(pos):
value = pos.get(key)
if key.endswith("-rel"):
abs_key = key[:key.index("-rel")]
if value is not None:
els = tree.findall(".//*[@id='" + value + "']")
for el in els :
pos[abs_key] = num(el.get(abs_key)) + pos.get(abs_key)
step.attrib[abs_key] = str(pos.get(abs_key))
else:
step.attrib[key] = str(pos[key])
if 'hovercraft-path' in step.attrib:
del step.attrib['hovercraft-path'] | [
"def",
"update_positions",
"(",
"tree",
",",
"positions",
")",
":",
"for",
"step",
",",
"pos",
"in",
"zip",
"(",
"tree",
".",
"findall",
"(",
"'step'",
")",
",",
"positions",
")",
":",
"for",
"key",
"in",
"sorted",
"(",
"pos",
")",
":",
"value",
"=... | Updates the tree with new positions | [
"Updates",
"the",
"tree",
"with",
"new",
"positions"
] | d9f63bfdfe1519c4d7a81697ee066e49dc26a30b | https://github.com/regebro/hovercraft/blob/d9f63bfdfe1519c4d7a81697ee066e49dc26a30b/hovercraft/position.py#L219-L236 | train | 230,682 |
regebro/hovercraft | hovercraft/position.py | position_slides | def position_slides(tree):
"""Position the slides in the tree"""
positions = gather_positions(tree)
positions = calculate_positions(positions)
update_positions(tree, positions) | python | def position_slides(tree):
"""Position the slides in the tree"""
positions = gather_positions(tree)
positions = calculate_positions(positions)
update_positions(tree, positions) | [
"def",
"position_slides",
"(",
"tree",
")",
":",
"positions",
"=",
"gather_positions",
"(",
"tree",
")",
"positions",
"=",
"calculate_positions",
"(",
"positions",
")",
"update_positions",
"(",
"tree",
",",
"positions",
")"
] | Position the slides in the tree | [
"Position",
"the",
"slides",
"in",
"the",
"tree"
] | d9f63bfdfe1519c4d7a81697ee066e49dc26a30b | https://github.com/regebro/hovercraft/blob/d9f63bfdfe1519c4d7a81697ee066e49dc26a30b/hovercraft/position.py#L239-L244 | train | 230,683 |
regebro/hovercraft | hovercraft/parse.py | copy_node | def copy_node(node):
"""Makes a copy of a node with the same attributes and text, but no children."""
element = node.makeelement(node.tag)
element.text = node.text
element.tail = node.tail
for key, value in node.items():
element.set(key, value)
return element | python | def copy_node(node):
"""Makes a copy of a node with the same attributes and text, but no children."""
element = node.makeelement(node.tag)
element.text = node.text
element.tail = node.tail
for key, value in node.items():
element.set(key, value)
return element | [
"def",
"copy_node",
"(",
"node",
")",
":",
"element",
"=",
"node",
".",
"makeelement",
"(",
"node",
".",
"tag",
")",
"element",
".",
"text",
"=",
"node",
".",
"text",
"element",
".",
"tail",
"=",
"node",
".",
"tail",
"for",
"key",
",",
"value",
"in... | Makes a copy of a node with the same attributes and text, but no children. | [
"Makes",
"a",
"copy",
"of",
"a",
"node",
"with",
"the",
"same",
"attributes",
"and",
"text",
"but",
"no",
"children",
"."
] | d9f63bfdfe1519c4d7a81697ee066e49dc26a30b | https://github.com/regebro/hovercraft/blob/d9f63bfdfe1519c4d7a81697ee066e49dc26a30b/hovercraft/parse.py#L84-L92 | train | 230,684 |
regebro/hovercraft | hovercraft/template.py | Template.copy_resource | def copy_resource(self, resource, targetdir):
"""Copies a resource file and returns the source path for monitoring"""
final_path = resource.final_path()
if final_path[0] == '/' or (':' in final_path) or ('?' in final_path):
# Absolute path or URI: Do nothing
return
source_path = self.get_source_path(resource)
if resource.resource_type == DIRECTORY_RESOURCE:
for file_path in glob.iglob(os.path.join(source_path, '**'), recursive=True):
if os.path.isdir(file_path):
continue
rest_target_path = file_path[len(source_path)+1:]
target_path = os.path.join(targetdir, final_path, rest_target_path)
# Don't yield the result, we don't monitor these.
self._copy_file(file_path, target_path)
else:
target_path = os.path.join(targetdir, final_path)
yield self._copy_file(source_path, target_path) | python | def copy_resource(self, resource, targetdir):
"""Copies a resource file and returns the source path for monitoring"""
final_path = resource.final_path()
if final_path[0] == '/' or (':' in final_path) or ('?' in final_path):
# Absolute path or URI: Do nothing
return
source_path = self.get_source_path(resource)
if resource.resource_type == DIRECTORY_RESOURCE:
for file_path in glob.iglob(os.path.join(source_path, '**'), recursive=True):
if os.path.isdir(file_path):
continue
rest_target_path = file_path[len(source_path)+1:]
target_path = os.path.join(targetdir, final_path, rest_target_path)
# Don't yield the result, we don't monitor these.
self._copy_file(file_path, target_path)
else:
target_path = os.path.join(targetdir, final_path)
yield self._copy_file(source_path, target_path) | [
"def",
"copy_resource",
"(",
"self",
",",
"resource",
",",
"targetdir",
")",
":",
"final_path",
"=",
"resource",
".",
"final_path",
"(",
")",
"if",
"final_path",
"[",
"0",
"]",
"==",
"'/'",
"or",
"(",
"':'",
"in",
"final_path",
")",
"or",
"(",
"'?'",
... | Copies a resource file and returns the source path for monitoring | [
"Copies",
"a",
"resource",
"file",
"and",
"returns",
"the",
"source",
"path",
"for",
"monitoring"
] | d9f63bfdfe1519c4d7a81697ee066e49dc26a30b | https://github.com/regebro/hovercraft/blob/d9f63bfdfe1519c4d7a81697ee066e49dc26a30b/hovercraft/template.py#L143-L162 | train | 230,685 |
regebro/hovercraft | hovercraft/generate.py | generate | def generate(args):
"""Generates the presentation and returns a list of files used"""
source_files = {args.presentation}
# Parse the template info
template_info = Template(args.template)
if args.css:
presentation_dir = os.path.split(args.presentation)[0]
target_path = os.path.relpath(args.css, presentation_dir)
template_info.add_resource(args.css, CSS_RESOURCE, target=target_path, extra_info='all')
source_files.add(args.css)
if args.js:
presentation_dir = os.path.split(args.presentation)[0]
target_path = os.path.relpath(args.js, presentation_dir)
template_info.add_resource(args.js, JS_RESOURCE, target=target_path, extra_info=JS_POSITION_BODY)
source_files.add(args.js)
# Make the resulting HTML
htmldata, dependencies = rst2html(args.presentation, template_info,
args.auto_console, args.skip_help,
args.skip_notes, args.mathjax,
args.slide_numbers)
source_files.update(dependencies)
# Write the HTML out
if not os.path.exists(args.targetdir):
os.makedirs(args.targetdir)
with open(os.path.join(args.targetdir, 'index.html'), 'wb') as outfile:
outfile.write(htmldata)
# Copy supporting files
source_files.update(template_info.copy_resources(args.targetdir))
# Copy images from the source:
sourcedir = os.path.split(os.path.abspath(args.presentation))[0]
tree = html.fromstring(htmldata)
for image in tree.iterdescendants('img'):
filename = image.attrib['src']
source_files.add(copy_resource(filename, sourcedir, args.targetdir))
RE_CSS_URL = re.compile(br"""url\(['"]?(.*?)['"]?[\)\?\#]""")
# Copy any files referenced by url() in the css-files:
for resource in template_info.resources:
if resource.resource_type != CSS_RESOURCE:
continue
# path in CSS is relative to CSS file; construct source/dest accordingly
css_base = template_info.template_root if resource.is_in_template else sourcedir
css_sourcedir = os.path.dirname(os.path.join(css_base, resource.filepath))
css_targetdir = os.path.dirname(os.path.join(args.targetdir, resource.final_path()))
uris = RE_CSS_URL.findall(template_info.read_data(resource))
uris = [uri.decode() for uri in uris]
if resource.is_in_template and template_info.builtin_template:
for filename in uris:
template_info.add_resource(filename, OTHER_RESOURCE, target=css_targetdir,
is_in_template=True)
else:
for filename in uris:
source_files.add(copy_resource(filename, css_sourcedir, css_targetdir))
# All done!
return {os.path.abspath(f) for f in source_files if f} | python | def generate(args):
"""Generates the presentation and returns a list of files used"""
source_files = {args.presentation}
# Parse the template info
template_info = Template(args.template)
if args.css:
presentation_dir = os.path.split(args.presentation)[0]
target_path = os.path.relpath(args.css, presentation_dir)
template_info.add_resource(args.css, CSS_RESOURCE, target=target_path, extra_info='all')
source_files.add(args.css)
if args.js:
presentation_dir = os.path.split(args.presentation)[0]
target_path = os.path.relpath(args.js, presentation_dir)
template_info.add_resource(args.js, JS_RESOURCE, target=target_path, extra_info=JS_POSITION_BODY)
source_files.add(args.js)
# Make the resulting HTML
htmldata, dependencies = rst2html(args.presentation, template_info,
args.auto_console, args.skip_help,
args.skip_notes, args.mathjax,
args.slide_numbers)
source_files.update(dependencies)
# Write the HTML out
if not os.path.exists(args.targetdir):
os.makedirs(args.targetdir)
with open(os.path.join(args.targetdir, 'index.html'), 'wb') as outfile:
outfile.write(htmldata)
# Copy supporting files
source_files.update(template_info.copy_resources(args.targetdir))
# Copy images from the source:
sourcedir = os.path.split(os.path.abspath(args.presentation))[0]
tree = html.fromstring(htmldata)
for image in tree.iterdescendants('img'):
filename = image.attrib['src']
source_files.add(copy_resource(filename, sourcedir, args.targetdir))
RE_CSS_URL = re.compile(br"""url\(['"]?(.*?)['"]?[\)\?\#]""")
# Copy any files referenced by url() in the css-files:
for resource in template_info.resources:
if resource.resource_type != CSS_RESOURCE:
continue
# path in CSS is relative to CSS file; construct source/dest accordingly
css_base = template_info.template_root if resource.is_in_template else sourcedir
css_sourcedir = os.path.dirname(os.path.join(css_base, resource.filepath))
css_targetdir = os.path.dirname(os.path.join(args.targetdir, resource.final_path()))
uris = RE_CSS_URL.findall(template_info.read_data(resource))
uris = [uri.decode() for uri in uris]
if resource.is_in_template and template_info.builtin_template:
for filename in uris:
template_info.add_resource(filename, OTHER_RESOURCE, target=css_targetdir,
is_in_template=True)
else:
for filename in uris:
source_files.add(copy_resource(filename, css_sourcedir, css_targetdir))
# All done!
return {os.path.abspath(f) for f in source_files if f} | [
"def",
"generate",
"(",
"args",
")",
":",
"source_files",
"=",
"{",
"args",
".",
"presentation",
"}",
"# Parse the template info",
"template_info",
"=",
"Template",
"(",
"args",
".",
"template",
")",
"if",
"args",
".",
"css",
":",
"presentation_dir",
"=",
"o... | Generates the presentation and returns a list of files used | [
"Generates",
"the",
"presentation",
"and",
"returns",
"a",
"list",
"of",
"files",
"used"
] | d9f63bfdfe1519c4d7a81697ee066e49dc26a30b | https://github.com/regebro/hovercraft/blob/d9f63bfdfe1519c4d7a81697ee066e49dc26a30b/hovercraft/generate.py#L144-L207 | train | 230,686 |
sourceperl/pyModbusTCP | pyModbusTCP/client.py | ModbusClient.port | def port(self, port=None):
"""Get or set TCP port
:param port: TCP port number or None for get value
:type port: int or None
:returns: TCP port or None if set fail
:rtype: int or None
"""
if (port is None) or (port == self.__port):
return self.__port
# when port change ensure old socket is close
self.close()
# valid port ?
if 0 < int(port) < 65536:
self.__port = int(port)
return self.__port
else:
return None | python | def port(self, port=None):
"""Get or set TCP port
:param port: TCP port number or None for get value
:type port: int or None
:returns: TCP port or None if set fail
:rtype: int or None
"""
if (port is None) or (port == self.__port):
return self.__port
# when port change ensure old socket is close
self.close()
# valid port ?
if 0 < int(port) < 65536:
self.__port = int(port)
return self.__port
else:
return None | [
"def",
"port",
"(",
"self",
",",
"port",
"=",
"None",
")",
":",
"if",
"(",
"port",
"is",
"None",
")",
"or",
"(",
"port",
"==",
"self",
".",
"__port",
")",
":",
"return",
"self",
".",
"__port",
"# when port change ensure old socket is close",
"self",
".",... | Get or set TCP port
:param port: TCP port number or None for get value
:type port: int or None
:returns: TCP port or None if set fail
:rtype: int or None | [
"Get",
"or",
"set",
"TCP",
"port"
] | 993f6e2f5ab52eba164be049e42cea560c3751a5 | https://github.com/sourceperl/pyModbusTCP/blob/993f6e2f5ab52eba164be049e42cea560c3751a5/pyModbusTCP/client.py#L145-L162 | train | 230,687 |
sourceperl/pyModbusTCP | pyModbusTCP/client.py | ModbusClient.unit_id | def unit_id(self, unit_id=None):
"""Get or set unit ID field
:param unit_id: unit ID (0 to 255) or None for get value
:type unit_id: int or None
:returns: unit ID or None if set fail
:rtype: int or None
"""
if unit_id is None:
return self.__unit_id
if 0 <= int(unit_id) < 256:
self.__unit_id = int(unit_id)
return self.__unit_id
else:
return None | python | def unit_id(self, unit_id=None):
"""Get or set unit ID field
:param unit_id: unit ID (0 to 255) or None for get value
:type unit_id: int or None
:returns: unit ID or None if set fail
:rtype: int or None
"""
if unit_id is None:
return self.__unit_id
if 0 <= int(unit_id) < 256:
self.__unit_id = int(unit_id)
return self.__unit_id
else:
return None | [
"def",
"unit_id",
"(",
"self",
",",
"unit_id",
"=",
"None",
")",
":",
"if",
"unit_id",
"is",
"None",
":",
"return",
"self",
".",
"__unit_id",
"if",
"0",
"<=",
"int",
"(",
"unit_id",
")",
"<",
"256",
":",
"self",
".",
"__unit_id",
"=",
"int",
"(",
... | Get or set unit ID field
:param unit_id: unit ID (0 to 255) or None for get value
:type unit_id: int or None
:returns: unit ID or None if set fail
:rtype: int or None | [
"Get",
"or",
"set",
"unit",
"ID",
"field"
] | 993f6e2f5ab52eba164be049e42cea560c3751a5 | https://github.com/sourceperl/pyModbusTCP/blob/993f6e2f5ab52eba164be049e42cea560c3751a5/pyModbusTCP/client.py#L164-L178 | train | 230,688 |
sourceperl/pyModbusTCP | pyModbusTCP/client.py | ModbusClient.timeout | def timeout(self, timeout=None):
"""Get or set timeout field
:param timeout: socket timeout in seconds or None for get value
:type timeout: float or None
:returns: timeout or None if set fail
:rtype: float or None
"""
if timeout is None:
return self.__timeout
if 0 < float(timeout) < 3600:
self.__timeout = float(timeout)
return self.__timeout
else:
return None | python | def timeout(self, timeout=None):
"""Get or set timeout field
:param timeout: socket timeout in seconds or None for get value
:type timeout: float or None
:returns: timeout or None if set fail
:rtype: float or None
"""
if timeout is None:
return self.__timeout
if 0 < float(timeout) < 3600:
self.__timeout = float(timeout)
return self.__timeout
else:
return None | [
"def",
"timeout",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"timeout",
"is",
"None",
":",
"return",
"self",
".",
"__timeout",
"if",
"0",
"<",
"float",
"(",
"timeout",
")",
"<",
"3600",
":",
"self",
".",
"__timeout",
"=",
"float",
"(... | Get or set timeout field
:param timeout: socket timeout in seconds or None for get value
:type timeout: float or None
:returns: timeout or None if set fail
:rtype: float or None | [
"Get",
"or",
"set",
"timeout",
"field"
] | 993f6e2f5ab52eba164be049e42cea560c3751a5 | https://github.com/sourceperl/pyModbusTCP/blob/993f6e2f5ab52eba164be049e42cea560c3751a5/pyModbusTCP/client.py#L180-L194 | train | 230,689 |
sourceperl/pyModbusTCP | pyModbusTCP/client.py | ModbusClient.debug | def debug(self, state=None):
"""Get or set debug mode
:param state: debug state or None for get value
:type state: bool or None
:returns: debug state or None if set fail
:rtype: bool or None
"""
if state is None:
return self.__debug
self.__debug = bool(state)
return self.__debug | python | def debug(self, state=None):
"""Get or set debug mode
:param state: debug state or None for get value
:type state: bool or None
:returns: debug state or None if set fail
:rtype: bool or None
"""
if state is None:
return self.__debug
self.__debug = bool(state)
return self.__debug | [
"def",
"debug",
"(",
"self",
",",
"state",
"=",
"None",
")",
":",
"if",
"state",
"is",
"None",
":",
"return",
"self",
".",
"__debug",
"self",
".",
"__debug",
"=",
"bool",
"(",
"state",
")",
"return",
"self",
".",
"__debug"
] | Get or set debug mode
:param state: debug state or None for get value
:type state: bool or None
:returns: debug state or None if set fail
:rtype: bool or None | [
"Get",
"or",
"set",
"debug",
"mode"
] | 993f6e2f5ab52eba164be049e42cea560c3751a5 | https://github.com/sourceperl/pyModbusTCP/blob/993f6e2f5ab52eba164be049e42cea560c3751a5/pyModbusTCP/client.py#L196-L207 | train | 230,690 |
sourceperl/pyModbusTCP | pyModbusTCP/client.py | ModbusClient.auto_open | def auto_open(self, state=None):
"""Get or set automatic TCP connect mode
:param state: auto_open state or None for get value
:type state: bool or None
:returns: auto_open state or None if set fail
:rtype: bool or None
"""
if state is None:
return self.__auto_open
self.__auto_open = bool(state)
return self.__auto_open | python | def auto_open(self, state=None):
"""Get or set automatic TCP connect mode
:param state: auto_open state or None for get value
:type state: bool or None
:returns: auto_open state or None if set fail
:rtype: bool or None
"""
if state is None:
return self.__auto_open
self.__auto_open = bool(state)
return self.__auto_open | [
"def",
"auto_open",
"(",
"self",
",",
"state",
"=",
"None",
")",
":",
"if",
"state",
"is",
"None",
":",
"return",
"self",
".",
"__auto_open",
"self",
".",
"__auto_open",
"=",
"bool",
"(",
"state",
")",
"return",
"self",
".",
"__auto_open"
] | Get or set automatic TCP connect mode
:param state: auto_open state or None for get value
:type state: bool or None
:returns: auto_open state or None if set fail
:rtype: bool or None | [
"Get",
"or",
"set",
"automatic",
"TCP",
"connect",
"mode"
] | 993f6e2f5ab52eba164be049e42cea560c3751a5 | https://github.com/sourceperl/pyModbusTCP/blob/993f6e2f5ab52eba164be049e42cea560c3751a5/pyModbusTCP/client.py#L209-L220 | train | 230,691 |
sourceperl/pyModbusTCP | pyModbusTCP/client.py | ModbusClient._can_read | def _can_read(self):
"""Wait data available for socket read
:returns: True if data available or None if timeout or socket error
:rtype: bool or None
"""
if self.__sock is None:
return None
if select.select([self.__sock], [], [], self.__timeout)[0]:
return True
else:
self.__last_error = const.MB_TIMEOUT_ERR
self.__debug_msg('timeout error')
self.close()
return None | python | def _can_read(self):
"""Wait data available for socket read
:returns: True if data available or None if timeout or socket error
:rtype: bool or None
"""
if self.__sock is None:
return None
if select.select([self.__sock], [], [], self.__timeout)[0]:
return True
else:
self.__last_error = const.MB_TIMEOUT_ERR
self.__debug_msg('timeout error')
self.close()
return None | [
"def",
"_can_read",
"(",
"self",
")",
":",
"if",
"self",
".",
"__sock",
"is",
"None",
":",
"return",
"None",
"if",
"select",
".",
"select",
"(",
"[",
"self",
".",
"__sock",
"]",
",",
"[",
"]",
",",
"[",
"]",
",",
"self",
".",
"__timeout",
")",
... | Wait data available for socket read
:returns: True if data available or None if timeout or socket error
:rtype: bool or None | [
"Wait",
"data",
"available",
"for",
"socket",
"read"
] | 993f6e2f5ab52eba164be049e42cea560c3751a5 | https://github.com/sourceperl/pyModbusTCP/blob/993f6e2f5ab52eba164be049e42cea560c3751a5/pyModbusTCP/client.py#L740-L754 | train | 230,692 |
sourceperl/pyModbusTCP | pyModbusTCP/client.py | ModbusClient._send | def _send(self, data):
"""Send data over current socket
:param data: registers value to write
:type data: str (Python2) or class bytes (Python3)
:returns: True if send ok or None if error
:rtype: bool or None
"""
# check link
if self.__sock is None:
self.__debug_msg('call _send on close socket')
return None
# send
data_l = len(data)
try:
send_l = self.__sock.send(data)
except socket.error:
send_l = None
# handle send error
if (send_l is None) or (send_l != data_l):
self.__last_error = const.MB_SEND_ERR
self.__debug_msg('_send error')
self.close()
return None
else:
return send_l | python | def _send(self, data):
"""Send data over current socket
:param data: registers value to write
:type data: str (Python2) or class bytes (Python3)
:returns: True if send ok or None if error
:rtype: bool or None
"""
# check link
if self.__sock is None:
self.__debug_msg('call _send on close socket')
return None
# send
data_l = len(data)
try:
send_l = self.__sock.send(data)
except socket.error:
send_l = None
# handle send error
if (send_l is None) or (send_l != data_l):
self.__last_error = const.MB_SEND_ERR
self.__debug_msg('_send error')
self.close()
return None
else:
return send_l | [
"def",
"_send",
"(",
"self",
",",
"data",
")",
":",
"# check link",
"if",
"self",
".",
"__sock",
"is",
"None",
":",
"self",
".",
"__debug_msg",
"(",
"'call _send on close socket'",
")",
"return",
"None",
"# send",
"data_l",
"=",
"len",
"(",
"data",
")",
... | Send data over current socket
:param data: registers value to write
:type data: str (Python2) or class bytes (Python3)
:returns: True if send ok or None if error
:rtype: bool or None | [
"Send",
"data",
"over",
"current",
"socket"
] | 993f6e2f5ab52eba164be049e42cea560c3751a5 | https://github.com/sourceperl/pyModbusTCP/blob/993f6e2f5ab52eba164be049e42cea560c3751a5/pyModbusTCP/client.py#L756-L781 | train | 230,693 |
sourceperl/pyModbusTCP | pyModbusTCP/client.py | ModbusClient._recv | def _recv(self, max_size):
"""Receive data over current socket
:param max_size: number of bytes to receive
:type max_size: int
:returns: receive data or None if error
:rtype: str (Python2) or class bytes (Python3) or None
"""
# wait for read
if not self._can_read():
self.close()
return None
# recv
try:
r_buffer = self.__sock.recv(max_size)
except socket.error:
r_buffer = None
# handle recv error
if not r_buffer:
self.__last_error = const.MB_RECV_ERR
self.__debug_msg('_recv error')
self.close()
return None
return r_buffer | python | def _recv(self, max_size):
"""Receive data over current socket
:param max_size: number of bytes to receive
:type max_size: int
:returns: receive data or None if error
:rtype: str (Python2) or class bytes (Python3) or None
"""
# wait for read
if not self._can_read():
self.close()
return None
# recv
try:
r_buffer = self.__sock.recv(max_size)
except socket.error:
r_buffer = None
# handle recv error
if not r_buffer:
self.__last_error = const.MB_RECV_ERR
self.__debug_msg('_recv error')
self.close()
return None
return r_buffer | [
"def",
"_recv",
"(",
"self",
",",
"max_size",
")",
":",
"# wait for read",
"if",
"not",
"self",
".",
"_can_read",
"(",
")",
":",
"self",
".",
"close",
"(",
")",
"return",
"None",
"# recv",
"try",
":",
"r_buffer",
"=",
"self",
".",
"__sock",
".",
"rec... | Receive data over current socket
:param max_size: number of bytes to receive
:type max_size: int
:returns: receive data or None if error
:rtype: str (Python2) or class bytes (Python3) or None | [
"Receive",
"data",
"over",
"current",
"socket"
] | 993f6e2f5ab52eba164be049e42cea560c3751a5 | https://github.com/sourceperl/pyModbusTCP/blob/993f6e2f5ab52eba164be049e42cea560c3751a5/pyModbusTCP/client.py#L783-L806 | train | 230,694 |
sourceperl/pyModbusTCP | pyModbusTCP/client.py | ModbusClient._send_mbus | def _send_mbus(self, frame):
"""Send modbus frame
:param frame: modbus frame to send (with MBAP for TCP/CRC for RTU)
:type frame: str (Python2) or class bytes (Python3)
:returns: number of bytes send or None if error
:rtype: int or None
"""
# for auto_open mode, check TCP and open if need
if self.__auto_open and not self.is_open():
self.open()
# send request
bytes_send = self._send(frame)
if bytes_send:
if self.__debug:
self._pretty_dump('Tx', frame)
return bytes_send
else:
return None | python | def _send_mbus(self, frame):
"""Send modbus frame
:param frame: modbus frame to send (with MBAP for TCP/CRC for RTU)
:type frame: str (Python2) or class bytes (Python3)
:returns: number of bytes send or None if error
:rtype: int or None
"""
# for auto_open mode, check TCP and open if need
if self.__auto_open and not self.is_open():
self.open()
# send request
bytes_send = self._send(frame)
if bytes_send:
if self.__debug:
self._pretty_dump('Tx', frame)
return bytes_send
else:
return None | [
"def",
"_send_mbus",
"(",
"self",
",",
"frame",
")",
":",
"# for auto_open mode, check TCP and open if need",
"if",
"self",
".",
"__auto_open",
"and",
"not",
"self",
".",
"is_open",
"(",
")",
":",
"self",
".",
"open",
"(",
")",
"# send request",
"bytes_send",
... | Send modbus frame
:param frame: modbus frame to send (with MBAP for TCP/CRC for RTU)
:type frame: str (Python2) or class bytes (Python3)
:returns: number of bytes send or None if error
:rtype: int or None | [
"Send",
"modbus",
"frame"
] | 993f6e2f5ab52eba164be049e42cea560c3751a5 | https://github.com/sourceperl/pyModbusTCP/blob/993f6e2f5ab52eba164be049e42cea560c3751a5/pyModbusTCP/client.py#L824-L842 | train | 230,695 |
sourceperl/pyModbusTCP | pyModbusTCP/client.py | ModbusClient._recv_mbus | def _recv_mbus(self):
"""Receive a modbus frame
:returns: modbus frame body or None if error
:rtype: str (Python2) or class bytes (Python3) or None
"""
# receive
# modbus TCP receive
if self.__mode == const.MODBUS_TCP:
# 7 bytes header (mbap)
rx_buffer = self._recv_all(7)
# check recv
if not (rx_buffer and len(rx_buffer) == 7):
self.__last_error = const.MB_RECV_ERR
self.__debug_msg('_recv MBAP error')
self.close()
return None
rx_frame = rx_buffer
# decode header
(rx_hd_tr_id, rx_hd_pr_id,
rx_hd_length, rx_hd_unit_id) = struct.unpack('>HHHB', rx_frame)
# check header
if not ((rx_hd_tr_id == self.__hd_tr_id) and
(rx_hd_pr_id == 0) and
(rx_hd_length < 256) and
(rx_hd_unit_id == self.__unit_id)):
self.__last_error = const.MB_RECV_ERR
self.__debug_msg('MBAP format error')
if self.__debug:
rx_frame += self._recv_all(rx_hd_length - 1)
self._pretty_dump('Rx', rx_frame)
self.close()
return None
# end of frame
rx_buffer = self._recv_all(rx_hd_length - 1)
if not (rx_buffer and
(len(rx_buffer) == rx_hd_length - 1) and
(len(rx_buffer) >= 2)):
self.__last_error = const.MB_RECV_ERR
self.__debug_msg('_recv frame body error')
self.close()
return None
rx_frame += rx_buffer
# dump frame
if self.__debug:
self._pretty_dump('Rx', rx_frame)
# body decode
rx_bd_fc = struct.unpack('B', rx_buffer[0:1])[0]
f_body = rx_buffer[1:]
# modbus RTU receive
elif self.__mode == const.MODBUS_RTU:
# receive modbus RTU frame (max size is 256 bytes)
rx_buffer = self._recv(256)
# on _recv error
if not rx_buffer:
return None
rx_frame = rx_buffer
# dump frame
if self.__debug:
self._pretty_dump('Rx', rx_frame)
# RTU frame min size is 5 bytes
if len(rx_buffer) < 5:
self.__last_error = const.MB_RECV_ERR
self.__debug_msg('short frame error')
self.close()
return None
# check CRC
if not self._crc_is_ok(rx_frame):
self.__last_error = const.MB_CRC_ERR
self.__debug_msg('CRC error')
self.close()
return None
# body decode
(rx_unit_id, rx_bd_fc) = struct.unpack("BB", rx_frame[:2])
# check
if not (rx_unit_id == self.__unit_id):
self.__last_error = const.MB_RECV_ERR
self.__debug_msg('unit ID mismatch error')
self.close()
return None
# format f_body: remove unit ID, function code and CRC 2 last bytes
f_body = rx_frame[2:-2]
# for auto_close mode, close socket after each request
if self.__auto_close:
self.close()
# check except
if rx_bd_fc > 0x80:
# except code
exp_code = struct.unpack('B', f_body[0:1])[0]
self.__last_error = const.MB_EXCEPT_ERR
self.__last_except = exp_code
self.__debug_msg('except (code ' + str(exp_code) + ')')
return None
else:
# return
return f_body | python | def _recv_mbus(self):
"""Receive a modbus frame
:returns: modbus frame body or None if error
:rtype: str (Python2) or class bytes (Python3) or None
"""
# receive
# modbus TCP receive
if self.__mode == const.MODBUS_TCP:
# 7 bytes header (mbap)
rx_buffer = self._recv_all(7)
# check recv
if not (rx_buffer and len(rx_buffer) == 7):
self.__last_error = const.MB_RECV_ERR
self.__debug_msg('_recv MBAP error')
self.close()
return None
rx_frame = rx_buffer
# decode header
(rx_hd_tr_id, rx_hd_pr_id,
rx_hd_length, rx_hd_unit_id) = struct.unpack('>HHHB', rx_frame)
# check header
if not ((rx_hd_tr_id == self.__hd_tr_id) and
(rx_hd_pr_id == 0) and
(rx_hd_length < 256) and
(rx_hd_unit_id == self.__unit_id)):
self.__last_error = const.MB_RECV_ERR
self.__debug_msg('MBAP format error')
if self.__debug:
rx_frame += self._recv_all(rx_hd_length - 1)
self._pretty_dump('Rx', rx_frame)
self.close()
return None
# end of frame
rx_buffer = self._recv_all(rx_hd_length - 1)
if not (rx_buffer and
(len(rx_buffer) == rx_hd_length - 1) and
(len(rx_buffer) >= 2)):
self.__last_error = const.MB_RECV_ERR
self.__debug_msg('_recv frame body error')
self.close()
return None
rx_frame += rx_buffer
# dump frame
if self.__debug:
self._pretty_dump('Rx', rx_frame)
# body decode
rx_bd_fc = struct.unpack('B', rx_buffer[0:1])[0]
f_body = rx_buffer[1:]
# modbus RTU receive
elif self.__mode == const.MODBUS_RTU:
# receive modbus RTU frame (max size is 256 bytes)
rx_buffer = self._recv(256)
# on _recv error
if not rx_buffer:
return None
rx_frame = rx_buffer
# dump frame
if self.__debug:
self._pretty_dump('Rx', rx_frame)
# RTU frame min size is 5 bytes
if len(rx_buffer) < 5:
self.__last_error = const.MB_RECV_ERR
self.__debug_msg('short frame error')
self.close()
return None
# check CRC
if not self._crc_is_ok(rx_frame):
self.__last_error = const.MB_CRC_ERR
self.__debug_msg('CRC error')
self.close()
return None
# body decode
(rx_unit_id, rx_bd_fc) = struct.unpack("BB", rx_frame[:2])
# check
if not (rx_unit_id == self.__unit_id):
self.__last_error = const.MB_RECV_ERR
self.__debug_msg('unit ID mismatch error')
self.close()
return None
# format f_body: remove unit ID, function code and CRC 2 last bytes
f_body = rx_frame[2:-2]
# for auto_close mode, close socket after each request
if self.__auto_close:
self.close()
# check except
if rx_bd_fc > 0x80:
# except code
exp_code = struct.unpack('B', f_body[0:1])[0]
self.__last_error = const.MB_EXCEPT_ERR
self.__last_except = exp_code
self.__debug_msg('except (code ' + str(exp_code) + ')')
return None
else:
# return
return f_body | [
"def",
"_recv_mbus",
"(",
"self",
")",
":",
"# receive",
"# modbus TCP receive",
"if",
"self",
".",
"__mode",
"==",
"const",
".",
"MODBUS_TCP",
":",
"# 7 bytes header (mbap)",
"rx_buffer",
"=",
"self",
".",
"_recv_all",
"(",
"7",
")",
"# check recv",
"if",
"no... | Receive a modbus frame
:returns: modbus frame body or None if error
:rtype: str (Python2) or class bytes (Python3) or None | [
"Receive",
"a",
"modbus",
"frame"
] | 993f6e2f5ab52eba164be049e42cea560c3751a5 | https://github.com/sourceperl/pyModbusTCP/blob/993f6e2f5ab52eba164be049e42cea560c3751a5/pyModbusTCP/client.py#L844-L939 | train | 230,696 |
ihabunek/toot | toot/wcstring.py | _wc_hard_wrap | def _wc_hard_wrap(line, length):
"""
Wrap text to length characters, breaking when target length is reached,
taking into account character width.
Used to wrap lines which cannot be wrapped on whitespace.
"""
chars = []
chars_len = 0
for char in line:
char_len = wcwidth(char)
if chars_len + char_len > length:
yield "".join(chars)
chars = []
chars_len = 0
chars.append(char)
chars_len += char_len
if chars:
yield "".join(chars) | python | def _wc_hard_wrap(line, length):
"""
Wrap text to length characters, breaking when target length is reached,
taking into account character width.
Used to wrap lines which cannot be wrapped on whitespace.
"""
chars = []
chars_len = 0
for char in line:
char_len = wcwidth(char)
if chars_len + char_len > length:
yield "".join(chars)
chars = []
chars_len = 0
chars.append(char)
chars_len += char_len
if chars:
yield "".join(chars) | [
"def",
"_wc_hard_wrap",
"(",
"line",
",",
"length",
")",
":",
"chars",
"=",
"[",
"]",
"chars_len",
"=",
"0",
"for",
"char",
"in",
"line",
":",
"char_len",
"=",
"wcwidth",
"(",
"char",
")",
"if",
"chars_len",
"+",
"char_len",
">",
"length",
":",
"yiel... | Wrap text to length characters, breaking when target length is reached,
taking into account character width.
Used to wrap lines which cannot be wrapped on whitespace. | [
"Wrap",
"text",
"to",
"length",
"characters",
"breaking",
"when",
"target",
"length",
"is",
"reached",
"taking",
"into",
"account",
"character",
"width",
"."
] | d13fa8685b300f96621fa325774913ec0f413a7f | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/wcstring.py#L10-L30 | train | 230,697 |
ihabunek/toot | toot/wcstring.py | wc_wrap | def wc_wrap(text, length):
"""
Wrap text to given length, breaking on whitespace and taking into account
character width.
Meant for use on a single line or paragraph. Will destroy spacing between
words and paragraphs and any indentation.
"""
line_words = []
line_len = 0
words = re.split(r"\s+", text.strip())
for word in words:
word_len = wcswidth(word)
if line_words and line_len + word_len > length:
line = " ".join(line_words)
if line_len <= length:
yield line
else:
yield from _wc_hard_wrap(line, length)
line_words = []
line_len = 0
line_words.append(word)
line_len += word_len + 1 # add 1 to account for space between words
if line_words:
line = " ".join(line_words)
if line_len <= length:
yield line
else:
yield from _wc_hard_wrap(line, length) | python | def wc_wrap(text, length):
"""
Wrap text to given length, breaking on whitespace and taking into account
character width.
Meant for use on a single line or paragraph. Will destroy spacing between
words and paragraphs and any indentation.
"""
line_words = []
line_len = 0
words = re.split(r"\s+", text.strip())
for word in words:
word_len = wcswidth(word)
if line_words and line_len + word_len > length:
line = " ".join(line_words)
if line_len <= length:
yield line
else:
yield from _wc_hard_wrap(line, length)
line_words = []
line_len = 0
line_words.append(word)
line_len += word_len + 1 # add 1 to account for space between words
if line_words:
line = " ".join(line_words)
if line_len <= length:
yield line
else:
yield from _wc_hard_wrap(line, length) | [
"def",
"wc_wrap",
"(",
"text",
",",
"length",
")",
":",
"line_words",
"=",
"[",
"]",
"line_len",
"=",
"0",
"words",
"=",
"re",
".",
"split",
"(",
"r\"\\s+\"",
",",
"text",
".",
"strip",
"(",
")",
")",
"for",
"word",
"in",
"words",
":",
"word_len",
... | Wrap text to given length, breaking on whitespace and taking into account
character width.
Meant for use on a single line or paragraph. Will destroy spacing between
words and paragraphs and any indentation. | [
"Wrap",
"text",
"to",
"given",
"length",
"breaking",
"on",
"whitespace",
"and",
"taking",
"into",
"account",
"character",
"width",
"."
] | d13fa8685b300f96621fa325774913ec0f413a7f | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/wcstring.py#L33-L66 | train | 230,698 |
ihabunek/toot | toot/wcstring.py | trunc | def trunc(text, length):
"""
Truncates text to given length, taking into account wide characters.
If truncated, the last char is replaced by an elipsis.
"""
if length < 1:
raise ValueError("length should be 1 or larger")
# Remove whitespace first so no unneccesary truncation is done.
text = text.strip()
text_length = wcswidth(text)
if text_length <= length:
return text
# We cannot just remove n characters from the end since we don't know how
# wide these characters are and how it will affect text length.
# Use wcwidth to determine how many characters need to be truncated.
chars_to_truncate = 0
trunc_length = 0
for char in reversed(text):
chars_to_truncate += 1
trunc_length += wcwidth(char)
if text_length - trunc_length <= length:
break
# Additional char to make room for elipsis
n = chars_to_truncate + 1
return text[:-n].strip() + '…' | python | def trunc(text, length):
"""
Truncates text to given length, taking into account wide characters.
If truncated, the last char is replaced by an elipsis.
"""
if length < 1:
raise ValueError("length should be 1 or larger")
# Remove whitespace first so no unneccesary truncation is done.
text = text.strip()
text_length = wcswidth(text)
if text_length <= length:
return text
# We cannot just remove n characters from the end since we don't know how
# wide these characters are and how it will affect text length.
# Use wcwidth to determine how many characters need to be truncated.
chars_to_truncate = 0
trunc_length = 0
for char in reversed(text):
chars_to_truncate += 1
trunc_length += wcwidth(char)
if text_length - trunc_length <= length:
break
# Additional char to make room for elipsis
n = chars_to_truncate + 1
return text[:-n].strip() + '…' | [
"def",
"trunc",
"(",
"text",
",",
"length",
")",
":",
"if",
"length",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"\"length should be 1 or larger\"",
")",
"# Remove whitespace first so no unneccesary truncation is done.",
"text",
"=",
"text",
".",
"strip",
"(",
")",
... | Truncates text to given length, taking into account wide characters.
If truncated, the last char is replaced by an elipsis. | [
"Truncates",
"text",
"to",
"given",
"length",
"taking",
"into",
"account",
"wide",
"characters",
"."
] | d13fa8685b300f96621fa325774913ec0f413a7f | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/wcstring.py#L69-L98 | train | 230,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.