id
int32 0
252k
| 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 51
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
|
---|---|---|---|---|---|---|---|---|---|---|---|
249,600 | 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 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"
] | 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 |
249,601 | 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",
"(",
"self",
".",
"settings",
".",
"target_system",
",",
"self",
".",
"settings",
".",
"target_component",
")",
"return",
"self",
".",
"rallyloader_by_sysid",
"[",
"self",
".",
"target_system",
"]"
] | 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 |
249,602 | 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",
".",
"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"
] | 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 |
249,603 | 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):
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",
")",
")",
"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",
")",
")"
] | 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 |
249,604 | 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):
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",
".",
"height",
")",
",",
"agg",
".",
"buffer_rgba",
"(",
")",
")",
"else",
":",
"# agg => rgba buffer -> bitmap => clipped bitmap",
"return",
"_WX28_clipped_agg_as_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. | [
"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 |
249,605 | 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):
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",
".",
"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"
] | 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 |
249,606 | 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):
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",
".",
"get_renderer",
"(",
")",
",",
"None",
")",
"self",
".",
"_isDrawn",
"=",
"True",
"self",
".",
"gui_repaint",
"(",
"drawDC",
"=",
"drawDC",
")"
] | 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 |
249,607 | 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):
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",
"(",
")",
"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",
"(",
")"
] | 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 |
249,608 | 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\"",
"%",
"str",
"(",
"self",
".",
"gcs_location",
")",
")",
"return",
"self",
".",
"gcs_location",
"=",
"(",
"float",
"(",
"args",
"[",
"0",
"]",
")",
",",
"float",
"(",
"args",
"[",
"1",
"]",
")",
")"
] | set gcs location | [
"set",
"gcs",
"location"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_antenna.py#L20-L28 |
249,609 | 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 |
249,610 | 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",
"(",
"\"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",
"]",
")"
] | 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 |
249,611 | 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",
".",
"MAVLINK_MSG_ID_RADIO_STATUS",
":",
"True",
"}",
"if",
"msgId",
"in",
"self",
".",
"allow",
":",
"return",
"True",
"if",
"self",
".",
"settings",
".",
"allow_unsigned",
":",
"return",
"True",
"return",
"False"
] | 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 |
249,612 | 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",
"(",
"\"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\"",
")"
] | 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 |
249,613 | 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_signing_send",
"(",
"self",
".",
"target_system",
",",
"self",
".",
"target_component",
",",
"[",
"0",
"]",
"*",
"32",
",",
"0",
")",
"self",
".",
"master",
".",
"disable_signing",
"(",
")",
"print",
"(",
"\"Removed signing\"",
")"
] | remove signing from server | [
"remove",
"signing",
"from",
"server"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_signing.py#L100-L107 |
249,614 | 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\"",
":",
"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>\"",
")"
] | handle output commands | [
"handle",
"output",
"commands"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_output.py#L21-L41 |
249,615 | 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",
"=",
"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"
] | add new output | [
"add",
"new",
"output"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_output.py#L55-L69 |
249,616 | 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",
")",
")",
"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"
] | 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 |
249,617 | 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",
".",
"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"
] | remove an output | [
"remove",
"an",
"output"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_output.py#L90-L103 |
249,618 | 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 |
249,619 | 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",
".",
"WinLayout",
")",
":",
"win_layout",
".",
"set_layout",
"(",
"evt",
",",
"self",
".",
"set_layout",
")",
"if",
"self",
".",
"event_queue",
".",
"qsize",
"(",
")",
"==",
"0",
":",
"return",
"None",
"evt",
"=",
"self",
".",
"event_queue",
".",
"get",
"(",
")",
"return",
"evt"
] | 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 |
249,620 | 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",
"[",
"0",
"]",
"==",
"\"load\"",
":",
"win_layout",
".",
"load_layout",
"(",
"self",
".",
"mpstate",
".",
"settings",
".",
"vehicle_name",
")",
"elif",
"args",
"[",
"0",
"]",
"==",
"\"save\"",
":",
"win_layout",
".",
"save_layout",
"(",
"self",
".",
"mpstate",
".",
"settings",
".",
"vehicle_name",
")"
] | handle layout command | [
"handle",
"layout",
"command"
] | f50bdeff33064876f7dc8dc4683d278ff47f75d5 | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_layout.py#L13-L22 |
249,621 | 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",
"is",
"None",
":",
"continue",
"try",
":",
"open",
"(",
"file",
",",
"mode",
"=",
"'wb'",
")",
".",
"write",
"(",
"data",
")",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"\"Failed to save to %s : %s\"",
"%",
"(",
"file",
",",
"e",
")",
")"
] | 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 |
249,622 | 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",
"=",
"str",
".",
"find",
"(",
"\"\\0\"",
")",
"if",
"idx",
"!=",
"-",
"1",
":",
"str",
"=",
"str",
"[",
":",
"idx",
"]",
"return",
"str"
] | 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 |
249,623 | 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",
"=",
"(",
"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",
")",
")"
] | 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 |
249,624 | 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):
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",
".",
"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.\"",
")"
] | 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 |
249,625 | 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):
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",
">",
"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",
"(",
")"
] | 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 |
249,626 | 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):
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",
"=",
"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"
] | 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 |
249,627 | 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):
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",
"=",
"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"
] | 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 |
249,628 | 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):
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",
"(",
"\"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",
"(",
")"
] | 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 |
249,629 | 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):
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 |
249,630 | 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):
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 |
249,631 | 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):
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",
"=",
"sticky"
] | 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 |
249,632 | 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):
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 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.\"",
")"
] | 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 |
249,633 | 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):
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",
".",
"_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"
] | 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 |
249,634 | 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):
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",
"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"
] | 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 |
249,635 | 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):
# 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",
".",
"items",
"(",
")",
":",
"ldap",
".",
"set_option",
"(",
"opt",
",",
"value",
")",
"cls",
".",
"_ldap_configured",
"=",
"True",
"return",
"ldap"
] | 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 |
249,636 | 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):
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",
"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",
")"
] | 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",
"values",
"escaped",
"pass",
"escape",
"=",
"False",
"."
] | 9ce3c2825527f8faa1793958b041816e63d839af | https://github.com/django-auth-ldap/django-auth-ldap/blob/9ce3c2825527f8faa1793958b041816e63d839af/django_auth_ldap/config.py#L105-L122 |
249,637 | 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):
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",
".",
"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"
] | 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 |
249,638 | 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):
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",
"(",
"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"
] | 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 |
249,639 | 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):
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",
"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",
"(",
")"
] | 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",
"to",
"etc",
".",
"Circular",
"references",
"will",
"be",
"detected",
"and",
"pruned",
"."
] | 9ce3c2825527f8faa1793958b041816e63d839af | https://github.com/django-auth-ldap/django-auth-ldap/blob/9ce3c2825527f8faa1793958b041816e63d839af/django_auth_ldap/config.py#L509-L532 |
249,640 | 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):
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",
"ValueError",
"(",
"self",
".",
"connector",
")",
"return",
"aggregator"
] | 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 |
249,641 | 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):
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",
",",
"groups",
")",
"else",
":",
"yield",
"groups",
".",
"is_member_of",
"(",
"child",
")"
] | 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 |
249,642 | 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):
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'",
":",
"'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",
"(",
")"
] | 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 |
249,643 | 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):
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'",
":",
"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",
")"
] | Calculates position information | [
"Calculates",
"position",
"information"
] | d9f63bfdfe1519c4d7a81697ee066e49dc26a30b | https://github.com/regebro/hovercraft/blob/d9f63bfdfe1519c4d7a81697ee066e49dc26a30b/hovercraft/position.py#L131-L216 |
249,644 | 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):
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",
"=",
"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'",
"]"
] | 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 |
249,645 | 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):
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 |
249,646 | 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):
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",
"node",
".",
"items",
"(",
")",
":",
"element",
".",
"set",
"(",
"key",
",",
"value",
")",
"return",
"element"
] | 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 |
249,647 | 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):
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",
"(",
"'?'",
"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",
")"
] | 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 |
249,648 | 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):
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",
"=",
"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",
"}"
] | 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 |
249,649 | 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):
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",
".",
"close",
"(",
")",
"# valid port ?",
"if",
"0",
"<",
"int",
"(",
"port",
")",
"<",
"65536",
":",
"self",
".",
"__port",
"=",
"int",
"(",
"port",
")",
"return",
"self",
".",
"__port",
"else",
":",
"return",
"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 | [
"Get",
"or",
"set",
"TCP",
"port"
] | 993f6e2f5ab52eba164be049e42cea560c3751a5 | https://github.com/sourceperl/pyModbusTCP/blob/993f6e2f5ab52eba164be049e42cea560c3751a5/pyModbusTCP/client.py#L145-L162 |
249,650 | 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):
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",
"(",
"unit_id",
")",
"return",
"self",
".",
"__unit_id",
"else",
":",
"return",
"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 | [
"Get",
"or",
"set",
"unit",
"ID",
"field"
] | 993f6e2f5ab52eba164be049e42cea560c3751a5 | https://github.com/sourceperl/pyModbusTCP/blob/993f6e2f5ab52eba164be049e42cea560c3751a5/pyModbusTCP/client.py#L164-L178 |
249,651 | 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):
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",
"(",
"timeout",
")",
"return",
"self",
".",
"__timeout",
"else",
":",
"return",
"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 | [
"Get",
"or",
"set",
"timeout",
"field"
] | 993f6e2f5ab52eba164be049e42cea560c3751a5 | https://github.com/sourceperl/pyModbusTCP/blob/993f6e2f5ab52eba164be049e42cea560c3751a5/pyModbusTCP/client.py#L180-L194 |
249,652 | 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):
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 |
249,653 | 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):
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 |
249,654 | 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):
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",
")",
"[",
"0",
"]",
":",
"return",
"True",
"else",
":",
"self",
".",
"__last_error",
"=",
"const",
".",
"MB_TIMEOUT_ERR",
"self",
".",
"__debug_msg",
"(",
"'timeout error'",
")",
"self",
".",
"close",
"(",
")",
"return",
"None"
] | 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 |
249,655 | 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):
# 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",
")",
"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"
] | 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 |
249,656 | 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):
# 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",
".",
"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"
] | 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 |
249,657 | 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):
# 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",
"=",
"self",
".",
"_send",
"(",
"frame",
")",
"if",
"bytes_send",
":",
"if",
"self",
".",
"__debug",
":",
"self",
".",
"_pretty_dump",
"(",
"'Tx'",
",",
"frame",
")",
"return",
"bytes_send",
"else",
":",
"return",
"None"
] | 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 |
249,658 | 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
# 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",
"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"
] | 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 |
249,659 | 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):
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",
":",
"yield",
"\"\"",
".",
"join",
"(",
"chars",
")",
"chars",
"=",
"[",
"]",
"chars_len",
"=",
"0",
"chars",
".",
"append",
"(",
"char",
")",
"chars_len",
"+=",
"char_len",
"if",
"chars",
":",
"yield",
"\"\"",
".",
"join",
"(",
"chars",
")"
] | 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 |
249,660 | 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):
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",
"=",
"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",
")"
] | 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 |
249,661 | 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):
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",
"(",
")",
"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",
"(",
")",
"+",
"'…'"
] | 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 |
249,662 | ihabunek/toot | toot/wcstring.py | pad | def pad(text, length):
"""Pads text to given length, taking into account wide characters."""
text_length = wcswidth(text)
if text_length < length:
return text + ' ' * (length - text_length)
return text | python | def pad(text, length):
text_length = wcswidth(text)
if text_length < length:
return text + ' ' * (length - text_length)
return text | [
"def",
"pad",
"(",
"text",
",",
"length",
")",
":",
"text_length",
"=",
"wcswidth",
"(",
"text",
")",
"if",
"text_length",
"<",
"length",
":",
"return",
"text",
"+",
"' '",
"*",
"(",
"length",
"-",
"text_length",
")",
"return",
"text"
] | Pads text to given length, taking into account wide characters. | [
"Pads",
"text",
"to",
"given",
"length",
"taking",
"into",
"account",
"wide",
"characters",
"."
] | d13fa8685b300f96621fa325774913ec0f413a7f | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/wcstring.py#L101-L108 |
249,663 | ihabunek/toot | toot/wcstring.py | fit_text | def fit_text(text, length):
"""Makes text fit the given length by padding or truncating it."""
text_length = wcswidth(text)
if text_length > length:
return trunc(text, length)
if text_length < length:
return pad(text, length)
return text | python | def fit_text(text, length):
text_length = wcswidth(text)
if text_length > length:
return trunc(text, length)
if text_length < length:
return pad(text, length)
return text | [
"def",
"fit_text",
"(",
"text",
",",
"length",
")",
":",
"text_length",
"=",
"wcswidth",
"(",
"text",
")",
"if",
"text_length",
">",
"length",
":",
"return",
"trunc",
"(",
"text",
",",
"length",
")",
"if",
"text_length",
"<",
"length",
":",
"return",
"pad",
"(",
"text",
",",
"length",
")",
"return",
"text"
] | Makes text fit the given length by padding or truncating it. | [
"Makes",
"text",
"fit",
"the",
"given",
"length",
"by",
"padding",
"or",
"truncating",
"it",
"."
] | d13fa8685b300f96621fa325774913ec0f413a7f | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/wcstring.py#L111-L121 |
249,664 | ihabunek/toot | toot/http.py | _get_error_message | def _get_error_message(response):
"""Attempt to extract an error message from response body"""
try:
data = response.json()
if "error_description" in data:
return data['error_description']
if "error" in data:
return data['error']
except Exception:
pass
return "Unknown error" | python | def _get_error_message(response):
try:
data = response.json()
if "error_description" in data:
return data['error_description']
if "error" in data:
return data['error']
except Exception:
pass
return "Unknown error" | [
"def",
"_get_error_message",
"(",
"response",
")",
":",
"try",
":",
"data",
"=",
"response",
".",
"json",
"(",
")",
"if",
"\"error_description\"",
"in",
"data",
":",
"return",
"data",
"[",
"'error_description'",
"]",
"if",
"\"error\"",
"in",
"data",
":",
"return",
"data",
"[",
"'error'",
"]",
"except",
"Exception",
":",
"pass",
"return",
"\"Unknown error\""
] | Attempt to extract an error message from response body | [
"Attempt",
"to",
"extract",
"an",
"error",
"message",
"from",
"response",
"body"
] | d13fa8685b300f96621fa325774913ec0f413a7f | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/http.py#L19-L30 |
249,665 | ihabunek/toot | toot/api.py | _get_next_path | def _get_next_path(headers):
"""Given timeline response headers, returns the path to the next batch"""
links = headers.get('Link', '')
matches = re.match('<([^>]+)>; rel="next"', links)
if matches:
parsed = urlparse(matches.group(1))
return "?".join([parsed.path, parsed.query]) | python | def _get_next_path(headers):
links = headers.get('Link', '')
matches = re.match('<([^>]+)>; rel="next"', links)
if matches:
parsed = urlparse(matches.group(1))
return "?".join([parsed.path, parsed.query]) | [
"def",
"_get_next_path",
"(",
"headers",
")",
":",
"links",
"=",
"headers",
".",
"get",
"(",
"'Link'",
",",
"''",
")",
"matches",
"=",
"re",
".",
"match",
"(",
"'<([^>]+)>; rel=\"next\"'",
",",
"links",
")",
"if",
"matches",
":",
"parsed",
"=",
"urlparse",
"(",
"matches",
".",
"group",
"(",
"1",
")",
")",
"return",
"\"?\"",
".",
"join",
"(",
"[",
"parsed",
".",
"path",
",",
"parsed",
".",
"query",
"]",
")"
] | Given timeline response headers, returns the path to the next batch | [
"Given",
"timeline",
"response",
"headers",
"returns",
"the",
"path",
"to",
"the",
"next",
"batch"
] | d13fa8685b300f96621fa325774913ec0f413a7f | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/api.py#L160-L166 |
249,666 | ihabunek/toot | toot/ui/app.py | TimelineApp.select_previous | def select_previous(self):
"""Move to the previous status in the timeline."""
self.footer.clear_message()
if self.selected == 0:
self.footer.draw_message("Cannot move beyond first toot.", Color.GREEN)
return
old_index = self.selected
new_index = self.selected - 1
self.selected = new_index
self.redraw_after_selection_change(old_index, new_index) | python | def select_previous(self):
self.footer.clear_message()
if self.selected == 0:
self.footer.draw_message("Cannot move beyond first toot.", Color.GREEN)
return
old_index = self.selected
new_index = self.selected - 1
self.selected = new_index
self.redraw_after_selection_change(old_index, new_index) | [
"def",
"select_previous",
"(",
"self",
")",
":",
"self",
".",
"footer",
".",
"clear_message",
"(",
")",
"if",
"self",
".",
"selected",
"==",
"0",
":",
"self",
".",
"footer",
".",
"draw_message",
"(",
"\"Cannot move beyond first toot.\"",
",",
"Color",
".",
"GREEN",
")",
"return",
"old_index",
"=",
"self",
".",
"selected",
"new_index",
"=",
"self",
".",
"selected",
"-",
"1",
"self",
".",
"selected",
"=",
"new_index",
"self",
".",
"redraw_after_selection_change",
"(",
"old_index",
",",
"new_index",
")"
] | Move to the previous status in the timeline. | [
"Move",
"to",
"the",
"previous",
"status",
"in",
"the",
"timeline",
"."
] | d13fa8685b300f96621fa325774913ec0f413a7f | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/ui/app.py#L692-L704 |
249,667 | ihabunek/toot | toot/ui/app.py | TimelineApp.select_next | def select_next(self):
"""Move to the next status in the timeline."""
self.footer.clear_message()
old_index = self.selected
new_index = self.selected + 1
# Load more statuses if no more are available
if self.selected + 1 >= len(self.statuses):
self.fetch_next()
self.left.draw_statuses(self.statuses, self.selected, new_index - 1)
self.draw_footer_status()
self.selected = new_index
self.redraw_after_selection_change(old_index, new_index) | python | def select_next(self):
self.footer.clear_message()
old_index = self.selected
new_index = self.selected + 1
# Load more statuses if no more are available
if self.selected + 1 >= len(self.statuses):
self.fetch_next()
self.left.draw_statuses(self.statuses, self.selected, new_index - 1)
self.draw_footer_status()
self.selected = new_index
self.redraw_after_selection_change(old_index, new_index) | [
"def",
"select_next",
"(",
"self",
")",
":",
"self",
".",
"footer",
".",
"clear_message",
"(",
")",
"old_index",
"=",
"self",
".",
"selected",
"new_index",
"=",
"self",
".",
"selected",
"+",
"1",
"# Load more statuses if no more are available",
"if",
"self",
".",
"selected",
"+",
"1",
">=",
"len",
"(",
"self",
".",
"statuses",
")",
":",
"self",
".",
"fetch_next",
"(",
")",
"self",
".",
"left",
".",
"draw_statuses",
"(",
"self",
".",
"statuses",
",",
"self",
".",
"selected",
",",
"new_index",
"-",
"1",
")",
"self",
".",
"draw_footer_status",
"(",
")",
"self",
".",
"selected",
"=",
"new_index",
"self",
".",
"redraw_after_selection_change",
"(",
"old_index",
",",
"new_index",
")"
] | Move to the next status in the timeline. | [
"Move",
"to",
"the",
"next",
"status",
"in",
"the",
"timeline",
"."
] | d13fa8685b300f96621fa325774913ec0f413a7f | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/ui/app.py#L706-L720 |
249,668 | ihabunek/toot | toot/ui/app.py | TimelineApp.full_redraw | def full_redraw(self):
"""Perform a full redraw of the UI."""
self.left.draw_statuses(self.statuses, self.selected)
self.right.draw(self.get_selected_status())
self.header.draw(self.user)
self.draw_footer_status() | python | def full_redraw(self):
self.left.draw_statuses(self.statuses, self.selected)
self.right.draw(self.get_selected_status())
self.header.draw(self.user)
self.draw_footer_status() | [
"def",
"full_redraw",
"(",
"self",
")",
":",
"self",
".",
"left",
".",
"draw_statuses",
"(",
"self",
".",
"statuses",
",",
"self",
".",
"selected",
")",
"self",
".",
"right",
".",
"draw",
"(",
"self",
".",
"get_selected_status",
"(",
")",
")",
"self",
".",
"header",
".",
"draw",
"(",
"self",
".",
"user",
")",
"self",
".",
"draw_footer_status",
"(",
")"
] | Perform a full redraw of the UI. | [
"Perform",
"a",
"full",
"redraw",
"of",
"the",
"UI",
"."
] | d13fa8685b300f96621fa325774913ec0f413a7f | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/ui/app.py#L740-L746 |
249,669 | ihabunek/toot | toot/ui/utils.py | size_as_drawn | def size_as_drawn(lines, screen_width):
"""Get the bottom-right corner of some text as would be drawn by draw_lines"""
y = 0
x = 0
for line in lines:
wrapped = list(wc_wrap(line, screen_width))
if len(wrapped) > 0:
for wrapped_line in wrapped:
x = len(wrapped_line)
y += 1
else:
x = 0
y += 1
return y - 1, x - 1 if x != 0 else 0 | python | def size_as_drawn(lines, screen_width):
y = 0
x = 0
for line in lines:
wrapped = list(wc_wrap(line, screen_width))
if len(wrapped) > 0:
for wrapped_line in wrapped:
x = len(wrapped_line)
y += 1
else:
x = 0
y += 1
return y - 1, x - 1 if x != 0 else 0 | [
"def",
"size_as_drawn",
"(",
"lines",
",",
"screen_width",
")",
":",
"y",
"=",
"0",
"x",
"=",
"0",
"for",
"line",
"in",
"lines",
":",
"wrapped",
"=",
"list",
"(",
"wc_wrap",
"(",
"line",
",",
"screen_width",
")",
")",
"if",
"len",
"(",
"wrapped",
")",
">",
"0",
":",
"for",
"wrapped_line",
"in",
"wrapped",
":",
"x",
"=",
"len",
"(",
"wrapped_line",
")",
"y",
"+=",
"1",
"else",
":",
"x",
"=",
"0",
"y",
"+=",
"1",
"return",
"y",
"-",
"1",
",",
"x",
"-",
"1",
"if",
"x",
"!=",
"0",
"else",
"0"
] | Get the bottom-right corner of some text as would be drawn by draw_lines | [
"Get",
"the",
"bottom",
"-",
"right",
"corner",
"of",
"some",
"text",
"as",
"would",
"be",
"drawn",
"by",
"draw_lines"
] | d13fa8685b300f96621fa325774913ec0f413a7f | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/ui/utils.py#L49-L62 |
249,670 | ihabunek/toot | toot/commands.py | _find_account | def _find_account(app, user, account_name):
"""For a given account name, returns the Account object.
Raises an exception if not found.
"""
if not account_name:
raise ConsoleError("Empty account name given")
accounts = api.search_accounts(app, user, account_name)
if account_name[0] == "@":
account_name = account_name[1:]
for account in accounts:
if account['acct'] == account_name:
return account
raise ConsoleError("Account not found") | python | def _find_account(app, user, account_name):
if not account_name:
raise ConsoleError("Empty account name given")
accounts = api.search_accounts(app, user, account_name)
if account_name[0] == "@":
account_name = account_name[1:]
for account in accounts:
if account['acct'] == account_name:
return account
raise ConsoleError("Account not found") | [
"def",
"_find_account",
"(",
"app",
",",
"user",
",",
"account_name",
")",
":",
"if",
"not",
"account_name",
":",
"raise",
"ConsoleError",
"(",
"\"Empty account name given\"",
")",
"accounts",
"=",
"api",
".",
"search_accounts",
"(",
"app",
",",
"user",
",",
"account_name",
")",
"if",
"account_name",
"[",
"0",
"]",
"==",
"\"@\"",
":",
"account_name",
"=",
"account_name",
"[",
"1",
":",
"]",
"for",
"account",
"in",
"accounts",
":",
"if",
"account",
"[",
"'acct'",
"]",
"==",
"account_name",
":",
"return",
"account",
"raise",
"ConsoleError",
"(",
"\"Account not found\"",
")"
] | For a given account name, returns the Account object.
Raises an exception if not found. | [
"For",
"a",
"given",
"account",
"name",
"returns",
"the",
"Account",
"object",
"."
] | d13fa8685b300f96621fa325774913ec0f413a7f | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/commands.py#L216-L233 |
249,671 | ihabunek/toot | toot/config_legacy.py | add_username | def add_username(user, apps):
"""When using broser login, username was not stored so look it up"""
if not user:
return None
apps = [a for a in apps if a.instance == user.instance]
if not apps:
return None
from toot.api import verify_credentials
creds = verify_credentials(apps.pop(), user)
return User(user.instance, creds['username'], user.access_token) | python | def add_username(user, apps):
if not user:
return None
apps = [a for a in apps if a.instance == user.instance]
if not apps:
return None
from toot.api import verify_credentials
creds = verify_credentials(apps.pop(), user)
return User(user.instance, creds['username'], user.access_token) | [
"def",
"add_username",
"(",
"user",
",",
"apps",
")",
":",
"if",
"not",
"user",
":",
"return",
"None",
"apps",
"=",
"[",
"a",
"for",
"a",
"in",
"apps",
"if",
"a",
".",
"instance",
"==",
"user",
".",
"instance",
"]",
"if",
"not",
"apps",
":",
"return",
"None",
"from",
"toot",
".",
"api",
"import",
"verify_credentials",
"creds",
"=",
"verify_credentials",
"(",
"apps",
".",
"pop",
"(",
")",
",",
"user",
")",
"return",
"User",
"(",
"user",
".",
"instance",
",",
"creds",
"[",
"'username'",
"]",
",",
"user",
".",
"access_token",
")"
] | When using broser login, username was not stored so look it up | [
"When",
"using",
"broser",
"login",
"username",
"was",
"not",
"stored",
"so",
"look",
"it",
"up"
] | d13fa8685b300f96621fa325774913ec0f413a7f | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/config_legacy.py#L42-L55 |
249,672 | ihabunek/toot | toot/utils.py | get_text | def get_text(html):
"""Converts html to text, strips all tags."""
# Ignore warnings made by BeautifulSoup, if passed something that looks like
# a file (e.g. a dot which matches current dict), it will warn that the file
# should be opened instead of passing a filename.
with warnings.catch_warnings():
warnings.simplefilter("ignore")
text = BeautifulSoup(html.replace(''', "'"), "html.parser").get_text()
return unicodedata.normalize('NFKC', text) | python | def get_text(html):
# Ignore warnings made by BeautifulSoup, if passed something that looks like
# a file (e.g. a dot which matches current dict), it will warn that the file
# should be opened instead of passing a filename.
with warnings.catch_warnings():
warnings.simplefilter("ignore")
text = BeautifulSoup(html.replace(''', "'"), "html.parser").get_text()
return unicodedata.normalize('NFKC', text) | [
"def",
"get_text",
"(",
"html",
")",
":",
"# Ignore warnings made by BeautifulSoup, if passed something that looks like",
"# a file (e.g. a dot which matches current dict), it will warn that the file",
"# should be opened instead of passing a filename.",
"with",
"warnings",
".",
"catch_warnings",
"(",
")",
":",
"warnings",
".",
"simplefilter",
"(",
"\"ignore\"",
")",
"text",
"=",
"BeautifulSoup",
"(",
"html",
".",
"replace",
"(",
"'''",
",",
"\"'\"",
")",
",",
"\"html.parser\"",
")",
".",
"get_text",
"(",
")",
"return",
"unicodedata",
".",
"normalize",
"(",
"'NFKC'",
",",
"text",
")"
] | Converts html to text, strips all tags. | [
"Converts",
"html",
"to",
"text",
"strips",
"all",
"tags",
"."
] | d13fa8685b300f96621fa325774913ec0f413a7f | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/utils.py#L19-L29 |
249,673 | ihabunek/toot | toot/utils.py | parse_html | def parse_html(html):
"""Attempt to convert html to plain text while keeping line breaks.
Returns a list of paragraphs, each being a list of lines.
"""
paragraphs = re.split("</?p[^>]*>", html)
# Convert <br>s to line breaks and remove empty paragraphs
paragraphs = [re.split("<br */?>", p) for p in paragraphs if p]
# Convert each line in each paragraph to plain text:
return [[get_text(l) for l in p] for p in paragraphs] | python | def parse_html(html):
paragraphs = re.split("</?p[^>]*>", html)
# Convert <br>s to line breaks and remove empty paragraphs
paragraphs = [re.split("<br */?>", p) for p in paragraphs if p]
# Convert each line in each paragraph to plain text:
return [[get_text(l) for l in p] for p in paragraphs] | [
"def",
"parse_html",
"(",
"html",
")",
":",
"paragraphs",
"=",
"re",
".",
"split",
"(",
"\"</?p[^>]*>\"",
",",
"html",
")",
"# Convert <br>s to line breaks and remove empty paragraphs",
"paragraphs",
"=",
"[",
"re",
".",
"split",
"(",
"\"<br */?>\"",
",",
"p",
")",
"for",
"p",
"in",
"paragraphs",
"if",
"p",
"]",
"# Convert each line in each paragraph to plain text:",
"return",
"[",
"[",
"get_text",
"(",
"l",
")",
"for",
"l",
"in",
"p",
"]",
"for",
"p",
"in",
"paragraphs",
"]"
] | Attempt to convert html to plain text while keeping line breaks.
Returns a list of paragraphs, each being a list of lines. | [
"Attempt",
"to",
"convert",
"html",
"to",
"plain",
"text",
"while",
"keeping",
"line",
"breaks",
".",
"Returns",
"a",
"list",
"of",
"paragraphs",
"each",
"being",
"a",
"list",
"of",
"lines",
"."
] | d13fa8685b300f96621fa325774913ec0f413a7f | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/utils.py#L32-L42 |
249,674 | ihabunek/toot | toot/utils.py | format_content | def format_content(content):
"""Given a Status contents in HTML, converts it into lines of plain text.
Returns a generator yielding lines of content.
"""
paragraphs = parse_html(content)
first = True
for paragraph in paragraphs:
if not first:
yield ""
for line in paragraph:
yield line
first = False | python | def format_content(content):
paragraphs = parse_html(content)
first = True
for paragraph in paragraphs:
if not first:
yield ""
for line in paragraph:
yield line
first = False | [
"def",
"format_content",
"(",
"content",
")",
":",
"paragraphs",
"=",
"parse_html",
"(",
"content",
")",
"first",
"=",
"True",
"for",
"paragraph",
"in",
"paragraphs",
":",
"if",
"not",
"first",
":",
"yield",
"\"\"",
"for",
"line",
"in",
"paragraph",
":",
"yield",
"line",
"first",
"=",
"False"
] | Given a Status contents in HTML, converts it into lines of plain text.
Returns a generator yielding lines of content. | [
"Given",
"a",
"Status",
"contents",
"in",
"HTML",
"converts",
"it",
"into",
"lines",
"of",
"plain",
"text",
"."
] | d13fa8685b300f96621fa325774913ec0f413a7f | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/utils.py#L45-L62 |
249,675 | ihabunek/toot | toot/utils.py | multiline_input | def multiline_input():
"""Lets user input multiple lines of text, terminated by EOF."""
lines = []
while True:
try:
lines.append(input())
except EOFError:
break
return "\n".join(lines).strip() | python | def multiline_input():
lines = []
while True:
try:
lines.append(input())
except EOFError:
break
return "\n".join(lines).strip() | [
"def",
"multiline_input",
"(",
")",
":",
"lines",
"=",
"[",
"]",
"while",
"True",
":",
"try",
":",
"lines",
".",
"append",
"(",
"input",
"(",
")",
")",
"except",
"EOFError",
":",
"break",
"return",
"\"\\n\"",
".",
"join",
"(",
"lines",
")",
".",
"strip",
"(",
")"
] | Lets user input multiple lines of text, terminated by EOF. | [
"Lets",
"user",
"input",
"multiple",
"lines",
"of",
"text",
"terminated",
"by",
"EOF",
"."
] | d13fa8685b300f96621fa325774913ec0f413a7f | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/utils.py#L81-L90 |
249,676 | Azure/azure-kusto-python | azure-kusto-data/azure/kusto/data/_models.py | KustoResultTable.to_dict | def to_dict(self):
"""Converts the table to a dict."""
return {"name": self.table_name, "kind": self.table_kind, "data": [r.to_dict() for r in self]} | python | def to_dict(self):
return {"name": self.table_name, "kind": self.table_kind, "data": [r.to_dict() for r in self]} | [
"def",
"to_dict",
"(",
"self",
")",
":",
"return",
"{",
"\"name\"",
":",
"self",
".",
"table_name",
",",
"\"kind\"",
":",
"self",
".",
"table_kind",
",",
"\"data\"",
":",
"[",
"r",
".",
"to_dict",
"(",
")",
"for",
"r",
"in",
"self",
"]",
"}"
] | Converts the table to a dict. | [
"Converts",
"the",
"table",
"to",
"a",
"dict",
"."
] | 92466a2ae175d6353d1dee3496a02517b2a71a86 | https://github.com/Azure/azure-kusto-python/blob/92466a2ae175d6353d1dee3496a02517b2a71a86/azure-kusto-data/azure/kusto/data/_models.py#L152-L154 |
249,677 | Azure/azure-kusto-python | azure-kusto-data/azure/kusto/data/_converters.py | to_datetime | def to_datetime(value):
"""Converts a string to a datetime."""
if value is None:
return None
if isinstance(value, six.integer_types):
return parser.parse(value)
return parser.isoparse(value) | python | def to_datetime(value):
if value is None:
return None
if isinstance(value, six.integer_types):
return parser.parse(value)
return parser.isoparse(value) | [
"def",
"to_datetime",
"(",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"integer_types",
")",
":",
"return",
"parser",
".",
"parse",
"(",
"value",
")",
"return",
"parser",
".",
"isoparse",
"(",
"value",
")"
] | Converts a string to a datetime. | [
"Converts",
"a",
"string",
"to",
"a",
"datetime",
"."
] | 92466a2ae175d6353d1dee3496a02517b2a71a86 | https://github.com/Azure/azure-kusto-python/blob/92466a2ae175d6353d1dee3496a02517b2a71a86/azure-kusto-data/azure/kusto/data/_converters.py#L12-L19 |
249,678 | Azure/azure-kusto-python | azure-kusto-data/azure/kusto/data/_converters.py | to_timedelta | def to_timedelta(value):
"""Converts a string to a timedelta."""
if value is None:
return None
if isinstance(value, (six.integer_types, float)):
return timedelta(microseconds=(float(value) / 10))
match = _TIMESPAN_PATTERN.match(value)
if match:
if match.group(1) == "-":
factor = -1
else:
factor = 1
return factor * timedelta(
days=int(match.group("d") or 0),
hours=int(match.group("h")),
minutes=int(match.group("m")),
seconds=float(match.group("s")),
)
else:
raise ValueError("Timespan value '{}' cannot be decoded".format(value)) | python | def to_timedelta(value):
if value is None:
return None
if isinstance(value, (six.integer_types, float)):
return timedelta(microseconds=(float(value) / 10))
match = _TIMESPAN_PATTERN.match(value)
if match:
if match.group(1) == "-":
factor = -1
else:
factor = 1
return factor * timedelta(
days=int(match.group("d") or 0),
hours=int(match.group("h")),
minutes=int(match.group("m")),
seconds=float(match.group("s")),
)
else:
raise ValueError("Timespan value '{}' cannot be decoded".format(value)) | [
"def",
"to_timedelta",
"(",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"value",
",",
"(",
"six",
".",
"integer_types",
",",
"float",
")",
")",
":",
"return",
"timedelta",
"(",
"microseconds",
"=",
"(",
"float",
"(",
"value",
")",
"/",
"10",
")",
")",
"match",
"=",
"_TIMESPAN_PATTERN",
".",
"match",
"(",
"value",
")",
"if",
"match",
":",
"if",
"match",
".",
"group",
"(",
"1",
")",
"==",
"\"-\"",
":",
"factor",
"=",
"-",
"1",
"else",
":",
"factor",
"=",
"1",
"return",
"factor",
"*",
"timedelta",
"(",
"days",
"=",
"int",
"(",
"match",
".",
"group",
"(",
"\"d\"",
")",
"or",
"0",
")",
",",
"hours",
"=",
"int",
"(",
"match",
".",
"group",
"(",
"\"h\"",
")",
")",
",",
"minutes",
"=",
"int",
"(",
"match",
".",
"group",
"(",
"\"m\"",
")",
")",
",",
"seconds",
"=",
"float",
"(",
"match",
".",
"group",
"(",
"\"s\"",
")",
")",
",",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Timespan value '{}' cannot be decoded\"",
".",
"format",
"(",
"value",
")",
")"
] | Converts a string to a timedelta. | [
"Converts",
"a",
"string",
"to",
"a",
"timedelta",
"."
] | 92466a2ae175d6353d1dee3496a02517b2a71a86 | https://github.com/Azure/azure-kusto-python/blob/92466a2ae175d6353d1dee3496a02517b2a71a86/azure-kusto-data/azure/kusto/data/_converters.py#L22-L41 |
249,679 | Azure/azure-kusto-python | azure-kusto-data/azure/kusto/data/security.py | _AadHelper.acquire_authorization_header | def acquire_authorization_header(self):
"""Acquire tokens from AAD."""
try:
return self._acquire_authorization_header()
except AdalError as error:
if self._authentication_method is AuthenticationMethod.aad_username_password:
kwargs = {"username": self._username, "client_id": self._client_id}
elif self._authentication_method is AuthenticationMethod.aad_application_key:
kwargs = {"client_id": self._client_id}
elif self._authentication_method is AuthenticationMethod.aad_device_login:
kwargs = {"client_id": self._client_id}
elif self._authentication_method is AuthenticationMethod.aad_application_certificate:
kwargs = {"client_id": self._client_id, "thumbprint": self._thumbprint}
else:
raise error
kwargs["resource"] = self._kusto_cluster
kwargs["authority"] = self._adal_context.authority.url
raise KustoAuthenticationError(self._authentication_method.value, error, **kwargs) | python | def acquire_authorization_header(self):
try:
return self._acquire_authorization_header()
except AdalError as error:
if self._authentication_method is AuthenticationMethod.aad_username_password:
kwargs = {"username": self._username, "client_id": self._client_id}
elif self._authentication_method is AuthenticationMethod.aad_application_key:
kwargs = {"client_id": self._client_id}
elif self._authentication_method is AuthenticationMethod.aad_device_login:
kwargs = {"client_id": self._client_id}
elif self._authentication_method is AuthenticationMethod.aad_application_certificate:
kwargs = {"client_id": self._client_id, "thumbprint": self._thumbprint}
else:
raise error
kwargs["resource"] = self._kusto_cluster
kwargs["authority"] = self._adal_context.authority.url
raise KustoAuthenticationError(self._authentication_method.value, error, **kwargs) | [
"def",
"acquire_authorization_header",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_acquire_authorization_header",
"(",
")",
"except",
"AdalError",
"as",
"error",
":",
"if",
"self",
".",
"_authentication_method",
"is",
"AuthenticationMethod",
".",
"aad_username_password",
":",
"kwargs",
"=",
"{",
"\"username\"",
":",
"self",
".",
"_username",
",",
"\"client_id\"",
":",
"self",
".",
"_client_id",
"}",
"elif",
"self",
".",
"_authentication_method",
"is",
"AuthenticationMethod",
".",
"aad_application_key",
":",
"kwargs",
"=",
"{",
"\"client_id\"",
":",
"self",
".",
"_client_id",
"}",
"elif",
"self",
".",
"_authentication_method",
"is",
"AuthenticationMethod",
".",
"aad_device_login",
":",
"kwargs",
"=",
"{",
"\"client_id\"",
":",
"self",
".",
"_client_id",
"}",
"elif",
"self",
".",
"_authentication_method",
"is",
"AuthenticationMethod",
".",
"aad_application_certificate",
":",
"kwargs",
"=",
"{",
"\"client_id\"",
":",
"self",
".",
"_client_id",
",",
"\"thumbprint\"",
":",
"self",
".",
"_thumbprint",
"}",
"else",
":",
"raise",
"error",
"kwargs",
"[",
"\"resource\"",
"]",
"=",
"self",
".",
"_kusto_cluster",
"kwargs",
"[",
"\"authority\"",
"]",
"=",
"self",
".",
"_adal_context",
".",
"authority",
".",
"url",
"raise",
"KustoAuthenticationError",
"(",
"self",
".",
"_authentication_method",
".",
"value",
",",
"error",
",",
"*",
"*",
"kwargs",
")"
] | Acquire tokens from AAD. | [
"Acquire",
"tokens",
"from",
"AAD",
"."
] | 92466a2ae175d6353d1dee3496a02517b2a71a86 | https://github.com/Azure/azure-kusto-python/blob/92466a2ae175d6353d1dee3496a02517b2a71a86/azure-kusto-data/azure/kusto/data/security.py#L49-L68 |
249,680 | Azure/azure-kusto-python | azure-kusto-data/azure/kusto/data/request.py | KustoClient._execute | def _execute(self, endpoint, database, query, default_timeout, properties=None):
"""Executes given query against this client"""
request_payload = {"db": database, "csl": query}
if properties:
request_payload["properties"] = properties.to_json()
request_headers = {
"Accept": "application/json",
"Accept-Encoding": "gzip,deflate",
"Content-Type": "application/json; charset=utf-8",
"x-ms-client-version": "Kusto.Python.Client:" + VERSION,
"x-ms-client-request-id": "KPC.execute;" + str(uuid.uuid4()),
}
if self._auth_provider:
request_headers["Authorization"] = self._auth_provider.acquire_authorization_header()
timeout = self._get_timeout(properties, default_timeout)
response = self._session.post(endpoint, headers=request_headers, json=request_payload, timeout=timeout.seconds)
if response.status_code == 200:
if endpoint.endswith("v2/rest/query"):
return KustoResponseDataSetV2(response.json())
return KustoResponseDataSetV1(response.json())
raise KustoServiceError([response.json()], response) | python | def _execute(self, endpoint, database, query, default_timeout, properties=None):
request_payload = {"db": database, "csl": query}
if properties:
request_payload["properties"] = properties.to_json()
request_headers = {
"Accept": "application/json",
"Accept-Encoding": "gzip,deflate",
"Content-Type": "application/json; charset=utf-8",
"x-ms-client-version": "Kusto.Python.Client:" + VERSION,
"x-ms-client-request-id": "KPC.execute;" + str(uuid.uuid4()),
}
if self._auth_provider:
request_headers["Authorization"] = self._auth_provider.acquire_authorization_header()
timeout = self._get_timeout(properties, default_timeout)
response = self._session.post(endpoint, headers=request_headers, json=request_payload, timeout=timeout.seconds)
if response.status_code == 200:
if endpoint.endswith("v2/rest/query"):
return KustoResponseDataSetV2(response.json())
return KustoResponseDataSetV1(response.json())
raise KustoServiceError([response.json()], response) | [
"def",
"_execute",
"(",
"self",
",",
"endpoint",
",",
"database",
",",
"query",
",",
"default_timeout",
",",
"properties",
"=",
"None",
")",
":",
"request_payload",
"=",
"{",
"\"db\"",
":",
"database",
",",
"\"csl\"",
":",
"query",
"}",
"if",
"properties",
":",
"request_payload",
"[",
"\"properties\"",
"]",
"=",
"properties",
".",
"to_json",
"(",
")",
"request_headers",
"=",
"{",
"\"Accept\"",
":",
"\"application/json\"",
",",
"\"Accept-Encoding\"",
":",
"\"gzip,deflate\"",
",",
"\"Content-Type\"",
":",
"\"application/json; charset=utf-8\"",
",",
"\"x-ms-client-version\"",
":",
"\"Kusto.Python.Client:\"",
"+",
"VERSION",
",",
"\"x-ms-client-request-id\"",
":",
"\"KPC.execute;\"",
"+",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
",",
"}",
"if",
"self",
".",
"_auth_provider",
":",
"request_headers",
"[",
"\"Authorization\"",
"]",
"=",
"self",
".",
"_auth_provider",
".",
"acquire_authorization_header",
"(",
")",
"timeout",
"=",
"self",
".",
"_get_timeout",
"(",
"properties",
",",
"default_timeout",
")",
"response",
"=",
"self",
".",
"_session",
".",
"post",
"(",
"endpoint",
",",
"headers",
"=",
"request_headers",
",",
"json",
"=",
"request_payload",
",",
"timeout",
"=",
"timeout",
".",
"seconds",
")",
"if",
"response",
".",
"status_code",
"==",
"200",
":",
"if",
"endpoint",
".",
"endswith",
"(",
"\"v2/rest/query\"",
")",
":",
"return",
"KustoResponseDataSetV2",
"(",
"response",
".",
"json",
"(",
")",
")",
"return",
"KustoResponseDataSetV1",
"(",
"response",
".",
"json",
"(",
")",
")",
"raise",
"KustoServiceError",
"(",
"[",
"response",
".",
"json",
"(",
")",
"]",
",",
"response",
")"
] | Executes given query against this client | [
"Executes",
"given",
"query",
"against",
"this",
"client"
] | 92466a2ae175d6353d1dee3496a02517b2a71a86 | https://github.com/Azure/azure-kusto-python/blob/92466a2ae175d6353d1dee3496a02517b2a71a86/azure-kusto-data/azure/kusto/data/request.py#L360-L386 |
249,681 | Azure/azure-kusto-python | azure-kusto-data/azure/kusto/data/request.py | ClientRequestProperties.set_option | def set_option(self, name, value):
"""Sets an option's value"""
_assert_value_is_valid(name)
self._options[name] = value | python | def set_option(self, name, value):
_assert_value_is_valid(name)
self._options[name] = value | [
"def",
"set_option",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"_assert_value_is_valid",
"(",
"name",
")",
"self",
".",
"_options",
"[",
"name",
"]",
"=",
"value"
] | Sets an option's value | [
"Sets",
"an",
"option",
"s",
"value"
] | 92466a2ae175d6353d1dee3496a02517b2a71a86 | https://github.com/Azure/azure-kusto-python/blob/92466a2ae175d6353d1dee3496a02517b2a71a86/azure-kusto-data/azure/kusto/data/request.py#L467-L470 |
249,682 | Azure/azure-kusto-python | azure-kusto-ingest/azure/kusto/ingest/_resource_manager.py | _ResourceUri.parse | def parse(cls, uri):
"""Parses uri into a ResourceUri object"""
match = _URI_FORMAT.search(uri)
return cls(match.group(1), match.group(2), match.group(3), match.group(4)) | python | def parse(cls, uri):
match = _URI_FORMAT.search(uri)
return cls(match.group(1), match.group(2), match.group(3), match.group(4)) | [
"def",
"parse",
"(",
"cls",
",",
"uri",
")",
":",
"match",
"=",
"_URI_FORMAT",
".",
"search",
"(",
"uri",
")",
"return",
"cls",
"(",
"match",
".",
"group",
"(",
"1",
")",
",",
"match",
".",
"group",
"(",
"2",
")",
",",
"match",
".",
"group",
"(",
"3",
")",
",",
"match",
".",
"group",
"(",
"4",
")",
")"
] | Parses uri into a ResourceUri object | [
"Parses",
"uri",
"into",
"a",
"ResourceUri",
"object"
] | 92466a2ae175d6353d1dee3496a02517b2a71a86 | https://github.com/Azure/azure-kusto-python/blob/92466a2ae175d6353d1dee3496a02517b2a71a86/azure-kusto-ingest/azure/kusto/ingest/_resource_manager.py#L17-L20 |
249,683 | Azure/azure-kusto-python | azure-kusto-ingest/azure/kusto/ingest/_ingestion_properties.py | IngestionProperties.get_mapping_format | def get_mapping_format(self):
"""Dictating the corresponding mapping to the format."""
if self.format == DataFormat.json or self.format == DataFormat.avro:
return self.format.name
else:
return DataFormat.csv.name | python | def get_mapping_format(self):
if self.format == DataFormat.json or self.format == DataFormat.avro:
return self.format.name
else:
return DataFormat.csv.name | [
"def",
"get_mapping_format",
"(",
"self",
")",
":",
"if",
"self",
".",
"format",
"==",
"DataFormat",
".",
"json",
"or",
"self",
".",
"format",
"==",
"DataFormat",
".",
"avro",
":",
"return",
"self",
".",
"format",
".",
"name",
"else",
":",
"return",
"DataFormat",
".",
"csv",
".",
"name"
] | Dictating the corresponding mapping to the format. | [
"Dictating",
"the",
"corresponding",
"mapping",
"to",
"the",
"format",
"."
] | 92466a2ae175d6353d1dee3496a02517b2a71a86 | https://github.com/Azure/azure-kusto-python/blob/92466a2ae175d6353d1dee3496a02517b2a71a86/azure-kusto-ingest/azure/kusto/ingest/_ingestion_properties.py#L125-L130 |
249,684 | yuce/pyswip | pyswip/easy.py | getAtomChars | def getAtomChars(t):
"""If t is an atom, return it as a string, otherwise raise InvalidTypeError.
"""
s = c_char_p()
if PL_get_atom_chars(t, byref(s)):
return s.value
else:
raise InvalidTypeError("atom") | python | def getAtomChars(t):
s = c_char_p()
if PL_get_atom_chars(t, byref(s)):
return s.value
else:
raise InvalidTypeError("atom") | [
"def",
"getAtomChars",
"(",
"t",
")",
":",
"s",
"=",
"c_char_p",
"(",
")",
"if",
"PL_get_atom_chars",
"(",
"t",
",",
"byref",
"(",
"s",
")",
")",
":",
"return",
"s",
".",
"value",
"else",
":",
"raise",
"InvalidTypeError",
"(",
"\"atom\"",
")"
] | If t is an atom, return it as a string, otherwise raise InvalidTypeError. | [
"If",
"t",
"is",
"an",
"atom",
"return",
"it",
"as",
"a",
"string",
"otherwise",
"raise",
"InvalidTypeError",
"."
] | f7c1f1e8c3a13b90bd775861d374788a8b5677d8 | https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/easy.py#L333-L340 |
249,685 | yuce/pyswip | pyswip/easy.py | getBool | def getBool(t):
"""If t is of type bool, return it, otherwise raise InvalidTypeError.
"""
b = c_int()
if PL_get_long(t, byref(b)):
return bool(b.value)
else:
raise InvalidTypeError("bool") | python | def getBool(t):
b = c_int()
if PL_get_long(t, byref(b)):
return bool(b.value)
else:
raise InvalidTypeError("bool") | [
"def",
"getBool",
"(",
"t",
")",
":",
"b",
"=",
"c_int",
"(",
")",
"if",
"PL_get_long",
"(",
"t",
",",
"byref",
"(",
"b",
")",
")",
":",
"return",
"bool",
"(",
"b",
".",
"value",
")",
"else",
":",
"raise",
"InvalidTypeError",
"(",
"\"bool\"",
")"
] | If t is of type bool, return it, otherwise raise InvalidTypeError. | [
"If",
"t",
"is",
"of",
"type",
"bool",
"return",
"it",
"otherwise",
"raise",
"InvalidTypeError",
"."
] | f7c1f1e8c3a13b90bd775861d374788a8b5677d8 | https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/easy.py#L349-L356 |
249,686 | yuce/pyswip | pyswip/easy.py | getLong | def getLong(t):
"""If t is of type long, return it, otherwise raise InvalidTypeError.
"""
i = c_long()
if PL_get_long(t, byref(i)):
return i.value
else:
raise InvalidTypeError("long") | python | def getLong(t):
i = c_long()
if PL_get_long(t, byref(i)):
return i.value
else:
raise InvalidTypeError("long") | [
"def",
"getLong",
"(",
"t",
")",
":",
"i",
"=",
"c_long",
"(",
")",
"if",
"PL_get_long",
"(",
"t",
",",
"byref",
"(",
"i",
")",
")",
":",
"return",
"i",
".",
"value",
"else",
":",
"raise",
"InvalidTypeError",
"(",
"\"long\"",
")"
] | If t is of type long, return it, otherwise raise InvalidTypeError. | [
"If",
"t",
"is",
"of",
"type",
"long",
"return",
"it",
"otherwise",
"raise",
"InvalidTypeError",
"."
] | f7c1f1e8c3a13b90bd775861d374788a8b5677d8 | https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/easy.py#L359-L366 |
249,687 | yuce/pyswip | pyswip/easy.py | getFloat | def getFloat(t):
"""If t is of type float, return it, otherwise raise InvalidTypeError.
"""
d = c_double()
if PL_get_float(t, byref(d)):
return d.value
else:
raise InvalidTypeError("float") | python | def getFloat(t):
d = c_double()
if PL_get_float(t, byref(d)):
return d.value
else:
raise InvalidTypeError("float") | [
"def",
"getFloat",
"(",
"t",
")",
":",
"d",
"=",
"c_double",
"(",
")",
"if",
"PL_get_float",
"(",
"t",
",",
"byref",
"(",
"d",
")",
")",
":",
"return",
"d",
".",
"value",
"else",
":",
"raise",
"InvalidTypeError",
"(",
"\"float\"",
")"
] | If t is of type float, return it, otherwise raise InvalidTypeError. | [
"If",
"t",
"is",
"of",
"type",
"float",
"return",
"it",
"otherwise",
"raise",
"InvalidTypeError",
"."
] | f7c1f1e8c3a13b90bd775861d374788a8b5677d8 | https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/easy.py#L372-L379 |
249,688 | yuce/pyswip | pyswip/easy.py | getString | def getString(t):
"""If t is of type string, return it, otherwise raise InvalidTypeError.
"""
slen = c_int()
s = c_char_p()
if PL_get_string_chars(t, byref(s), byref(slen)):
return s.value
else:
raise InvalidTypeError("string") | python | def getString(t):
slen = c_int()
s = c_char_p()
if PL_get_string_chars(t, byref(s), byref(slen)):
return s.value
else:
raise InvalidTypeError("string") | [
"def",
"getString",
"(",
"t",
")",
":",
"slen",
"=",
"c_int",
"(",
")",
"s",
"=",
"c_char_p",
"(",
")",
"if",
"PL_get_string_chars",
"(",
"t",
",",
"byref",
"(",
"s",
")",
",",
"byref",
"(",
"slen",
")",
")",
":",
"return",
"s",
".",
"value",
"else",
":",
"raise",
"InvalidTypeError",
"(",
"\"string\"",
")"
] | If t is of type string, return it, otherwise raise InvalidTypeError. | [
"If",
"t",
"is",
"of",
"type",
"string",
"return",
"it",
"otherwise",
"raise",
"InvalidTypeError",
"."
] | f7c1f1e8c3a13b90bd775861d374788a8b5677d8 | https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/easy.py#L382-L390 |
249,689 | yuce/pyswip | pyswip/easy.py | getList | def getList(x):
"""
Return t as a list.
"""
t = PL_copy_term_ref(x)
head = PL_new_term_ref()
result = []
while PL_get_list(t, head, t):
result.append(getTerm(head))
head = PL_new_term_ref()
return result | python | def getList(x):
t = PL_copy_term_ref(x)
head = PL_new_term_ref()
result = []
while PL_get_list(t, head, t):
result.append(getTerm(head))
head = PL_new_term_ref()
return result | [
"def",
"getList",
"(",
"x",
")",
":",
"t",
"=",
"PL_copy_term_ref",
"(",
"x",
")",
"head",
"=",
"PL_new_term_ref",
"(",
")",
"result",
"=",
"[",
"]",
"while",
"PL_get_list",
"(",
"t",
",",
"head",
",",
"t",
")",
":",
"result",
".",
"append",
"(",
"getTerm",
"(",
"head",
")",
")",
"head",
"=",
"PL_new_term_ref",
"(",
")",
"return",
"result"
] | Return t as a list. | [
"Return",
"t",
"as",
"a",
"list",
"."
] | f7c1f1e8c3a13b90bd775861d374788a8b5677d8 | https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/easy.py#L411-L423 |
249,690 | yuce/pyswip | pyswip/easy.py | Atom.fromTerm | def fromTerm(cls, term):
"""Create an atom from a Term or term handle."""
if isinstance(term, Term):
term = term.handle
elif not isinstance(term, (c_void_p, int)):
raise ArgumentTypeError((str(Term), str(c_void_p)), str(type(term)))
a = atom_t()
if PL_get_atom(term, byref(a)):
return cls(a.value) | python | def fromTerm(cls, term):
if isinstance(term, Term):
term = term.handle
elif not isinstance(term, (c_void_p, int)):
raise ArgumentTypeError((str(Term), str(c_void_p)), str(type(term)))
a = atom_t()
if PL_get_atom(term, byref(a)):
return cls(a.value) | [
"def",
"fromTerm",
"(",
"cls",
",",
"term",
")",
":",
"if",
"isinstance",
"(",
"term",
",",
"Term",
")",
":",
"term",
"=",
"term",
".",
"handle",
"elif",
"not",
"isinstance",
"(",
"term",
",",
"(",
"c_void_p",
",",
"int",
")",
")",
":",
"raise",
"ArgumentTypeError",
"(",
"(",
"str",
"(",
"Term",
")",
",",
"str",
"(",
"c_void_p",
")",
")",
",",
"str",
"(",
"type",
"(",
"term",
")",
")",
")",
"a",
"=",
"atom_t",
"(",
")",
"if",
"PL_get_atom",
"(",
"term",
",",
"byref",
"(",
"a",
")",
")",
":",
"return",
"cls",
"(",
"a",
".",
"value",
")"
] | Create an atom from a Term or term handle. | [
"Create",
"an",
"atom",
"from",
"a",
"Term",
"or",
"term",
"handle",
"."
] | f7c1f1e8c3a13b90bd775861d374788a8b5677d8 | https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/easy.py#L62-L72 |
249,691 | yuce/pyswip | pyswip/easy.py | Functor.fromTerm | def fromTerm(cls, term):
"""Create a functor from a Term or term handle."""
if isinstance(term, Term):
term = term.handle
elif not isinstance(term, (c_void_p, int)):
raise ArgumentTypeError((str(Term), str(int)), str(type(term)))
f = functor_t()
if PL_get_functor(term, byref(f)):
# get args
args = []
arity = PL_functor_arity(f.value)
# let's have all args be consecutive
a0 = PL_new_term_refs(arity)
for i, a in enumerate(range(1, arity + 1)):
if PL_get_arg(a, term, a0 + i):
args.append(getTerm(a0 + i))
return cls(f.value, args=args, a0=a0) | python | def fromTerm(cls, term):
if isinstance(term, Term):
term = term.handle
elif not isinstance(term, (c_void_p, int)):
raise ArgumentTypeError((str(Term), str(int)), str(type(term)))
f = functor_t()
if PL_get_functor(term, byref(f)):
# get args
args = []
arity = PL_functor_arity(f.value)
# let's have all args be consecutive
a0 = PL_new_term_refs(arity)
for i, a in enumerate(range(1, arity + 1)):
if PL_get_arg(a, term, a0 + i):
args.append(getTerm(a0 + i))
return cls(f.value, args=args, a0=a0) | [
"def",
"fromTerm",
"(",
"cls",
",",
"term",
")",
":",
"if",
"isinstance",
"(",
"term",
",",
"Term",
")",
":",
"term",
"=",
"term",
".",
"handle",
"elif",
"not",
"isinstance",
"(",
"term",
",",
"(",
"c_void_p",
",",
"int",
")",
")",
":",
"raise",
"ArgumentTypeError",
"(",
"(",
"str",
"(",
"Term",
")",
",",
"str",
"(",
"int",
")",
")",
",",
"str",
"(",
"type",
"(",
"term",
")",
")",
")",
"f",
"=",
"functor_t",
"(",
")",
"if",
"PL_get_functor",
"(",
"term",
",",
"byref",
"(",
"f",
")",
")",
":",
"# get args",
"args",
"=",
"[",
"]",
"arity",
"=",
"PL_functor_arity",
"(",
"f",
".",
"value",
")",
"# let's have all args be consecutive",
"a0",
"=",
"PL_new_term_refs",
"(",
"arity",
")",
"for",
"i",
",",
"a",
"in",
"enumerate",
"(",
"range",
"(",
"1",
",",
"arity",
"+",
"1",
")",
")",
":",
"if",
"PL_get_arg",
"(",
"a",
",",
"term",
",",
"a0",
"+",
"i",
")",
":",
"args",
".",
"append",
"(",
"getTerm",
"(",
"a0",
"+",
"i",
")",
")",
"return",
"cls",
"(",
"f",
".",
"value",
",",
"args",
"=",
"args",
",",
"a0",
"=",
"a0",
")"
] | Create a functor from a Term or term handle. | [
"Create",
"a",
"functor",
"from",
"a",
"Term",
"or",
"term",
"handle",
"."
] | f7c1f1e8c3a13b90bd775861d374788a8b5677d8 | https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/easy.py#L235-L254 |
249,692 | yuce/pyswip | pyswip/core.py | _findSwiplWin | def _findSwiplWin():
import re
"""
This function uses several heuristics to gues where SWI-Prolog is installed
in Windows. It always returns None as the path of the resource file because,
in Windows, the way to find it is more robust so the SWI-Prolog DLL is
always able to find it.
:returns:
A tuple of (path to the swipl DLL, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
dllNames = ('swipl.dll', 'libswipl.dll')
# First try: check the usual installation path (this is faster but
# hardcoded)
programFiles = os.getenv('ProgramFiles')
paths = [os.path.join(programFiles, r'pl\bin', dllName)
for dllName in dllNames]
for path in paths:
if os.path.exists(path):
return (path, None)
# Second try: use the find_library
path = _findSwiplPathFromFindLib()
if path is not None and os.path.exists(path):
return (path, None)
# Third try: use reg.exe to find the installation path in the registry
# (reg should be installed in all Windows XPs)
try:
cmd = Popen(['reg', 'query',
r'HKEY_LOCAL_MACHINE\Software\SWI\Prolog',
'/v', 'home'], stdout=PIPE)
ret = cmd.communicate()
# Result is like:
# ! REG.EXE VERSION 3.0
#
# HKEY_LOCAL_MACHINE\Software\SWI\Prolog
# home REG_SZ C:\Program Files\pl
# (Note: spaces may be \t or spaces in the output)
ret = ret[0].splitlines()
ret = [line.decode("utf-8") for line in ret if len(line) > 0]
pattern = re.compile('[^h]*home[^R]*REG_SZ( |\t)*(.*)$')
match = pattern.match(ret[-1])
if match is not None:
path = match.group(2)
paths = [os.path.join(path, 'bin', dllName)
for dllName in dllNames]
for path in paths:
if os.path.exists(path):
return (path, None)
except OSError:
# reg.exe not found? Weird...
pass
# May the exec is on path?
(path, swiHome) = _findSwiplFromExec()
if path is not None:
return (path, swiHome)
# Last try: maybe it is in the current dir
for dllName in dllNames:
if os.path.exists(dllName):
return (dllName, None)
return (None, None) | python | def _findSwiplWin():
import re
dllNames = ('swipl.dll', 'libswipl.dll')
# First try: check the usual installation path (this is faster but
# hardcoded)
programFiles = os.getenv('ProgramFiles')
paths = [os.path.join(programFiles, r'pl\bin', dllName)
for dllName in dllNames]
for path in paths:
if os.path.exists(path):
return (path, None)
# Second try: use the find_library
path = _findSwiplPathFromFindLib()
if path is not None and os.path.exists(path):
return (path, None)
# Third try: use reg.exe to find the installation path in the registry
# (reg should be installed in all Windows XPs)
try:
cmd = Popen(['reg', 'query',
r'HKEY_LOCAL_MACHINE\Software\SWI\Prolog',
'/v', 'home'], stdout=PIPE)
ret = cmd.communicate()
# Result is like:
# ! REG.EXE VERSION 3.0
#
# HKEY_LOCAL_MACHINE\Software\SWI\Prolog
# home REG_SZ C:\Program Files\pl
# (Note: spaces may be \t or spaces in the output)
ret = ret[0].splitlines()
ret = [line.decode("utf-8") for line in ret if len(line) > 0]
pattern = re.compile('[^h]*home[^R]*REG_SZ( |\t)*(.*)$')
match = pattern.match(ret[-1])
if match is not None:
path = match.group(2)
paths = [os.path.join(path, 'bin', dllName)
for dllName in dllNames]
for path in paths:
if os.path.exists(path):
return (path, None)
except OSError:
# reg.exe not found? Weird...
pass
# May the exec is on path?
(path, swiHome) = _findSwiplFromExec()
if path is not None:
return (path, swiHome)
# Last try: maybe it is in the current dir
for dllName in dllNames:
if os.path.exists(dllName):
return (dllName, None)
return (None, None) | [
"def",
"_findSwiplWin",
"(",
")",
":",
"import",
"re",
"dllNames",
"=",
"(",
"'swipl.dll'",
",",
"'libswipl.dll'",
")",
"# First try: check the usual installation path (this is faster but",
"# hardcoded)",
"programFiles",
"=",
"os",
".",
"getenv",
"(",
"'ProgramFiles'",
")",
"paths",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"programFiles",
",",
"r'pl\\bin'",
",",
"dllName",
")",
"for",
"dllName",
"in",
"dllNames",
"]",
"for",
"path",
"in",
"paths",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"return",
"(",
"path",
",",
"None",
")",
"# Second try: use the find_library",
"path",
"=",
"_findSwiplPathFromFindLib",
"(",
")",
"if",
"path",
"is",
"not",
"None",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"return",
"(",
"path",
",",
"None",
")",
"# Third try: use reg.exe to find the installation path in the registry",
"# (reg should be installed in all Windows XPs)",
"try",
":",
"cmd",
"=",
"Popen",
"(",
"[",
"'reg'",
",",
"'query'",
",",
"r'HKEY_LOCAL_MACHINE\\Software\\SWI\\Prolog'",
",",
"'/v'",
",",
"'home'",
"]",
",",
"stdout",
"=",
"PIPE",
")",
"ret",
"=",
"cmd",
".",
"communicate",
"(",
")",
"# Result is like:",
"# ! REG.EXE VERSION 3.0",
"#",
"# HKEY_LOCAL_MACHINE\\Software\\SWI\\Prolog",
"# home REG_SZ C:\\Program Files\\pl",
"# (Note: spaces may be \\t or spaces in the output)",
"ret",
"=",
"ret",
"[",
"0",
"]",
".",
"splitlines",
"(",
")",
"ret",
"=",
"[",
"line",
".",
"decode",
"(",
"\"utf-8\"",
")",
"for",
"line",
"in",
"ret",
"if",
"len",
"(",
"line",
")",
">",
"0",
"]",
"pattern",
"=",
"re",
".",
"compile",
"(",
"'[^h]*home[^R]*REG_SZ( |\\t)*(.*)$'",
")",
"match",
"=",
"pattern",
".",
"match",
"(",
"ret",
"[",
"-",
"1",
"]",
")",
"if",
"match",
"is",
"not",
"None",
":",
"path",
"=",
"match",
".",
"group",
"(",
"2",
")",
"paths",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'bin'",
",",
"dllName",
")",
"for",
"dllName",
"in",
"dllNames",
"]",
"for",
"path",
"in",
"paths",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"return",
"(",
"path",
",",
"None",
")",
"except",
"OSError",
":",
"# reg.exe not found? Weird...",
"pass",
"# May the exec is on path?",
"(",
"path",
",",
"swiHome",
")",
"=",
"_findSwiplFromExec",
"(",
")",
"if",
"path",
"is",
"not",
"None",
":",
"return",
"(",
"path",
",",
"swiHome",
")",
"# Last try: maybe it is in the current dir",
"for",
"dllName",
"in",
"dllNames",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"dllName",
")",
":",
"return",
"(",
"dllName",
",",
"None",
")",
"return",
"(",
"None",
",",
"None",
")"
] | This function uses several heuristics to gues where SWI-Prolog is installed
in Windows. It always returns None as the path of the resource file because,
in Windows, the way to find it is more robust so the SWI-Prolog DLL is
always able to find it.
:returns:
A tuple of (path to the swipl DLL, path to the resource file)
:returns type:
({str, None}, {str, None}) | [
"This",
"function",
"uses",
"several",
"heuristics",
"to",
"gues",
"where",
"SWI",
"-",
"Prolog",
"is",
"installed",
"in",
"Windows",
".",
"It",
"always",
"returns",
"None",
"as",
"the",
"path",
"of",
"the",
"resource",
"file",
"because",
"in",
"Windows",
"the",
"way",
"to",
"find",
"it",
"is",
"more",
"robust",
"so",
"the",
"SWI",
"-",
"Prolog",
"DLL",
"is",
"always",
"able",
"to",
"find",
"it",
"."
] | f7c1f1e8c3a13b90bd775861d374788a8b5677d8 | https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/core.py#L159-L232 |
249,693 | yuce/pyswip | pyswip/core.py | _findSwiplLin | def _findSwiplLin():
"""
This function uses several heuristics to guess where SWI-Prolog is
installed in Linuxes.
:returns:
A tuple of (path to the swipl so, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
# Maybe the exec is on path?
(path, swiHome) = _findSwiplFromExec()
if path is not None:
return (path, swiHome)
# If it is not, use find_library
path = _findSwiplPathFromFindLib()
if path is not None:
return (path, swiHome)
# Our last try: some hardcoded paths.
paths = ['/lib', '/usr/lib', '/usr/local/lib', '.', './lib']
names = ['libswipl.so', 'libpl.so']
path = None
for name in names:
for try_ in paths:
try_ = os.path.join(try_, name)
if os.path.exists(try_):
path = try_
break
if path is not None:
return (path, swiHome)
return (None, None) | python | def _findSwiplLin():
# Maybe the exec is on path?
(path, swiHome) = _findSwiplFromExec()
if path is not None:
return (path, swiHome)
# If it is not, use find_library
path = _findSwiplPathFromFindLib()
if path is not None:
return (path, swiHome)
# Our last try: some hardcoded paths.
paths = ['/lib', '/usr/lib', '/usr/local/lib', '.', './lib']
names = ['libswipl.so', 'libpl.so']
path = None
for name in names:
for try_ in paths:
try_ = os.path.join(try_, name)
if os.path.exists(try_):
path = try_
break
if path is not None:
return (path, swiHome)
return (None, None) | [
"def",
"_findSwiplLin",
"(",
")",
":",
"# Maybe the exec is on path?",
"(",
"path",
",",
"swiHome",
")",
"=",
"_findSwiplFromExec",
"(",
")",
"if",
"path",
"is",
"not",
"None",
":",
"return",
"(",
"path",
",",
"swiHome",
")",
"# If it is not, use find_library",
"path",
"=",
"_findSwiplPathFromFindLib",
"(",
")",
"if",
"path",
"is",
"not",
"None",
":",
"return",
"(",
"path",
",",
"swiHome",
")",
"# Our last try: some hardcoded paths.",
"paths",
"=",
"[",
"'/lib'",
",",
"'/usr/lib'",
",",
"'/usr/local/lib'",
",",
"'.'",
",",
"'./lib'",
"]",
"names",
"=",
"[",
"'libswipl.so'",
",",
"'libpl.so'",
"]",
"path",
"=",
"None",
"for",
"name",
"in",
"names",
":",
"for",
"try_",
"in",
"paths",
":",
"try_",
"=",
"os",
".",
"path",
".",
"join",
"(",
"try_",
",",
"name",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"try_",
")",
":",
"path",
"=",
"try_",
"break",
"if",
"path",
"is",
"not",
"None",
":",
"return",
"(",
"path",
",",
"swiHome",
")",
"return",
"(",
"None",
",",
"None",
")"
] | This function uses several heuristics to guess where SWI-Prolog is
installed in Linuxes.
:returns:
A tuple of (path to the swipl so, path to the resource file)
:returns type:
({str, None}, {str, None}) | [
"This",
"function",
"uses",
"several",
"heuristics",
"to",
"guess",
"where",
"SWI",
"-",
"Prolog",
"is",
"installed",
"in",
"Linuxes",
"."
] | f7c1f1e8c3a13b90bd775861d374788a8b5677d8 | https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/core.py#L234-L271 |
249,694 | yuce/pyswip | pyswip/core.py | _findSwiplDar | def _findSwiplDar():
"""
This function uses several heuristics to guess where SWI-Prolog is
installed in MacOS.
:returns:
A tuple of (path to the swipl so, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
# If the exec is in path
(path, swiHome) = _findSwiplFromExec()
if path is not None:
return (path, swiHome)
# If it is not, use find_library
path = _findSwiplPathFromFindLib()
if path is not None:
return (path, swiHome)
# Last guess, searching for the file
paths = ['.', './lib', '/usr/lib/', '/usr/local/lib', '/opt/local/lib']
names = ['libswipl.dylib', 'libpl.dylib']
for name in names:
for path in paths:
path = os.path.join(path, name)
if os.path.exists(path):
return (path, None)
return (None, None) | python | def _findSwiplDar():
# If the exec is in path
(path, swiHome) = _findSwiplFromExec()
if path is not None:
return (path, swiHome)
# If it is not, use find_library
path = _findSwiplPathFromFindLib()
if path is not None:
return (path, swiHome)
# Last guess, searching for the file
paths = ['.', './lib', '/usr/lib/', '/usr/local/lib', '/opt/local/lib']
names = ['libswipl.dylib', 'libpl.dylib']
for name in names:
for path in paths:
path = os.path.join(path, name)
if os.path.exists(path):
return (path, None)
return (None, None) | [
"def",
"_findSwiplDar",
"(",
")",
":",
"# If the exec is in path",
"(",
"path",
",",
"swiHome",
")",
"=",
"_findSwiplFromExec",
"(",
")",
"if",
"path",
"is",
"not",
"None",
":",
"return",
"(",
"path",
",",
"swiHome",
")",
"# If it is not, use find_library",
"path",
"=",
"_findSwiplPathFromFindLib",
"(",
")",
"if",
"path",
"is",
"not",
"None",
":",
"return",
"(",
"path",
",",
"swiHome",
")",
"# Last guess, searching for the file",
"paths",
"=",
"[",
"'.'",
",",
"'./lib'",
",",
"'/usr/lib/'",
",",
"'/usr/local/lib'",
",",
"'/opt/local/lib'",
"]",
"names",
"=",
"[",
"'libswipl.dylib'",
",",
"'libpl.dylib'",
"]",
"for",
"name",
"in",
"names",
":",
"for",
"path",
"in",
"paths",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"name",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"return",
"(",
"path",
",",
"None",
")",
"return",
"(",
"None",
",",
"None",
")"
] | This function uses several heuristics to guess where SWI-Prolog is
installed in MacOS.
:returns:
A tuple of (path to the swipl so, path to the resource file)
:returns type:
({str, None}, {str, None}) | [
"This",
"function",
"uses",
"several",
"heuristics",
"to",
"guess",
"where",
"SWI",
"-",
"Prolog",
"is",
"installed",
"in",
"MacOS",
"."
] | f7c1f1e8c3a13b90bd775861d374788a8b5677d8 | https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/core.py#L358-L390 |
249,695 | yuce/pyswip | pyswip/core.py | _fixWindowsPath | def _fixWindowsPath(dll):
"""
When the path to the DLL is not in Windows search path, Windows will not be
able to find other DLLs on the same directory, so we have to add it to the
path. This function takes care of it.
:parameters:
- `dll` (str) - File name of the DLL
"""
if sys.platform[:3] != 'win':
return # Nothing to do here
pathToDll = os.path.dirname(dll)
currentWindowsPath = os.getenv('PATH')
if pathToDll not in currentWindowsPath:
# We will prepend the path, to avoid conflicts between DLLs
newPath = pathToDll + ';' + currentWindowsPath
os.putenv('PATH', newPath) | python | def _fixWindowsPath(dll):
if sys.platform[:3] != 'win':
return # Nothing to do here
pathToDll = os.path.dirname(dll)
currentWindowsPath = os.getenv('PATH')
if pathToDll not in currentWindowsPath:
# We will prepend the path, to avoid conflicts between DLLs
newPath = pathToDll + ';' + currentWindowsPath
os.putenv('PATH', newPath) | [
"def",
"_fixWindowsPath",
"(",
"dll",
")",
":",
"if",
"sys",
".",
"platform",
"[",
":",
"3",
"]",
"!=",
"'win'",
":",
"return",
"# Nothing to do here",
"pathToDll",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"dll",
")",
"currentWindowsPath",
"=",
"os",
".",
"getenv",
"(",
"'PATH'",
")",
"if",
"pathToDll",
"not",
"in",
"currentWindowsPath",
":",
"# We will prepend the path, to avoid conflicts between DLLs",
"newPath",
"=",
"pathToDll",
"+",
"';'",
"+",
"currentWindowsPath",
"os",
".",
"putenv",
"(",
"'PATH'",
",",
"newPath",
")"
] | When the path to the DLL is not in Windows search path, Windows will not be
able to find other DLLs on the same directory, so we have to add it to the
path. This function takes care of it.
:parameters:
- `dll` (str) - File name of the DLL | [
"When",
"the",
"path",
"to",
"the",
"DLL",
"is",
"not",
"in",
"Windows",
"search",
"path",
"Windows",
"will",
"not",
"be",
"able",
"to",
"find",
"other",
"DLLs",
"on",
"the",
"same",
"directory",
"so",
"we",
"have",
"to",
"add",
"it",
"to",
"the",
"path",
".",
"This",
"function",
"takes",
"care",
"of",
"it",
"."
] | f7c1f1e8c3a13b90bd775861d374788a8b5677d8 | https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/core.py#L435-L454 |
249,696 | yuce/pyswip | pyswip/core.py | list_to_bytes_list | def list_to_bytes_list(strList):
"""
This function turns an array of strings into a pointer array
with pointers pointing to the encodings of those strings
Possibly contained bytes are kept as they are.
:param strList: List of strings that shall be converted
:type strList: List of strings
:returns: Pointer array with pointers pointing to bytes
:raises: TypeError if strList is not list, set or tuple
"""
pList = c_char_p * len(strList)
# if strList is already a pointerarray or None, there is nothing to do
if isinstance(strList, (pList, type(None))):
return strList
if not isinstance(strList, (list, set, tuple)):
raise TypeError("strList must be list, set or tuple, not " +
str(type(strList)))
pList = pList()
for i, elem in enumerate(strList):
pList[i] = str_to_bytes(elem)
return pList | python | def list_to_bytes_list(strList):
pList = c_char_p * len(strList)
# if strList is already a pointerarray or None, there is nothing to do
if isinstance(strList, (pList, type(None))):
return strList
if not isinstance(strList, (list, set, tuple)):
raise TypeError("strList must be list, set or tuple, not " +
str(type(strList)))
pList = pList()
for i, elem in enumerate(strList):
pList[i] = str_to_bytes(elem)
return pList | [
"def",
"list_to_bytes_list",
"(",
"strList",
")",
":",
"pList",
"=",
"c_char_p",
"*",
"len",
"(",
"strList",
")",
"# if strList is already a pointerarray or None, there is nothing to do",
"if",
"isinstance",
"(",
"strList",
",",
"(",
"pList",
",",
"type",
"(",
"None",
")",
")",
")",
":",
"return",
"strList",
"if",
"not",
"isinstance",
"(",
"strList",
",",
"(",
"list",
",",
"set",
",",
"tuple",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"strList must be list, set or tuple, not \"",
"+",
"str",
"(",
"type",
"(",
"strList",
")",
")",
")",
"pList",
"=",
"pList",
"(",
")",
"for",
"i",
",",
"elem",
"in",
"enumerate",
"(",
"strList",
")",
":",
"pList",
"[",
"i",
"]",
"=",
"str_to_bytes",
"(",
"elem",
")",
"return",
"pList"
] | This function turns an array of strings into a pointer array
with pointers pointing to the encodings of those strings
Possibly contained bytes are kept as they are.
:param strList: List of strings that shall be converted
:type strList: List of strings
:returns: Pointer array with pointers pointing to bytes
:raises: TypeError if strList is not list, set or tuple | [
"This",
"function",
"turns",
"an",
"array",
"of",
"strings",
"into",
"a",
"pointer",
"array",
"with",
"pointers",
"pointing",
"to",
"the",
"encodings",
"of",
"those",
"strings",
"Possibly",
"contained",
"bytes",
"are",
"kept",
"as",
"they",
"are",
"."
] | f7c1f1e8c3a13b90bd775861d374788a8b5677d8 | https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/core.py#L478-L502 |
249,697 | yuce/pyswip | pyswip/core.py | check_strings | def check_strings(strings, arrays):
"""
Decorator function which can be used to automatically turn an incoming
string into a bytes object and an incoming list to a pointer array if
necessary.
:param strings: Indices of the arguments must be pointers to bytes
:type strings: List of integers
:param arrays: Indices of the arguments must be arrays of pointers to bytes
:type arrays: List of integers
"""
# if given a single element, turn it into a list
if isinstance(strings, int):
strings = [strings]
elif strings is None:
strings = []
# check if all entries are integers
for i,k in enumerate(strings):
if not isinstance(k, int):
raise TypeError(('Wrong type for index at {0} '+
'in strings. Must be int, not {1}!').format(i,k))
# if given a single element, turn it into a list
if isinstance(arrays, int):
arrays = [arrays]
elif arrays is None:
arrays = []
# check if all entries are integers
for i,k in enumerate(arrays):
if not isinstance(k, int):
raise TypeError(('Wrong type for index at {0} '+
'in arrays. Must be int, not {1}!').format(i,k))
# check if some index occurs in both
if set(strings).intersection(arrays):
raise ValueError('One or more elements occur in both arrays and ' +
' strings. One parameter cannot be both list and string!')
# create the checker that will check all arguments given by argsToCheck
# and turn them into the right datatype.
def checker(func):
def check_and_call(*args):
args = list(args)
for i in strings:
arg = args[i]
args[i] = str_to_bytes(arg)
for i in arrays:
arg = args[i]
args[i] = list_to_bytes_list(arg)
return func(*args)
return check_and_call
return checker | python | def check_strings(strings, arrays):
# if given a single element, turn it into a list
if isinstance(strings, int):
strings = [strings]
elif strings is None:
strings = []
# check if all entries are integers
for i,k in enumerate(strings):
if not isinstance(k, int):
raise TypeError(('Wrong type for index at {0} '+
'in strings. Must be int, not {1}!').format(i,k))
# if given a single element, turn it into a list
if isinstance(arrays, int):
arrays = [arrays]
elif arrays is None:
arrays = []
# check if all entries are integers
for i,k in enumerate(arrays):
if not isinstance(k, int):
raise TypeError(('Wrong type for index at {0} '+
'in arrays. Must be int, not {1}!').format(i,k))
# check if some index occurs in both
if set(strings).intersection(arrays):
raise ValueError('One or more elements occur in both arrays and ' +
' strings. One parameter cannot be both list and string!')
# create the checker that will check all arguments given by argsToCheck
# and turn them into the right datatype.
def checker(func):
def check_and_call(*args):
args = list(args)
for i in strings:
arg = args[i]
args[i] = str_to_bytes(arg)
for i in arrays:
arg = args[i]
args[i] = list_to_bytes_list(arg)
return func(*args)
return check_and_call
return checker | [
"def",
"check_strings",
"(",
"strings",
",",
"arrays",
")",
":",
"# if given a single element, turn it into a list",
"if",
"isinstance",
"(",
"strings",
",",
"int",
")",
":",
"strings",
"=",
"[",
"strings",
"]",
"elif",
"strings",
"is",
"None",
":",
"strings",
"=",
"[",
"]",
"# check if all entries are integers",
"for",
"i",
",",
"k",
"in",
"enumerate",
"(",
"strings",
")",
":",
"if",
"not",
"isinstance",
"(",
"k",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"(",
"'Wrong type for index at {0} '",
"+",
"'in strings. Must be int, not {1}!'",
")",
".",
"format",
"(",
"i",
",",
"k",
")",
")",
"# if given a single element, turn it into a list",
"if",
"isinstance",
"(",
"arrays",
",",
"int",
")",
":",
"arrays",
"=",
"[",
"arrays",
"]",
"elif",
"arrays",
"is",
"None",
":",
"arrays",
"=",
"[",
"]",
"# check if all entries are integers",
"for",
"i",
",",
"k",
"in",
"enumerate",
"(",
"arrays",
")",
":",
"if",
"not",
"isinstance",
"(",
"k",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"(",
"'Wrong type for index at {0} '",
"+",
"'in arrays. Must be int, not {1}!'",
")",
".",
"format",
"(",
"i",
",",
"k",
")",
")",
"# check if some index occurs in both",
"if",
"set",
"(",
"strings",
")",
".",
"intersection",
"(",
"arrays",
")",
":",
"raise",
"ValueError",
"(",
"'One or more elements occur in both arrays and '",
"+",
"' strings. One parameter cannot be both list and string!'",
")",
"# create the checker that will check all arguments given by argsToCheck",
"# and turn them into the right datatype.",
"def",
"checker",
"(",
"func",
")",
":",
"def",
"check_and_call",
"(",
"*",
"args",
")",
":",
"args",
"=",
"list",
"(",
"args",
")",
"for",
"i",
"in",
"strings",
":",
"arg",
"=",
"args",
"[",
"i",
"]",
"args",
"[",
"i",
"]",
"=",
"str_to_bytes",
"(",
"arg",
")",
"for",
"i",
"in",
"arrays",
":",
"arg",
"=",
"args",
"[",
"i",
"]",
"args",
"[",
"i",
"]",
"=",
"list_to_bytes_list",
"(",
"arg",
")",
"return",
"func",
"(",
"*",
"args",
")",
"return",
"check_and_call",
"return",
"checker"
] | Decorator function which can be used to automatically turn an incoming
string into a bytes object and an incoming list to a pointer array if
necessary.
:param strings: Indices of the arguments must be pointers to bytes
:type strings: List of integers
:param arrays: Indices of the arguments must be arrays of pointers to bytes
:type arrays: List of integers | [
"Decorator",
"function",
"which",
"can",
"be",
"used",
"to",
"automatically",
"turn",
"an",
"incoming",
"string",
"into",
"a",
"bytes",
"object",
"and",
"an",
"incoming",
"list",
"to",
"a",
"pointer",
"array",
"if",
"necessary",
"."
] | f7c1f1e8c3a13b90bd775861d374788a8b5677d8 | https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/core.py#L506-L563 |
249,698 | hazelcast/hazelcast-python-client | hazelcast/proxy/queue.py | Queue.add | def add(self, item):
"""
Adds the specified item to this queue if there is available space.
:param item: (object), the specified item.
:return: (bool), ``true`` if element is successfully added, ``false`` otherwise.
"""
def result_fnc(f):
if f.result():
return True
raise Full("Queue is full!")
return self.offer(item).continue_with(result_fnc) | python | def add(self, item):
def result_fnc(f):
if f.result():
return True
raise Full("Queue is full!")
return self.offer(item).continue_with(result_fnc) | [
"def",
"add",
"(",
"self",
",",
"item",
")",
":",
"def",
"result_fnc",
"(",
"f",
")",
":",
"if",
"f",
".",
"result",
"(",
")",
":",
"return",
"True",
"raise",
"Full",
"(",
"\"Queue is full!\"",
")",
"return",
"self",
".",
"offer",
"(",
"item",
")",
".",
"continue_with",
"(",
"result_fnc",
")"
] | Adds the specified item to this queue if there is available space.
:param item: (object), the specified item.
:return: (bool), ``true`` if element is successfully added, ``false`` otherwise. | [
"Adds",
"the",
"specified",
"item",
"to",
"this",
"queue",
"if",
"there",
"is",
"available",
"space",
"."
] | 3f6639443c23d6d036aa343f8e094f052250d2c1 | https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/queue.py#L39-L51 |
249,699 | hazelcast/hazelcast-python-client | hazelcast/proxy/queue.py | Queue.add_all | def add_all(self, items):
"""
Adds the elements in the specified collection to this queue.
:param items: (Collection), collection which includes the items to be added.
:return: (bool), ``true`` if this queue is changed after call, ``false`` otherwise.
"""
check_not_none(items, "Value can't be None")
data_items = []
for item in items:
check_not_none(item, "Value can't be None")
data_items.append(self._to_data(item))
return self._encode_invoke(queue_add_all_codec, data_list=data_items) | python | def add_all(self, items):
check_not_none(items, "Value can't be None")
data_items = []
for item in items:
check_not_none(item, "Value can't be None")
data_items.append(self._to_data(item))
return self._encode_invoke(queue_add_all_codec, data_list=data_items) | [
"def",
"add_all",
"(",
"self",
",",
"items",
")",
":",
"check_not_none",
"(",
"items",
",",
"\"Value can't be None\"",
")",
"data_items",
"=",
"[",
"]",
"for",
"item",
"in",
"items",
":",
"check_not_none",
"(",
"item",
",",
"\"Value can't be None\"",
")",
"data_items",
".",
"append",
"(",
"self",
".",
"_to_data",
"(",
"item",
")",
")",
"return",
"self",
".",
"_encode_invoke",
"(",
"queue_add_all_codec",
",",
"data_list",
"=",
"data_items",
")"
] | Adds the elements in the specified collection to this queue.
:param items: (Collection), collection which includes the items to be added.
:return: (bool), ``true`` if this queue is changed after call, ``false`` otherwise. | [
"Adds",
"the",
"elements",
"in",
"the",
"specified",
"collection",
"to",
"this",
"queue",
"."
] | 3f6639443c23d6d036aa343f8e094f052250d2c1 | https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/queue.py#L53-L65 |
Subsets and Splits