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
75
19.8k
code_tokens
sequencelengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
sequencelengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
docstring_summary
stringclasses
1 value
parameters
stringclasses
1 value
return_statement
stringclasses
1 value
argument_list
stringclasses
1 value
identifier
stringclasses
1 value
nwo
stringclasses
1 value
score
float32
-1
-1
251,600
dranjan/python-plyfile
plyfile.py
PlyProperty._read_bin
def _read_bin(self, stream, byte_order): ''' Read data from a binary stream. Raise StopIteration if the property could not be read. ''' try: return _read_array(stream, self.dtype(byte_order), 1)[0] except IndexError: raise StopIteration
python
def _read_bin(self, stream, byte_order): ''' Read data from a binary stream. Raise StopIteration if the property could not be read. ''' try: return _read_array(stream, self.dtype(byte_order), 1)[0] except IndexError: raise StopIteration
[ "def", "_read_bin", "(", "self", ",", "stream", ",", "byte_order", ")", ":", "try", ":", "return", "_read_array", "(", "stream", ",", "self", ".", "dtype", "(", "byte_order", ")", ",", "1", ")", "[", "0", "]", "except", "IndexError", ":", "raise", "StopIteration" ]
Read data from a binary stream. Raise StopIteration if the property could not be read.
[ "Read", "data", "from", "a", "binary", "stream", ".", "Raise", "StopIteration", "if", "the", "property", "could", "not", "be", "read", "." ]
9f8e8708d3a071229cf292caae7d13264e11c88b
https://github.com/dranjan/python-plyfile/blob/9f8e8708d3a071229cf292caae7d13264e11c88b/plyfile.py#L841-L850
-1
251,601
99designs/colorific
colorific/palette.py
color_stream_st
def color_stream_st(istream=sys.stdin, save_palette=False, **kwargs): """ Read filenames from the input stream and detect their palette. """ for line in istream: filename = line.strip() try: palette = extract_colors(filename, **kwargs) except Exception as e: print(filename, e, file=sys.stderr) continue print_colors(filename, palette) if save_palette: save_palette_as_image(filename, palette)
python
def color_stream_st(istream=sys.stdin, save_palette=False, **kwargs): """ Read filenames from the input stream and detect their palette. """ for line in istream: filename = line.strip() try: palette = extract_colors(filename, **kwargs) except Exception as e: print(filename, e, file=sys.stderr) continue print_colors(filename, palette) if save_palette: save_palette_as_image(filename, palette)
[ "def", "color_stream_st", "(", "istream", "=", "sys", ".", "stdin", ",", "save_palette", "=", "False", ",", "*", "*", "kwargs", ")", ":", "for", "line", "in", "istream", ":", "filename", "=", "line", ".", "strip", "(", ")", "try", ":", "palette", "=", "extract_colors", "(", "filename", ",", "*", "*", "kwargs", ")", "except", "Exception", "as", "e", ":", "print", "(", "filename", ",", "e", ",", "file", "=", "sys", ".", "stderr", ")", "continue", "print_colors", "(", "filename", ",", "palette", ")", "if", "save_palette", ":", "save_palette_as_image", "(", "filename", ",", "palette", ")" ]
Read filenames from the input stream and detect their palette.
[ "Read", "filenames", "from", "the", "input", "stream", "and", "detect", "their", "palette", "." ]
f83e59f61295500f5527dee5894207f2f033cf35
https://github.com/99designs/colorific/blob/f83e59f61295500f5527dee5894207f2f033cf35/colorific/palette.py#L37-L52
-1
251,602
99designs/colorific
colorific/palette.py
color_stream_mt
def color_stream_mt(istream=sys.stdin, n=config.N_PROCESSES, **kwargs): """ Read filenames from the input stream and detect their palette using multiple processes. """ queue = multiprocessing.Queue(1000) lock = multiprocessing.Lock() pool = [multiprocessing.Process(target=color_process, args=(queue, lock), kwargs=kwargs) for i in range(n)] for p in pool: p.start() block = [] for line in istream: block.append(line.strip()) if len(block) == config.BLOCK_SIZE: queue.put(block) block = [] if block: queue.put(block) for i in range(n): queue.put(config.SENTINEL) for p in pool: p.join()
python
def color_stream_mt(istream=sys.stdin, n=config.N_PROCESSES, **kwargs): """ Read filenames from the input stream and detect their palette using multiple processes. """ queue = multiprocessing.Queue(1000) lock = multiprocessing.Lock() pool = [multiprocessing.Process(target=color_process, args=(queue, lock), kwargs=kwargs) for i in range(n)] for p in pool: p.start() block = [] for line in istream: block.append(line.strip()) if len(block) == config.BLOCK_SIZE: queue.put(block) block = [] if block: queue.put(block) for i in range(n): queue.put(config.SENTINEL) for p in pool: p.join()
[ "def", "color_stream_mt", "(", "istream", "=", "sys", ".", "stdin", ",", "n", "=", "config", ".", "N_PROCESSES", ",", "*", "*", "kwargs", ")", ":", "queue", "=", "multiprocessing", ".", "Queue", "(", "1000", ")", "lock", "=", "multiprocessing", ".", "Lock", "(", ")", "pool", "=", "[", "multiprocessing", ".", "Process", "(", "target", "=", "color_process", ",", "args", "=", "(", "queue", ",", "lock", ")", ",", "kwargs", "=", "kwargs", ")", "for", "i", "in", "range", "(", "n", ")", "]", "for", "p", "in", "pool", ":", "p", ".", "start", "(", ")", "block", "=", "[", "]", "for", "line", "in", "istream", ":", "block", ".", "append", "(", "line", ".", "strip", "(", ")", ")", "if", "len", "(", "block", ")", "==", "config", ".", "BLOCK_SIZE", ":", "queue", ".", "put", "(", "block", ")", "block", "=", "[", "]", "if", "block", ":", "queue", ".", "put", "(", "block", ")", "for", "i", "in", "range", "(", "n", ")", ":", "queue", ".", "put", "(", "config", ".", "SENTINEL", ")", "for", "p", "in", "pool", ":", "p", ".", "join", "(", ")" ]
Read filenames from the input stream and detect their palette using multiple processes.
[ "Read", "filenames", "from", "the", "input", "stream", "and", "detect", "their", "palette", "using", "multiple", "processes", "." ]
f83e59f61295500f5527dee5894207f2f033cf35
https://github.com/99designs/colorific/blob/f83e59f61295500f5527dee5894207f2f033cf35/colorific/palette.py#L55-L81
-1
251,603
99designs/colorific
colorific/palette.py
color_process
def color_process(queue, lock): "Receive filenames and get the colors from their images." while True: block = queue.get() if block == config.SENTINEL: break for filename in block: try: palette = extract_colors(filename) except: # TODO: it's too broad exception. continue lock.acquire() try: print_colors(filename, palette) finally: lock.release()
python
def color_process(queue, lock): "Receive filenames and get the colors from their images." while True: block = queue.get() if block == config.SENTINEL: break for filename in block: try: palette = extract_colors(filename) except: # TODO: it's too broad exception. continue lock.acquire() try: print_colors(filename, palette) finally: lock.release()
[ "def", "color_process", "(", "queue", ",", "lock", ")", ":", "while", "True", ":", "block", "=", "queue", ".", "get", "(", ")", "if", "block", "==", "config", ".", "SENTINEL", ":", "break", "for", "filename", "in", "block", ":", "try", ":", "palette", "=", "extract_colors", "(", "filename", ")", "except", ":", "# TODO: it's too broad exception.", "continue", "lock", ".", "acquire", "(", ")", "try", ":", "print_colors", "(", "filename", ",", "palette", ")", "finally", ":", "lock", ".", "release", "(", ")" ]
Receive filenames and get the colors from their images.
[ "Receive", "filenames", "and", "get", "the", "colors", "from", "their", "images", "." ]
f83e59f61295500f5527dee5894207f2f033cf35
https://github.com/99designs/colorific/blob/f83e59f61295500f5527dee5894207f2f033cf35/colorific/palette.py#L84-L100
-1
251,604
99designs/colorific
colorific/palette.py
extract_colors
def extract_colors( filename_or_img, min_saturation=config.MIN_SATURATION, min_distance=config.MIN_DISTANCE, max_colors=config.MAX_COLORS, min_prominence=config.MIN_PROMINENCE, n_quantized=config.N_QUANTIZED): """ Determine what the major colors are in the given image. """ if Image.isImageType(filename_or_img): im = filename_or_img else: im = Image.open(filename_or_img) # get point color count if im.mode != 'RGB': im = im.convert('RGB') im = autocrop(im, config.WHITE) # assume white box im = im.convert( 'P', palette=Image.ADAPTIVE, colors=n_quantized).convert('RGB') dist = Counter({color: count for count, color in im.getcolors(n_quantized)}) n_pixels = mul(*im.size) # aggregate colors to_canonical = {config.WHITE: config.WHITE, config.BLACK: config.BLACK} aggregated = Counter({config.WHITE: 0, config.BLACK: 0}) sorted_cols = sorted(dist.items(), key=itemgetter(1), reverse=True) for c, n in sorted_cols: if c in aggregated: # exact match! aggregated[c] += n else: d, nearest = min((distance(c, alt), alt) for alt in aggregated) if d < min_distance: # nearby match aggregated[nearest] += n to_canonical[c] = nearest else: # no nearby match aggregated[c] = n to_canonical[c] = c # order by prominence colors = sorted( [Color(c, n / float(n_pixels)) for c, n in aggregated.items()], key=attrgetter('prominence'), reverse=True) colors, bg_color = detect_background(im, colors, to_canonical) # keep any color which meets the minimum saturation sat_colors = [c for c in colors if meets_min_saturation(c, min_saturation)] if bg_color and not meets_min_saturation(bg_color, min_saturation): bg_color = None if sat_colors: colors = sat_colors else: # keep at least one color colors = colors[:1] # keep any color within 10% of the majority color color_list = [] color_count = 0 for color in colors: if color.prominence >= colors[0].prominence * min_prominence: color_list.append(color) color_count += 1 if color_count >= max_colors: break return Palette(color_list, bg_color)
python
def extract_colors( filename_or_img, min_saturation=config.MIN_SATURATION, min_distance=config.MIN_DISTANCE, max_colors=config.MAX_COLORS, min_prominence=config.MIN_PROMINENCE, n_quantized=config.N_QUANTIZED): """ Determine what the major colors are in the given image. """ if Image.isImageType(filename_or_img): im = filename_or_img else: im = Image.open(filename_or_img) # get point color count if im.mode != 'RGB': im = im.convert('RGB') im = autocrop(im, config.WHITE) # assume white box im = im.convert( 'P', palette=Image.ADAPTIVE, colors=n_quantized).convert('RGB') dist = Counter({color: count for count, color in im.getcolors(n_quantized)}) n_pixels = mul(*im.size) # aggregate colors to_canonical = {config.WHITE: config.WHITE, config.BLACK: config.BLACK} aggregated = Counter({config.WHITE: 0, config.BLACK: 0}) sorted_cols = sorted(dist.items(), key=itemgetter(1), reverse=True) for c, n in sorted_cols: if c in aggregated: # exact match! aggregated[c] += n else: d, nearest = min((distance(c, alt), alt) for alt in aggregated) if d < min_distance: # nearby match aggregated[nearest] += n to_canonical[c] = nearest else: # no nearby match aggregated[c] = n to_canonical[c] = c # order by prominence colors = sorted( [Color(c, n / float(n_pixels)) for c, n in aggregated.items()], key=attrgetter('prominence'), reverse=True) colors, bg_color = detect_background(im, colors, to_canonical) # keep any color which meets the minimum saturation sat_colors = [c for c in colors if meets_min_saturation(c, min_saturation)] if bg_color and not meets_min_saturation(bg_color, min_saturation): bg_color = None if sat_colors: colors = sat_colors else: # keep at least one color colors = colors[:1] # keep any color within 10% of the majority color color_list = [] color_count = 0 for color in colors: if color.prominence >= colors[0].prominence * min_prominence: color_list.append(color) color_count += 1 if color_count >= max_colors: break return Palette(color_list, bg_color)
[ "def", "extract_colors", "(", "filename_or_img", ",", "min_saturation", "=", "config", ".", "MIN_SATURATION", ",", "min_distance", "=", "config", ".", "MIN_DISTANCE", ",", "max_colors", "=", "config", ".", "MAX_COLORS", ",", "min_prominence", "=", "config", ".", "MIN_PROMINENCE", ",", "n_quantized", "=", "config", ".", "N_QUANTIZED", ")", ":", "if", "Image", ".", "isImageType", "(", "filename_or_img", ")", ":", "im", "=", "filename_or_img", "else", ":", "im", "=", "Image", ".", "open", "(", "filename_or_img", ")", "# get point color count", "if", "im", ".", "mode", "!=", "'RGB'", ":", "im", "=", "im", ".", "convert", "(", "'RGB'", ")", "im", "=", "autocrop", "(", "im", ",", "config", ".", "WHITE", ")", "# assume white box", "im", "=", "im", ".", "convert", "(", "'P'", ",", "palette", "=", "Image", ".", "ADAPTIVE", ",", "colors", "=", "n_quantized", ")", ".", "convert", "(", "'RGB'", ")", "dist", "=", "Counter", "(", "{", "color", ":", "count", "for", "count", ",", "color", "in", "im", ".", "getcolors", "(", "n_quantized", ")", "}", ")", "n_pixels", "=", "mul", "(", "*", "im", ".", "size", ")", "# aggregate colors", "to_canonical", "=", "{", "config", ".", "WHITE", ":", "config", ".", "WHITE", ",", "config", ".", "BLACK", ":", "config", ".", "BLACK", "}", "aggregated", "=", "Counter", "(", "{", "config", ".", "WHITE", ":", "0", ",", "config", ".", "BLACK", ":", "0", "}", ")", "sorted_cols", "=", "sorted", "(", "dist", ".", "items", "(", ")", ",", "key", "=", "itemgetter", "(", "1", ")", ",", "reverse", "=", "True", ")", "for", "c", ",", "n", "in", "sorted_cols", ":", "if", "c", "in", "aggregated", ":", "# exact match!", "aggregated", "[", "c", "]", "+=", "n", "else", ":", "d", ",", "nearest", "=", "min", "(", "(", "distance", "(", "c", ",", "alt", ")", ",", "alt", ")", "for", "alt", "in", "aggregated", ")", "if", "d", "<", "min_distance", ":", "# nearby match", "aggregated", "[", "nearest", "]", "+=", "n", "to_canonical", "[", "c", "]", "=", "nearest", "else", ":", "# no nearby match", "aggregated", "[", "c", "]", "=", "n", "to_canonical", "[", "c", "]", "=", "c", "# order by prominence", "colors", "=", "sorted", "(", "[", "Color", "(", "c", ",", "n", "/", "float", "(", "n_pixels", ")", ")", "for", "c", ",", "n", "in", "aggregated", ".", "items", "(", ")", "]", ",", "key", "=", "attrgetter", "(", "'prominence'", ")", ",", "reverse", "=", "True", ")", "colors", ",", "bg_color", "=", "detect_background", "(", "im", ",", "colors", ",", "to_canonical", ")", "# keep any color which meets the minimum saturation", "sat_colors", "=", "[", "c", "for", "c", "in", "colors", "if", "meets_min_saturation", "(", "c", ",", "min_saturation", ")", "]", "if", "bg_color", "and", "not", "meets_min_saturation", "(", "bg_color", ",", "min_saturation", ")", ":", "bg_color", "=", "None", "if", "sat_colors", ":", "colors", "=", "sat_colors", "else", ":", "# keep at least one color", "colors", "=", "colors", "[", ":", "1", "]", "# keep any color within 10% of the majority color", "color_list", "=", "[", "]", "color_count", "=", "0", "for", "color", "in", "colors", ":", "if", "color", ".", "prominence", ">=", "colors", "[", "0", "]", ".", "prominence", "*", "min_prominence", ":", "color_list", ".", "append", "(", "color", ")", "color_count", "+=", "1", "if", "color_count", ">=", "max_colors", ":", "break", "return", "Palette", "(", "color_list", ",", "bg_color", ")" ]
Determine what the major colors are in the given image.
[ "Determine", "what", "the", "major", "colors", "are", "in", "the", "given", "image", "." ]
f83e59f61295500f5527dee5894207f2f033cf35
https://github.com/99designs/colorific/blob/f83e59f61295500f5527dee5894207f2f033cf35/colorific/palette.py#L124-L194
-1
251,605
99designs/colorific
colorific/palette.py
save_palette_as_image
def save_palette_as_image(filename, palette): "Save palette as a PNG with labeled, colored blocks" output_filename = '%s_palette.png' % filename[:filename.rfind('.')] size = (80 * len(palette.colors), 80) im = Image.new('RGB', size) draw = ImageDraw.Draw(im) for i, c in enumerate(palette.colors): v = colorsys.rgb_to_hsv(*norm_color(c.value))[2] (x1, y1) = (i * 80, 0) (x2, y2) = ((i + 1) * 80 - 1, 79) draw.rectangle([(x1, y1), (x2, y2)], fill=c.value) if v < 0.6: # white with shadow draw.text((x1 + 4, y1 + 4), rgb_to_hex(c.value), (90, 90, 90)) draw.text((x1 + 3, y1 + 3), rgb_to_hex(c.value)) else: # dark with bright "shadow" draw.text((x1 + 4, y1 + 4), rgb_to_hex(c.value), (230, 230, 230)) draw.text((x1 + 3, y1 + 3), rgb_to_hex(c.value), (0, 0, 0)) im.save(output_filename, "PNG")
python
def save_palette_as_image(filename, palette): "Save palette as a PNG with labeled, colored blocks" output_filename = '%s_palette.png' % filename[:filename.rfind('.')] size = (80 * len(palette.colors), 80) im = Image.new('RGB', size) draw = ImageDraw.Draw(im) for i, c in enumerate(palette.colors): v = colorsys.rgb_to_hsv(*norm_color(c.value))[2] (x1, y1) = (i * 80, 0) (x2, y2) = ((i + 1) * 80 - 1, 79) draw.rectangle([(x1, y1), (x2, y2)], fill=c.value) if v < 0.6: # white with shadow draw.text((x1 + 4, y1 + 4), rgb_to_hex(c.value), (90, 90, 90)) draw.text((x1 + 3, y1 + 3), rgb_to_hex(c.value)) else: # dark with bright "shadow" draw.text((x1 + 4, y1 + 4), rgb_to_hex(c.value), (230, 230, 230)) draw.text((x1 + 3, y1 + 3), rgb_to_hex(c.value), (0, 0, 0)) im.save(output_filename, "PNG")
[ "def", "save_palette_as_image", "(", "filename", ",", "palette", ")", ":", "output_filename", "=", "'%s_palette.png'", "%", "filename", "[", ":", "filename", ".", "rfind", "(", "'.'", ")", "]", "size", "=", "(", "80", "*", "len", "(", "palette", ".", "colors", ")", ",", "80", ")", "im", "=", "Image", ".", "new", "(", "'RGB'", ",", "size", ")", "draw", "=", "ImageDraw", ".", "Draw", "(", "im", ")", "for", "i", ",", "c", "in", "enumerate", "(", "palette", ".", "colors", ")", ":", "v", "=", "colorsys", ".", "rgb_to_hsv", "(", "*", "norm_color", "(", "c", ".", "value", ")", ")", "[", "2", "]", "(", "x1", ",", "y1", ")", "=", "(", "i", "*", "80", ",", "0", ")", "(", "x2", ",", "y2", ")", "=", "(", "(", "i", "+", "1", ")", "*", "80", "-", "1", ",", "79", ")", "draw", ".", "rectangle", "(", "[", "(", "x1", ",", "y1", ")", ",", "(", "x2", ",", "y2", ")", "]", ",", "fill", "=", "c", ".", "value", ")", "if", "v", "<", "0.6", ":", "# white with shadow", "draw", ".", "text", "(", "(", "x1", "+", "4", ",", "y1", "+", "4", ")", ",", "rgb_to_hex", "(", "c", ".", "value", ")", ",", "(", "90", ",", "90", ",", "90", ")", ")", "draw", ".", "text", "(", "(", "x1", "+", "3", ",", "y1", "+", "3", ")", ",", "rgb_to_hex", "(", "c", ".", "value", ")", ")", "else", ":", "# dark with bright \"shadow\"", "draw", ".", "text", "(", "(", "x1", "+", "4", ",", "y1", "+", "4", ")", ",", "rgb_to_hex", "(", "c", ".", "value", ")", ",", "(", "230", ",", "230", ",", "230", ")", ")", "draw", ".", "text", "(", "(", "x1", "+", "3", ",", "y1", "+", "3", ")", ",", "rgb_to_hex", "(", "c", ".", "value", ")", ",", "(", "0", ",", "0", ",", "0", ")", ")", "im", ".", "save", "(", "output_filename", ",", "\"PNG\"", ")" ]
Save palette as a PNG with labeled, colored blocks
[ "Save", "palette", "as", "a", "PNG", "with", "labeled", "colored", "blocks" ]
f83e59f61295500f5527dee5894207f2f033cf35
https://github.com/99designs/colorific/blob/f83e59f61295500f5527dee5894207f2f033cf35/colorific/palette.py#L235-L255
-1
251,606
99designs/colorific
colorific/palette.py
autocrop
def autocrop(im, bgcolor): "Crop away a border of the given background color." if im.mode != "RGB": im = im.convert("RGB") bg = Image.new("RGB", im.size, bgcolor) diff = ImageChops.difference(im, bg) bbox = diff.getbbox() if bbox: return im.crop(bbox) return im
python
def autocrop(im, bgcolor): "Crop away a border of the given background color." if im.mode != "RGB": im = im.convert("RGB") bg = Image.new("RGB", im.size, bgcolor) diff = ImageChops.difference(im, bg) bbox = diff.getbbox() if bbox: return im.crop(bbox) return im
[ "def", "autocrop", "(", "im", ",", "bgcolor", ")", ":", "if", "im", ".", "mode", "!=", "\"RGB\"", ":", "im", "=", "im", ".", "convert", "(", "\"RGB\"", ")", "bg", "=", "Image", ".", "new", "(", "\"RGB\"", ",", "im", ".", "size", ",", "bgcolor", ")", "diff", "=", "ImageChops", ".", "difference", "(", "im", ",", "bg", ")", "bbox", "=", "diff", ".", "getbbox", "(", ")", "if", "bbox", ":", "return", "im", ".", "crop", "(", "bbox", ")", "return", "im" ]
Crop away a border of the given background color.
[ "Crop", "away", "a", "border", "of", "the", "given", "background", "color", "." ]
f83e59f61295500f5527dee5894207f2f033cf35
https://github.com/99designs/colorific/blob/f83e59f61295500f5527dee5894207f2f033cf35/colorific/palette.py#L262-L272
-1
251,607
ttu/ruuvitag-sensor
examples/post_to_influxdb.py
convert_to_influx
def convert_to_influx(mac, payload): ''' Convert data into RuuviCollector naming schme and scale returns: Object to be written to InfluxDB ''' dataFormat = payload["data_format"] if ('data_format' in payload) else None fields = {} fields["temperature"] = payload["temperature"] if ('temperature' in payload) else None fields["humidity"] = payload["humidity"] if ('humidity' in payload) else None fields["pressure"] = payload["pressure"] if ('pressure' in payload) else None fields["accelerationX"] = payload["acceleration_x"] if ('acceleration_x' in payload) else None fields["accelerationY"] = payload["acceleration_y"] if ('acceleration_y' in payload) else None fields["accelerationZ"] = payload["acceleration_z"] if ('acceleration_z' in payload) else None fields["batteryVoltage"] = payload["battery"]/1000.0 if ('battery' in payload) else None fields["txPower"] = payload["tx_power"] if ('tx_power' in payload) else None fields["movementCounter"] = payload["movement_counter"] if ('movement_counter' in payload) else None fields["measurementSequenceNumber"] = payload["measurement_sequence_number"] if ('measurement_sequence_number' in payload) else None fields["tagID"] = payload["tagID"] if ('tagID' in payload) else None fields["rssi"] = payload["rssi"] if ('rssi' in payload) else None return { "measurement": "ruuvi_measurements", "tags": { "mac": mac, "dataFormat": dataFormat }, "fields": fields }
python
def convert_to_influx(mac, payload): ''' Convert data into RuuviCollector naming schme and scale returns: Object to be written to InfluxDB ''' dataFormat = payload["data_format"] if ('data_format' in payload) else None fields = {} fields["temperature"] = payload["temperature"] if ('temperature' in payload) else None fields["humidity"] = payload["humidity"] if ('humidity' in payload) else None fields["pressure"] = payload["pressure"] if ('pressure' in payload) else None fields["accelerationX"] = payload["acceleration_x"] if ('acceleration_x' in payload) else None fields["accelerationY"] = payload["acceleration_y"] if ('acceleration_y' in payload) else None fields["accelerationZ"] = payload["acceleration_z"] if ('acceleration_z' in payload) else None fields["batteryVoltage"] = payload["battery"]/1000.0 if ('battery' in payload) else None fields["txPower"] = payload["tx_power"] if ('tx_power' in payload) else None fields["movementCounter"] = payload["movement_counter"] if ('movement_counter' in payload) else None fields["measurementSequenceNumber"] = payload["measurement_sequence_number"] if ('measurement_sequence_number' in payload) else None fields["tagID"] = payload["tagID"] if ('tagID' in payload) else None fields["rssi"] = payload["rssi"] if ('rssi' in payload) else None return { "measurement": "ruuvi_measurements", "tags": { "mac": mac, "dataFormat": dataFormat }, "fields": fields }
[ "def", "convert_to_influx", "(", "mac", ",", "payload", ")", ":", "dataFormat", "=", "payload", "[", "\"data_format\"", "]", "if", "(", "'data_format'", "in", "payload", ")", "else", "None", "fields", "=", "{", "}", "fields", "[", "\"temperature\"", "]", "=", "payload", "[", "\"temperature\"", "]", "if", "(", "'temperature'", "in", "payload", ")", "else", "None", "fields", "[", "\"humidity\"", "]", "=", "payload", "[", "\"humidity\"", "]", "if", "(", "'humidity'", "in", "payload", ")", "else", "None", "fields", "[", "\"pressure\"", "]", "=", "payload", "[", "\"pressure\"", "]", "if", "(", "'pressure'", "in", "payload", ")", "else", "None", "fields", "[", "\"accelerationX\"", "]", "=", "payload", "[", "\"acceleration_x\"", "]", "if", "(", "'acceleration_x'", "in", "payload", ")", "else", "None", "fields", "[", "\"accelerationY\"", "]", "=", "payload", "[", "\"acceleration_y\"", "]", "if", "(", "'acceleration_y'", "in", "payload", ")", "else", "None", "fields", "[", "\"accelerationZ\"", "]", "=", "payload", "[", "\"acceleration_z\"", "]", "if", "(", "'acceleration_z'", "in", "payload", ")", "else", "None", "fields", "[", "\"batteryVoltage\"", "]", "=", "payload", "[", "\"battery\"", "]", "/", "1000.0", "if", "(", "'battery'", "in", "payload", ")", "else", "None", "fields", "[", "\"txPower\"", "]", "=", "payload", "[", "\"tx_power\"", "]", "if", "(", "'tx_power'", "in", "payload", ")", "else", "None", "fields", "[", "\"movementCounter\"", "]", "=", "payload", "[", "\"movement_counter\"", "]", "if", "(", "'movement_counter'", "in", "payload", ")", "else", "None", "fields", "[", "\"measurementSequenceNumber\"", "]", "=", "payload", "[", "\"measurement_sequence_number\"", "]", "if", "(", "'measurement_sequence_number'", "in", "payload", ")", "else", "None", "fields", "[", "\"tagID\"", "]", "=", "payload", "[", "\"tagID\"", "]", "if", "(", "'tagID'", "in", "payload", ")", "else", "None", "fields", "[", "\"rssi\"", "]", "=", "payload", "[", "\"rssi\"", "]", "if", "(", "'rssi'", "in", "payload", ")", "else", "None", "return", "{", "\"measurement\"", ":", "\"ruuvi_measurements\"", ",", "\"tags\"", ":", "{", "\"mac\"", ":", "mac", ",", "\"dataFormat\"", ":", "dataFormat", "}", ",", "\"fields\"", ":", "fields", "}" ]
Convert data into RuuviCollector naming schme and scale returns: Object to be written to InfluxDB
[ "Convert", "data", "into", "RuuviCollector", "naming", "schme", "and", "scale" ]
b5d1367c26844ae5875b2964c68e7b2f4e1cb082
https://github.com/ttu/ruuvitag-sensor/blob/b5d1367c26844ae5875b2964c68e7b2f4e1cb082/examples/post_to_influxdb.py#L35-L63
-1
251,608
ttu/ruuvitag-sensor
ruuvitag_sensor/ruuvi_rx.py
_run_get_data_background
def _run_get_data_background(macs, queue, shared_data, bt_device): """ Background process function for RuuviTag Sensors """ run_flag = RunFlag() def add_data(data): if not shared_data['run_flag']: run_flag.running = False data[1]['time'] = datetime.utcnow().isoformat() queue.put(data) RuuviTagSensor.get_datas(add_data, macs, run_flag, bt_device)
python
def _run_get_data_background(macs, queue, shared_data, bt_device): """ Background process function for RuuviTag Sensors """ run_flag = RunFlag() def add_data(data): if not shared_data['run_flag']: run_flag.running = False data[1]['time'] = datetime.utcnow().isoformat() queue.put(data) RuuviTagSensor.get_datas(add_data, macs, run_flag, bt_device)
[ "def", "_run_get_data_background", "(", "macs", ",", "queue", ",", "shared_data", ",", "bt_device", ")", ":", "run_flag", "=", "RunFlag", "(", ")", "def", "add_data", "(", "data", ")", ":", "if", "not", "shared_data", "[", "'run_flag'", "]", ":", "run_flag", ".", "running", "=", "False", "data", "[", "1", "]", "[", "'time'", "]", "=", "datetime", ".", "utcnow", "(", ")", ".", "isoformat", "(", ")", "queue", ".", "put", "(", "data", ")", "RuuviTagSensor", ".", "get_datas", "(", "add_data", ",", "macs", ",", "run_flag", ",", "bt_device", ")" ]
Background process function for RuuviTag Sensors
[ "Background", "process", "function", "for", "RuuviTag", "Sensors" ]
b5d1367c26844ae5875b2964c68e7b2f4e1cb082
https://github.com/ttu/ruuvitag-sensor/blob/b5d1367c26844ae5875b2964c68e7b2f4e1cb082/ruuvitag_sensor/ruuvi_rx.py#L11-L25
-1
251,609
ttu/ruuvitag-sensor
ruuvitag_sensor/ruuvi_rx.py
RuuviTagReactive._data_update
def _data_update(subjects, queue, run_flag): """ Get data from backgound process and notify all subscribed observers with the new data """ while run_flag.running: while not queue.empty(): data = queue.get() for subject in [s for s in subjects if not s.is_disposed]: subject.on_next(data) time.sleep(0.1)
python
def _data_update(subjects, queue, run_flag): """ Get data from backgound process and notify all subscribed observers with the new data """ while run_flag.running: while not queue.empty(): data = queue.get() for subject in [s for s in subjects if not s.is_disposed]: subject.on_next(data) time.sleep(0.1)
[ "def", "_data_update", "(", "subjects", ",", "queue", ",", "run_flag", ")", ":", "while", "run_flag", ".", "running", ":", "while", "not", "queue", ".", "empty", "(", ")", ":", "data", "=", "queue", ".", "get", "(", ")", "for", "subject", "in", "[", "s", "for", "s", "in", "subjects", "if", "not", "s", ".", "is_disposed", "]", ":", "subject", ".", "on_next", "(", "data", ")", "time", ".", "sleep", "(", "0.1", ")" ]
Get data from backgound process and notify all subscribed observers with the new data
[ "Get", "data", "from", "backgound", "process", "and", "notify", "all", "subscribed", "observers", "with", "the", "new", "data" ]
b5d1367c26844ae5875b2964c68e7b2f4e1cb082
https://github.com/ttu/ruuvitag-sensor/blob/b5d1367c26844ae5875b2964c68e7b2f4e1cb082/ruuvitag_sensor/ruuvi_rx.py#L34-L43
-1
251,610
ttu/ruuvitag-sensor
examples/http_server_asyncio.py
data_update
async def data_update(queue): """ Update data sent by the background process to global allData variable """ global allData while True: while not queue.empty(): data = queue.get() allData[data[0]] = data[1] for key, value in tags.items(): if key in allData: allData[key]['name'] = value await asyncio.sleep(0.5)
python
async def data_update(queue): """ Update data sent by the background process to global allData variable """ global allData while True: while not queue.empty(): data = queue.get() allData[data[0]] = data[1] for key, value in tags.items(): if key in allData: allData[key]['name'] = value await asyncio.sleep(0.5)
[ "async", "def", "data_update", "(", "queue", ")", ":", "global", "allData", "while", "True", ":", "while", "not", "queue", ".", "empty", "(", ")", ":", "data", "=", "queue", ".", "get", "(", ")", "allData", "[", "data", "[", "0", "]", "]", "=", "data", "[", "1", "]", "for", "key", ",", "value", "in", "tags", ".", "items", "(", ")", ":", "if", "key", "in", "allData", ":", "allData", "[", "key", "]", "[", "'name'", "]", "=", "value", "await", "asyncio", ".", "sleep", "(", "0.5", ")" ]
Update data sent by the background process to global allData variable
[ "Update", "data", "sent", "by", "the", "background", "process", "to", "global", "allData", "variable" ]
b5d1367c26844ae5875b2964c68e7b2f4e1cb082
https://github.com/ttu/ruuvitag-sensor/blob/b5d1367c26844ae5875b2964c68e7b2f4e1cb082/examples/http_server_asyncio.py#L36-L48
-1
251,611
ttu/ruuvitag-sensor
ruuvitag_sensor/ruuvi.py
RuuviTagSensor.convert_data
def convert_data(raw): """ Validate that data is from RuuviTag and get correct data part. Returns: tuple (int, string): Data Format type and Sensor data """ # TODO: Check from raw data correct data format # Now this returns 2 also for Data Format 4 data = RuuviTagSensor._get_data_format_2and4(raw) if data is not None: return (2, data) data = RuuviTagSensor._get_data_format_3(raw) if data is not None: return (3, data) data = RuuviTagSensor._get_data_format_5(raw) if data is not None: return (5, data) return (None, None)
python
def convert_data(raw): """ Validate that data is from RuuviTag and get correct data part. Returns: tuple (int, string): Data Format type and Sensor data """ # TODO: Check from raw data correct data format # Now this returns 2 also for Data Format 4 data = RuuviTagSensor._get_data_format_2and4(raw) if data is not None: return (2, data) data = RuuviTagSensor._get_data_format_3(raw) if data is not None: return (3, data) data = RuuviTagSensor._get_data_format_5(raw) if data is not None: return (5, data) return (None, None)
[ "def", "convert_data", "(", "raw", ")", ":", "# TODO: Check from raw data correct data format", "# Now this returns 2 also for Data Format 4", "data", "=", "RuuviTagSensor", ".", "_get_data_format_2and4", "(", "raw", ")", "if", "data", "is", "not", "None", ":", "return", "(", "2", ",", "data", ")", "data", "=", "RuuviTagSensor", ".", "_get_data_format_3", "(", "raw", ")", "if", "data", "is", "not", "None", ":", "return", "(", "3", ",", "data", ")", "data", "=", "RuuviTagSensor", ".", "_get_data_format_5", "(", "raw", ")", "if", "data", "is", "not", "None", ":", "return", "(", "5", ",", "data", ")", "return", "(", "None", ",", "None", ")" ]
Validate that data is from RuuviTag and get correct data part. Returns: tuple (int, string): Data Format type and Sensor data
[ "Validate", "that", "data", "is", "from", "RuuviTag", "and", "get", "correct", "data", "part", "." ]
b5d1367c26844ae5875b2964c68e7b2f4e1cb082
https://github.com/ttu/ruuvitag-sensor/blob/b5d1367c26844ae5875b2964c68e7b2f4e1cb082/ruuvitag_sensor/ruuvi.py#L42-L66
-1
251,612
ttu/ruuvitag-sensor
ruuvitag_sensor/ruuvi.py
RuuviTagSensor.find_ruuvitags
def find_ruuvitags(bt_device=''): """ Find all RuuviTags. Function will print the mac and the state of the sensors when found. Function will execute as long as it is stopped. Stop ecexution with Crtl+C. Returns: dict: MAC and state of found sensors """ log.info('Finding RuuviTags. Stop with Ctrl+C.') datas = dict() for new_data in RuuviTagSensor._get_ruuvitag_datas(bt_device=bt_device): if new_data[0] in datas: continue datas[new_data[0]] = new_data[1] log.info(new_data[0]) log.info(new_data[1]) return datas
python
def find_ruuvitags(bt_device=''): """ Find all RuuviTags. Function will print the mac and the state of the sensors when found. Function will execute as long as it is stopped. Stop ecexution with Crtl+C. Returns: dict: MAC and state of found sensors """ log.info('Finding RuuviTags. Stop with Ctrl+C.') datas = dict() for new_data in RuuviTagSensor._get_ruuvitag_datas(bt_device=bt_device): if new_data[0] in datas: continue datas[new_data[0]] = new_data[1] log.info(new_data[0]) log.info(new_data[1]) return datas
[ "def", "find_ruuvitags", "(", "bt_device", "=", "''", ")", ":", "log", ".", "info", "(", "'Finding RuuviTags. Stop with Ctrl+C.'", ")", "datas", "=", "dict", "(", ")", "for", "new_data", "in", "RuuviTagSensor", ".", "_get_ruuvitag_datas", "(", "bt_device", "=", "bt_device", ")", ":", "if", "new_data", "[", "0", "]", "in", "datas", ":", "continue", "datas", "[", "new_data", "[", "0", "]", "]", "=", "new_data", "[", "1", "]", "log", ".", "info", "(", "new_data", "[", "0", "]", ")", "log", ".", "info", "(", "new_data", "[", "1", "]", ")", "return", "datas" ]
Find all RuuviTags. Function will print the mac and the state of the sensors when found. Function will execute as long as it is stopped. Stop ecexution with Crtl+C. Returns: dict: MAC and state of found sensors
[ "Find", "all", "RuuviTags", ".", "Function", "will", "print", "the", "mac", "and", "the", "state", "of", "the", "sensors", "when", "found", ".", "Function", "will", "execute", "as", "long", "as", "it", "is", "stopped", ".", "Stop", "ecexution", "with", "Crtl", "+", "C", "." ]
b5d1367c26844ae5875b2964c68e7b2f4e1cb082
https://github.com/ttu/ruuvitag-sensor/blob/b5d1367c26844ae5875b2964c68e7b2f4e1cb082/ruuvitag_sensor/ruuvi.py#L69-L88
-1
251,613
ttu/ruuvitag-sensor
ruuvitag_sensor/ruuvi.py
RuuviTagSensor.get_data_for_sensors
def get_data_for_sensors(macs=[], search_duratio_sec=5, bt_device=''): """ Get lates data for sensors in the MAC's list. Args: macs (array): MAC addresses search_duratio_sec (int): Search duration in seconds. Default 5 bt_device (string): Bluetooth device id Returns: dict: MAC and state of found sensors """ log.info('Get latest data for sensors. Stop with Ctrl+C.') log.info('Stops automatically in %ss', search_duratio_sec) log.info('MACs: %s', macs) datas = dict() for new_data in RuuviTagSensor._get_ruuvitag_datas(macs, search_duratio_sec, bt_device=bt_device): datas[new_data[0]] = new_data[1] return datas
python
def get_data_for_sensors(macs=[], search_duratio_sec=5, bt_device=''): """ Get lates data for sensors in the MAC's list. Args: macs (array): MAC addresses search_duratio_sec (int): Search duration in seconds. Default 5 bt_device (string): Bluetooth device id Returns: dict: MAC and state of found sensors """ log.info('Get latest data for sensors. Stop with Ctrl+C.') log.info('Stops automatically in %ss', search_duratio_sec) log.info('MACs: %s', macs) datas = dict() for new_data in RuuviTagSensor._get_ruuvitag_datas(macs, search_duratio_sec, bt_device=bt_device): datas[new_data[0]] = new_data[1] return datas
[ "def", "get_data_for_sensors", "(", "macs", "=", "[", "]", ",", "search_duratio_sec", "=", "5", ",", "bt_device", "=", "''", ")", ":", "log", ".", "info", "(", "'Get latest data for sensors. Stop with Ctrl+C.'", ")", "log", ".", "info", "(", "'Stops automatically in %ss'", ",", "search_duratio_sec", ")", "log", ".", "info", "(", "'MACs: %s'", ",", "macs", ")", "datas", "=", "dict", "(", ")", "for", "new_data", "in", "RuuviTagSensor", ".", "_get_ruuvitag_datas", "(", "macs", ",", "search_duratio_sec", ",", "bt_device", "=", "bt_device", ")", ":", "datas", "[", "new_data", "[", "0", "]", "]", "=", "new_data", "[", "1", "]", "return", "datas" ]
Get lates data for sensors in the MAC's list. Args: macs (array): MAC addresses search_duratio_sec (int): Search duration in seconds. Default 5 bt_device (string): Bluetooth device id Returns: dict: MAC and state of found sensors
[ "Get", "lates", "data", "for", "sensors", "in", "the", "MAC", "s", "list", "." ]
b5d1367c26844ae5875b2964c68e7b2f4e1cb082
https://github.com/ttu/ruuvitag-sensor/blob/b5d1367c26844ae5875b2964c68e7b2f4e1cb082/ruuvitag_sensor/ruuvi.py#L91-L112
-1
251,614
ttu/ruuvitag-sensor
ruuvitag_sensor/ruuvi.py
RuuviTagSensor.get_datas
def get_datas(callback, macs=[], run_flag=RunFlag(), bt_device=''): """ Get data for all ruuvitag sensors or sensors in the MAC's list. Args: callback (func): callback funcion to be called when new data is received macs (list): MAC addresses run_flag (object): RunFlag object. Function executes while run_flag.running bt_device (string): Bluetooth device id """ log.info('Get latest data for sensors. Stop with Ctrl+C.') log.info('MACs: %s', macs) for new_data in RuuviTagSensor._get_ruuvitag_datas(macs, None, run_flag, bt_device): callback(new_data)
python
def get_datas(callback, macs=[], run_flag=RunFlag(), bt_device=''): """ Get data for all ruuvitag sensors or sensors in the MAC's list. Args: callback (func): callback funcion to be called when new data is received macs (list): MAC addresses run_flag (object): RunFlag object. Function executes while run_flag.running bt_device (string): Bluetooth device id """ log.info('Get latest data for sensors. Stop with Ctrl+C.') log.info('MACs: %s', macs) for new_data in RuuviTagSensor._get_ruuvitag_datas(macs, None, run_flag, bt_device): callback(new_data)
[ "def", "get_datas", "(", "callback", ",", "macs", "=", "[", "]", ",", "run_flag", "=", "RunFlag", "(", ")", ",", "bt_device", "=", "''", ")", ":", "log", ".", "info", "(", "'Get latest data for sensors. Stop with Ctrl+C.'", ")", "log", ".", "info", "(", "'MACs: %s'", ",", "macs", ")", "for", "new_data", "in", "RuuviTagSensor", ".", "_get_ruuvitag_datas", "(", "macs", ",", "None", ",", "run_flag", ",", "bt_device", ")", ":", "callback", "(", "new_data", ")" ]
Get data for all ruuvitag sensors or sensors in the MAC's list. Args: callback (func): callback funcion to be called when new data is received macs (list): MAC addresses run_flag (object): RunFlag object. Function executes while run_flag.running bt_device (string): Bluetooth device id
[ "Get", "data", "for", "all", "ruuvitag", "sensors", "or", "sensors", "in", "the", "MAC", "s", "list", "." ]
b5d1367c26844ae5875b2964c68e7b2f4e1cb082
https://github.com/ttu/ruuvitag-sensor/blob/b5d1367c26844ae5875b2964c68e7b2f4e1cb082/ruuvitag_sensor/ruuvi.py#L115-L130
-1
251,615
ttu/ruuvitag-sensor
ruuvitag_sensor/ruuvi.py
RuuviTagSensor._get_ruuvitag_datas
def _get_ruuvitag_datas(macs=[], search_duratio_sec=None, run_flag=RunFlag(), bt_device=''): """ Get data from BluetoothCommunication and handle data encoding. Args: macs (list): MAC addresses. Default empty list search_duratio_sec (int): Search duration in seconds. Default None run_flag (object): RunFlag object. Function executes while run_flag.running. Default new RunFlag bt_device (string): Bluetooth device id Yields: tuple: MAC and State of RuuviTag sensor data """ mac_blacklist = [] start_time = time.time() data_iter = ble.get_datas(mac_blacklist, bt_device) for ble_data in data_iter: # Check duration if search_duratio_sec and time.time() - start_time > search_duratio_sec: data_iter.send(StopIteration) break # Check running flag if not run_flag.running: data_iter.send(StopIteration) break # Check MAC whitelist if macs and not ble_data[0] in macs: continue (data_format, data) = RuuviTagSensor.convert_data(ble_data[1]) # Check that encoded data is valid RuuviTag data and it is sensor data # If data is not valid RuuviTag data add MAC to blacklist if data is not None: state = get_decoder(data_format).decode_data(data) if state is not None: yield (ble_data[0], state) else: mac_blacklist.append(ble_data[0])
python
def _get_ruuvitag_datas(macs=[], search_duratio_sec=None, run_flag=RunFlag(), bt_device=''): """ Get data from BluetoothCommunication and handle data encoding. Args: macs (list): MAC addresses. Default empty list search_duratio_sec (int): Search duration in seconds. Default None run_flag (object): RunFlag object. Function executes while run_flag.running. Default new RunFlag bt_device (string): Bluetooth device id Yields: tuple: MAC and State of RuuviTag sensor data """ mac_blacklist = [] start_time = time.time() data_iter = ble.get_datas(mac_blacklist, bt_device) for ble_data in data_iter: # Check duration if search_duratio_sec and time.time() - start_time > search_duratio_sec: data_iter.send(StopIteration) break # Check running flag if not run_flag.running: data_iter.send(StopIteration) break # Check MAC whitelist if macs and not ble_data[0] in macs: continue (data_format, data) = RuuviTagSensor.convert_data(ble_data[1]) # Check that encoded data is valid RuuviTag data and it is sensor data # If data is not valid RuuviTag data add MAC to blacklist if data is not None: state = get_decoder(data_format).decode_data(data) if state is not None: yield (ble_data[0], state) else: mac_blacklist.append(ble_data[0])
[ "def", "_get_ruuvitag_datas", "(", "macs", "=", "[", "]", ",", "search_duratio_sec", "=", "None", ",", "run_flag", "=", "RunFlag", "(", ")", ",", "bt_device", "=", "''", ")", ":", "mac_blacklist", "=", "[", "]", "start_time", "=", "time", ".", "time", "(", ")", "data_iter", "=", "ble", ".", "get_datas", "(", "mac_blacklist", ",", "bt_device", ")", "for", "ble_data", "in", "data_iter", ":", "# Check duration", "if", "search_duratio_sec", "and", "time", ".", "time", "(", ")", "-", "start_time", ">", "search_duratio_sec", ":", "data_iter", ".", "send", "(", "StopIteration", ")", "break", "# Check running flag", "if", "not", "run_flag", ".", "running", ":", "data_iter", ".", "send", "(", "StopIteration", ")", "break", "# Check MAC whitelist", "if", "macs", "and", "not", "ble_data", "[", "0", "]", "in", "macs", ":", "continue", "(", "data_format", ",", "data", ")", "=", "RuuviTagSensor", ".", "convert_data", "(", "ble_data", "[", "1", "]", ")", "# Check that encoded data is valid RuuviTag data and it is sensor data", "# If data is not valid RuuviTag data add MAC to blacklist", "if", "data", "is", "not", "None", ":", "state", "=", "get_decoder", "(", "data_format", ")", ".", "decode_data", "(", "data", ")", "if", "state", "is", "not", "None", ":", "yield", "(", "ble_data", "[", "0", "]", ",", "state", ")", "else", ":", "mac_blacklist", ".", "append", "(", "ble_data", "[", "0", "]", ")" ]
Get data from BluetoothCommunication and handle data encoding. Args: macs (list): MAC addresses. Default empty list search_duratio_sec (int): Search duration in seconds. Default None run_flag (object): RunFlag object. Function executes while run_flag.running. Default new RunFlag bt_device (string): Bluetooth device id Yields: tuple: MAC and State of RuuviTag sensor data
[ "Get", "data", "from", "BluetoothCommunication", "and", "handle", "data", "encoding", "." ]
b5d1367c26844ae5875b2964c68e7b2f4e1cb082
https://github.com/ttu/ruuvitag-sensor/blob/b5d1367c26844ae5875b2964c68e7b2f4e1cb082/ruuvitag_sensor/ruuvi.py#L133-L170
-1
251,616
ttu/ruuvitag-sensor
ruuvitag_sensor/ruuvitag.py
RuuviTag.update
def update(self): """ Get lates data from the sensor and update own state. Returns: dict: Latest state """ (data_format, data) = RuuviTagSensor.get_data(self._mac, self._bt_device) if data == self._data: return self._state self._data = data if self._data is None: self._state = {} else: self._state = get_decoder(data_format).decode_data(self._data) return self._state
python
def update(self): """ Get lates data from the sensor and update own state. Returns: dict: Latest state """ (data_format, data) = RuuviTagSensor.get_data(self._mac, self._bt_device) if data == self._data: return self._state self._data = data if self._data is None: self._state = {} else: self._state = get_decoder(data_format).decode_data(self._data) return self._state
[ "def", "update", "(", "self", ")", ":", "(", "data_format", ",", "data", ")", "=", "RuuviTagSensor", ".", "get_data", "(", "self", ".", "_mac", ",", "self", ".", "_bt_device", ")", "if", "data", "==", "self", ".", "_data", ":", "return", "self", ".", "_state", "self", ".", "_data", "=", "data", "if", "self", ".", "_data", "is", "None", ":", "self", ".", "_state", "=", "{", "}", "else", ":", "self", ".", "_state", "=", "get_decoder", "(", "data_format", ")", ".", "decode_data", "(", "self", ".", "_data", ")", "return", "self", ".", "_state" ]
Get lates data from the sensor and update own state. Returns: dict: Latest state
[ "Get", "lates", "data", "from", "the", "sensor", "and", "update", "own", "state", "." ]
b5d1367c26844ae5875b2964c68e7b2f4e1cb082
https://github.com/ttu/ruuvitag-sensor/blob/b5d1367c26844ae5875b2964c68e7b2f4e1cb082/ruuvitag_sensor/ruuvitag.py#L32-L52
-1
251,617
ttu/ruuvitag-sensor
examples/post_to_influxdb_rx.py
write_to_influxdb
def write_to_influxdb(received_data): ''' Convert data into RuuviCollecor naming schme and scale ''' dataFormat = received_data[1]["data_format"] if ('data_format' in received_data[1]) else None fields = {} fields["temperature"] = received_data[1]["temperature"] if ('temperature' in received_data[1]) else None fields["humidity"] = received_data[1]["humidity"] if ('humidity' in received_data[1]) else None fields["pressure"] = received_data[1]["pressure"] if ('pressure' in received_data[1]) else None fields["accelerationX"] = received_data[1]["acceleration_x"] if ('acceleration_x' in received_data[1]) else None fields["accelerationY"] = received_data[1]["acceleration_y"] if ('acceleration_y' in received_data[1]) else None fields["accelerationZ"] = received_data[1]["acceleration_z"] if ('acceleration_z' in received_data[1]) else None fields["batteryVoltage"] = received_data[1]["battery"]/1000.0 if ('battery' in received_data[1]) else None fields["txPower"] = received_data[1]["tx_power"] if ('tx_power' in received_data[1]) else None fields["movementCounter"] = received_data[1]["movement_counter"] if ('movement_counter' in received_data[1]) else None fields["measurementSequenceNumber"] = received_data[1]["measurement_sequence_number"] if ('measurement_sequence_number' in received_data[1]) else None fields["tagID"] = received_data[1]["tagID"] if ('tagID' in received_data[1]) else None fields["rssi"] = received_data[1]["rssi"] if ('rssi' in received_data[1]) else None json_body = [ { "measurement": "ruuvi_measurements", "tags": { "mac": received_data[0], "dataFormat": dataFormat }, "fields": fields } ] client.write_points(json_body)
python
def write_to_influxdb(received_data): ''' Convert data into RuuviCollecor naming schme and scale ''' dataFormat = received_data[1]["data_format"] if ('data_format' in received_data[1]) else None fields = {} fields["temperature"] = received_data[1]["temperature"] if ('temperature' in received_data[1]) else None fields["humidity"] = received_data[1]["humidity"] if ('humidity' in received_data[1]) else None fields["pressure"] = received_data[1]["pressure"] if ('pressure' in received_data[1]) else None fields["accelerationX"] = received_data[1]["acceleration_x"] if ('acceleration_x' in received_data[1]) else None fields["accelerationY"] = received_data[1]["acceleration_y"] if ('acceleration_y' in received_data[1]) else None fields["accelerationZ"] = received_data[1]["acceleration_z"] if ('acceleration_z' in received_data[1]) else None fields["batteryVoltage"] = received_data[1]["battery"]/1000.0 if ('battery' in received_data[1]) else None fields["txPower"] = received_data[1]["tx_power"] if ('tx_power' in received_data[1]) else None fields["movementCounter"] = received_data[1]["movement_counter"] if ('movement_counter' in received_data[1]) else None fields["measurementSequenceNumber"] = received_data[1]["measurement_sequence_number"] if ('measurement_sequence_number' in received_data[1]) else None fields["tagID"] = received_data[1]["tagID"] if ('tagID' in received_data[1]) else None fields["rssi"] = received_data[1]["rssi"] if ('rssi' in received_data[1]) else None json_body = [ { "measurement": "ruuvi_measurements", "tags": { "mac": received_data[0], "dataFormat": dataFormat }, "fields": fields } ] client.write_points(json_body)
[ "def", "write_to_influxdb", "(", "received_data", ")", ":", "dataFormat", "=", "received_data", "[", "1", "]", "[", "\"data_format\"", "]", "if", "(", "'data_format'", "in", "received_data", "[", "1", "]", ")", "else", "None", "fields", "=", "{", "}", "fields", "[", "\"temperature\"", "]", "=", "received_data", "[", "1", "]", "[", "\"temperature\"", "]", "if", "(", "'temperature'", "in", "received_data", "[", "1", "]", ")", "else", "None", "fields", "[", "\"humidity\"", "]", "=", "received_data", "[", "1", "]", "[", "\"humidity\"", "]", "if", "(", "'humidity'", "in", "received_data", "[", "1", "]", ")", "else", "None", "fields", "[", "\"pressure\"", "]", "=", "received_data", "[", "1", "]", "[", "\"pressure\"", "]", "if", "(", "'pressure'", "in", "received_data", "[", "1", "]", ")", "else", "None", "fields", "[", "\"accelerationX\"", "]", "=", "received_data", "[", "1", "]", "[", "\"acceleration_x\"", "]", "if", "(", "'acceleration_x'", "in", "received_data", "[", "1", "]", ")", "else", "None", "fields", "[", "\"accelerationY\"", "]", "=", "received_data", "[", "1", "]", "[", "\"acceleration_y\"", "]", "if", "(", "'acceleration_y'", "in", "received_data", "[", "1", "]", ")", "else", "None", "fields", "[", "\"accelerationZ\"", "]", "=", "received_data", "[", "1", "]", "[", "\"acceleration_z\"", "]", "if", "(", "'acceleration_z'", "in", "received_data", "[", "1", "]", ")", "else", "None", "fields", "[", "\"batteryVoltage\"", "]", "=", "received_data", "[", "1", "]", "[", "\"battery\"", "]", "/", "1000.0", "if", "(", "'battery'", "in", "received_data", "[", "1", "]", ")", "else", "None", "fields", "[", "\"txPower\"", "]", "=", "received_data", "[", "1", "]", "[", "\"tx_power\"", "]", "if", "(", "'tx_power'", "in", "received_data", "[", "1", "]", ")", "else", "None", "fields", "[", "\"movementCounter\"", "]", "=", "received_data", "[", "1", "]", "[", "\"movement_counter\"", "]", "if", "(", "'movement_counter'", "in", "received_data", "[", "1", "]", ")", "else", "None", "fields", "[", "\"measurementSequenceNumber\"", "]", "=", "received_data", "[", "1", "]", "[", "\"measurement_sequence_number\"", "]", "if", "(", "'measurement_sequence_number'", "in", "received_data", "[", "1", "]", ")", "else", "None", "fields", "[", "\"tagID\"", "]", "=", "received_data", "[", "1", "]", "[", "\"tagID\"", "]", "if", "(", "'tagID'", "in", "received_data", "[", "1", "]", ")", "else", "None", "fields", "[", "\"rssi\"", "]", "=", "received_data", "[", "1", "]", "[", "\"rssi\"", "]", "if", "(", "'rssi'", "in", "received_data", "[", "1", "]", ")", "else", "None", "json_body", "=", "[", "{", "\"measurement\"", ":", "\"ruuvi_measurements\"", ",", "\"tags\"", ":", "{", "\"mac\"", ":", "received_data", "[", "0", "]", ",", "\"dataFormat\"", ":", "dataFormat", "}", ",", "\"fields\"", ":", "fields", "}", "]", "client", ".", "write_points", "(", "json_body", ")" ]
Convert data into RuuviCollecor naming schme and scale
[ "Convert", "data", "into", "RuuviCollecor", "naming", "schme", "and", "scale" ]
b5d1367c26844ae5875b2964c68e7b2f4e1cb082
https://github.com/ttu/ruuvitag-sensor/blob/b5d1367c26844ae5875b2964c68e7b2f4e1cb082/examples/post_to_influxdb_rx.py#L12-L40
-1
251,618
ttu/ruuvitag-sensor
examples/http_server.py
update_data
def update_data(): """ Update data sent by background process to global allData """ global allData while not q.empty(): allData = q.get() for key, value in tags.items(): if key in allData: allData[key]['name'] = value
python
def update_data(): """ Update data sent by background process to global allData """ global allData while not q.empty(): allData = q.get() for key, value in tags.items(): if key in allData: allData[key]['name'] = value
[ "def", "update_data", "(", ")", ":", "global", "allData", "while", "not", "q", ".", "empty", "(", ")", ":", "allData", "=", "q", ".", "get", "(", ")", "for", "key", ",", "value", "in", "tags", ".", "items", "(", ")", ":", "if", "key", "in", "allData", ":", "allData", "[", "key", "]", "[", "'name'", "]", "=", "value" ]
Update data sent by background process to global allData
[ "Update", "data", "sent", "by", "background", "process", "to", "global", "allData" ]
b5d1367c26844ae5875b2964c68e7b2f4e1cb082
https://github.com/ttu/ruuvitag-sensor/blob/b5d1367c26844ae5875b2964c68e7b2f4e1cb082/examples/http_server.py#L44-L53
-1
251,619
ttu/ruuvitag-sensor
ruuvitag_sensor/decoder.py
Df5Decoder._get_acceleration
def _get_acceleration(self, data): '''Return acceleration mG''' if (data[7:8] == 0x7FFF or data[9:10] == 0x7FFF or data[11:12] == 0x7FFF): return (None, None, None) acc_x = twos_complement((data[7] << 8) + data[8], 16) acc_y = twos_complement((data[9] << 8) + data[10], 16) acc_z = twos_complement((data[11] << 8) + data[12], 16) return (acc_x, acc_y, acc_z)
python
def _get_acceleration(self, data): '''Return acceleration mG''' if (data[7:8] == 0x7FFF or data[9:10] == 0x7FFF or data[11:12] == 0x7FFF): return (None, None, None) acc_x = twos_complement((data[7] << 8) + data[8], 16) acc_y = twos_complement((data[9] << 8) + data[10], 16) acc_z = twos_complement((data[11] << 8) + data[12], 16) return (acc_x, acc_y, acc_z)
[ "def", "_get_acceleration", "(", "self", ",", "data", ")", ":", "if", "(", "data", "[", "7", ":", "8", "]", "==", "0x7FFF", "or", "data", "[", "9", ":", "10", "]", "==", "0x7FFF", "or", "data", "[", "11", ":", "12", "]", "==", "0x7FFF", ")", ":", "return", "(", "None", ",", "None", ",", "None", ")", "acc_x", "=", "twos_complement", "(", "(", "data", "[", "7", "]", "<<", "8", ")", "+", "data", "[", "8", "]", ",", "16", ")", "acc_y", "=", "twos_complement", "(", "(", "data", "[", "9", "]", "<<", "8", ")", "+", "data", "[", "10", "]", ",", "16", ")", "acc_z", "=", "twos_complement", "(", "(", "data", "[", "11", "]", "<<", "8", ")", "+", "data", "[", "12", "]", ",", "16", ")", "return", "(", "acc_x", ",", "acc_y", ",", "acc_z", ")" ]
Return acceleration mG
[ "Return", "acceleration", "mG" ]
b5d1367c26844ae5875b2964c68e7b2f4e1cb082
https://github.com/ttu/ruuvitag-sensor/blob/b5d1367c26844ae5875b2964c68e7b2f4e1cb082/ruuvitag_sensor/decoder.py#L195-L205
-1
251,620
ttu/ruuvitag-sensor
ruuvitag_sensor/decoder.py
Df5Decoder._get_powerinfo
def _get_powerinfo(self, data): '''Return battery voltage and tx power ''' power_info = (data[13] & 0xFF) << 8 | (data[14] & 0xFF) battery_voltage = rshift(power_info, 5) + 1600 tx_power = (power_info & 0b11111) * 2 - 40 if rshift(power_info, 5) == 0b11111111111: battery_voltage = None if (power_info & 0b11111) == 0b11111: tx_power = None return (round(battery_voltage, 3), tx_power)
python
def _get_powerinfo(self, data): '''Return battery voltage and tx power ''' power_info = (data[13] & 0xFF) << 8 | (data[14] & 0xFF) battery_voltage = rshift(power_info, 5) + 1600 tx_power = (power_info & 0b11111) * 2 - 40 if rshift(power_info, 5) == 0b11111111111: battery_voltage = None if (power_info & 0b11111) == 0b11111: tx_power = None return (round(battery_voltage, 3), tx_power)
[ "def", "_get_powerinfo", "(", "self", ",", "data", ")", ":", "power_info", "=", "(", "data", "[", "13", "]", "&", "0xFF", ")", "<<", "8", "|", "(", "data", "[", "14", "]", "&", "0xFF", ")", "battery_voltage", "=", "rshift", "(", "power_info", ",", "5", ")", "+", "1600", "tx_power", "=", "(", "power_info", "&", "0b11111", ")", "*", "2", "-", "40", "if", "rshift", "(", "power_info", ",", "5", ")", "==", "0b11111111111", ":", "battery_voltage", "=", "None", "if", "(", "power_info", "&", "0b11111", ")", "==", "0b11111", ":", "tx_power", "=", "None", "return", "(", "round", "(", "battery_voltage", ",", "3", ")", ",", "tx_power", ")" ]
Return battery voltage and tx power
[ "Return", "battery", "voltage", "and", "tx", "power" ]
b5d1367c26844ae5875b2964c68e7b2f4e1cb082
https://github.com/ttu/ruuvitag-sensor/blob/b5d1367c26844ae5875b2964c68e7b2f4e1cb082/ruuvitag_sensor/decoder.py#L207-L218
-1
251,621
carlosescri/DottedDict
dotted/collection.py
split_key
def split_key(key, max_keys=0): """Splits a key but allows dots in the key name if they're scaped properly. Splitting this complex key: complex_key = ".dont\.splitme.d\.o\. origen.splitme\.dontsplit.splitme." split_key(complex_key) results in: ['', 'dont\.splitme', 'd\.o\. origen', 'splitme\.dontsplit', 'splitme', ''] Args: key (basestring): The key to be splitted. max_keys (int): The maximum number of keys to be extracted. 0 means no limits. Returns: A list of keys """ parts = [x for x in re.split(SPLIT_REGEX, key) if x != "."] result = [] while len(parts) > 0: if max_keys > 0 and len(result) == max_keys: break result.append(parts.pop(0)) if len(parts) > 0: result.append(".".join(parts)) return result
python
def split_key(key, max_keys=0): """Splits a key but allows dots in the key name if they're scaped properly. Splitting this complex key: complex_key = ".dont\.splitme.d\.o\. origen.splitme\.dontsplit.splitme." split_key(complex_key) results in: ['', 'dont\.splitme', 'd\.o\. origen', 'splitme\.dontsplit', 'splitme', ''] Args: key (basestring): The key to be splitted. max_keys (int): The maximum number of keys to be extracted. 0 means no limits. Returns: A list of keys """ parts = [x for x in re.split(SPLIT_REGEX, key) if x != "."] result = [] while len(parts) > 0: if max_keys > 0 and len(result) == max_keys: break result.append(parts.pop(0)) if len(parts) > 0: result.append(".".join(parts)) return result
[ "def", "split_key", "(", "key", ",", "max_keys", "=", "0", ")", ":", "parts", "=", "[", "x", "for", "x", "in", "re", ".", "split", "(", "SPLIT_REGEX", ",", "key", ")", "if", "x", "!=", "\".\"", "]", "result", "=", "[", "]", "while", "len", "(", "parts", ")", ">", "0", ":", "if", "max_keys", ">", "0", "and", "len", "(", "result", ")", "==", "max_keys", ":", "break", "result", ".", "append", "(", "parts", ".", "pop", "(", "0", ")", ")", "if", "len", "(", "parts", ")", ">", "0", ":", "result", ".", "append", "(", "\".\"", ".", "join", "(", "parts", ")", ")", "return", "result" ]
Splits a key but allows dots in the key name if they're scaped properly. Splitting this complex key: complex_key = ".dont\.splitme.d\.o\. origen.splitme\.dontsplit.splitme." split_key(complex_key) results in: ['', 'dont\.splitme', 'd\.o\. origen', 'splitme\.dontsplit', 'splitme', ''] Args: key (basestring): The key to be splitted. max_keys (int): The maximum number of keys to be extracted. 0 means no limits. Returns: A list of keys
[ "Splits", "a", "key", "but", "allows", "dots", "in", "the", "key", "name", "if", "they", "re", "scaped", "properly", "." ]
fa1cba43f414871d0f6978487d61b8760fda4a68
https://github.com/carlosescri/DottedDict/blob/fa1cba43f414871d0f6978487d61b8760fda4a68/dotted/collection.py#L20-L50
-1
251,622
carlosescri/DottedDict
dotted/collection.py
DottedList.to_python
def to_python(self): """Returns a plain python list and converts to plain python objects all this object's descendants. """ result = list(self) for index, value in enumerate(result): if isinstance(value, DottedCollection): result[index] = value.to_python() return result
python
def to_python(self): """Returns a plain python list and converts to plain python objects all this object's descendants. """ result = list(self) for index, value in enumerate(result): if isinstance(value, DottedCollection): result[index] = value.to_python() return result
[ "def", "to_python", "(", "self", ")", ":", "result", "=", "list", "(", "self", ")", "for", "index", ",", "value", "in", "enumerate", "(", "result", ")", ":", "if", "isinstance", "(", "value", ",", "DottedCollection", ")", ":", "result", "[", "index", "]", "=", "value", ".", "to_python", "(", ")", "return", "result" ]
Returns a plain python list and converts to plain python objects all this object's descendants.
[ "Returns", "a", "plain", "python", "list", "and", "converts", "to", "plain", "python", "objects", "all", "this", "object", "s", "descendants", "." ]
fa1cba43f414871d0f6978487d61b8760fda4a68
https://github.com/carlosescri/DottedDict/blob/fa1cba43f414871d0f6978487d61b8760fda4a68/dotted/collection.py#L238-L248
-1
251,623
carlosescri/DottedDict
dotted/collection.py
DottedDict.to_python
def to_python(self): """Returns a plain python dict and converts to plain python objects all this object's descendants. """ result = dict(self) for key, value in iteritems(result): if isinstance(value, DottedCollection): result[key] = value.to_python() return result
python
def to_python(self): """Returns a plain python dict and converts to plain python objects all this object's descendants. """ result = dict(self) for key, value in iteritems(result): if isinstance(value, DottedCollection): result[key] = value.to_python() return result
[ "def", "to_python", "(", "self", ")", ":", "result", "=", "dict", "(", "self", ")", "for", "key", ",", "value", "in", "iteritems", "(", "result", ")", ":", "if", "isinstance", "(", "value", ",", "DottedCollection", ")", ":", "result", "[", "key", "]", "=", "value", ".", "to_python", "(", ")", "return", "result" ]
Returns a plain python dict and converts to plain python objects all this object's descendants.
[ "Returns", "a", "plain", "python", "dict", "and", "converts", "to", "plain", "python", "objects", "all", "this", "object", "s", "descendants", "." ]
fa1cba43f414871d0f6978487d61b8760fda4a68
https://github.com/carlosescri/DottedDict/blob/fa1cba43f414871d0f6978487d61b8760fda4a68/dotted/collection.py#L315-L325
-1
251,624
jaraco/irc
irc/server.py
IRCClient.handle_nick
def handle_nick(self, params): """ Handle the initial setting of the user's nickname and nick changes. """ nick = params # Valid nickname? if re.search(r'[^a-zA-Z0-9\-\[\]\'`^{}_]', nick): raise IRCError.from_name('erroneusnickname', ':%s' % nick) if self.server.clients.get(nick, None) == self: # Already registered to user return if nick in self.server.clients: # Someone else is using the nick raise IRCError.from_name('nicknameinuse', 'NICK :%s' % (nick)) if not self.nick: # New connection and nick is available; register and send welcome # and MOTD. self.nick = nick self.server.clients[nick] = self response = ':%s %s %s :%s' % ( self.server.servername, events.codes['welcome'], self.nick, SRV_WELCOME) self.send_queue.append(response) response = ':%s 376 %s :End of MOTD command.' % ( self.server.servername, self.nick) self.send_queue.append(response) return # Nick is available. Change the nick. message = ':%s NICK :%s' % (self.client_ident(), nick) self.server.clients.pop(self.nick) self.nick = nick self.server.clients[self.nick] = self # Send a notification of the nick change to all the clients in the # channels the client is in. for channel in self.channels.values(): self._send_to_others(message, channel) # Send a notification of the nick change to the client itself return message
python
def handle_nick(self, params): """ Handle the initial setting of the user's nickname and nick changes. """ nick = params # Valid nickname? if re.search(r'[^a-zA-Z0-9\-\[\]\'`^{}_]', nick): raise IRCError.from_name('erroneusnickname', ':%s' % nick) if self.server.clients.get(nick, None) == self: # Already registered to user return if nick in self.server.clients: # Someone else is using the nick raise IRCError.from_name('nicknameinuse', 'NICK :%s' % (nick)) if not self.nick: # New connection and nick is available; register and send welcome # and MOTD. self.nick = nick self.server.clients[nick] = self response = ':%s %s %s :%s' % ( self.server.servername, events.codes['welcome'], self.nick, SRV_WELCOME) self.send_queue.append(response) response = ':%s 376 %s :End of MOTD command.' % ( self.server.servername, self.nick) self.send_queue.append(response) return # Nick is available. Change the nick. message = ':%s NICK :%s' % (self.client_ident(), nick) self.server.clients.pop(self.nick) self.nick = nick self.server.clients[self.nick] = self # Send a notification of the nick change to all the clients in the # channels the client is in. for channel in self.channels.values(): self._send_to_others(message, channel) # Send a notification of the nick change to the client itself return message
[ "def", "handle_nick", "(", "self", ",", "params", ")", ":", "nick", "=", "params", "# Valid nickname?", "if", "re", ".", "search", "(", "r'[^a-zA-Z0-9\\-\\[\\]\\'`^{}_]'", ",", "nick", ")", ":", "raise", "IRCError", ".", "from_name", "(", "'erroneusnickname'", ",", "':%s'", "%", "nick", ")", "if", "self", ".", "server", ".", "clients", ".", "get", "(", "nick", ",", "None", ")", "==", "self", ":", "# Already registered to user", "return", "if", "nick", "in", "self", ".", "server", ".", "clients", ":", "# Someone else is using the nick", "raise", "IRCError", ".", "from_name", "(", "'nicknameinuse'", ",", "'NICK :%s'", "%", "(", "nick", ")", ")", "if", "not", "self", ".", "nick", ":", "# New connection and nick is available; register and send welcome", "# and MOTD.", "self", ".", "nick", "=", "nick", "self", ".", "server", ".", "clients", "[", "nick", "]", "=", "self", "response", "=", "':%s %s %s :%s'", "%", "(", "self", ".", "server", ".", "servername", ",", "events", ".", "codes", "[", "'welcome'", "]", ",", "self", ".", "nick", ",", "SRV_WELCOME", ")", "self", ".", "send_queue", ".", "append", "(", "response", ")", "response", "=", "':%s 376 %s :End of MOTD command.'", "%", "(", "self", ".", "server", ".", "servername", ",", "self", ".", "nick", ")", "self", ".", "send_queue", ".", "append", "(", "response", ")", "return", "# Nick is available. Change the nick.", "message", "=", "':%s NICK :%s'", "%", "(", "self", ".", "client_ident", "(", ")", ",", "nick", ")", "self", ".", "server", ".", "clients", ".", "pop", "(", "self", ".", "nick", ")", "self", ".", "nick", "=", "nick", "self", ".", "server", ".", "clients", "[", "self", ".", "nick", "]", "=", "self", "# Send a notification of the nick change to all the clients in the", "# channels the client is in.", "for", "channel", "in", "self", ".", "channels", ".", "values", "(", ")", ":", "self", ".", "_send_to_others", "(", "message", ",", "channel", ")", "# Send a notification of the nick change to the client itself", "return", "message" ]
Handle the initial setting of the user's nickname and nick changes.
[ "Handle", "the", "initial", "setting", "of", "the", "user", "s", "nickname", "and", "nick", "changes", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/server.py#L194-L239
-1
251,625
jaraco/irc
irc/server.py
IRCClient.handle_user
def handle_user(self, params): """ Handle the USER command which identifies the user to the server. """ params = params.split(' ', 3) if len(params) != 4: raise IRCError.from_name( 'needmoreparams', 'USER :Not enough parameters') user, mode, unused, realname = params self.user = user self.mode = mode self.realname = realname return ''
python
def handle_user(self, params): """ Handle the USER command which identifies the user to the server. """ params = params.split(' ', 3) if len(params) != 4: raise IRCError.from_name( 'needmoreparams', 'USER :Not enough parameters') user, mode, unused, realname = params self.user = user self.mode = mode self.realname = realname return ''
[ "def", "handle_user", "(", "self", ",", "params", ")", ":", "params", "=", "params", ".", "split", "(", "' '", ",", "3", ")", "if", "len", "(", "params", ")", "!=", "4", ":", "raise", "IRCError", ".", "from_name", "(", "'needmoreparams'", ",", "'USER :Not enough parameters'", ")", "user", ",", "mode", ",", "unused", ",", "realname", "=", "params", "self", ".", "user", "=", "user", "self", ".", "mode", "=", "mode", "self", ".", "realname", "=", "realname", "return", "''" ]
Handle the USER command which identifies the user to the server.
[ "Handle", "the", "USER", "command", "which", "identifies", "the", "user", "to", "the", "server", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/server.py#L241-L256
-1
251,626
jaraco/irc
irc/server.py
IRCClient.handle_privmsg
def handle_privmsg(self, params): """ Handle sending a private message to a user or channel. """ target, sep, msg = params.partition(' ') if not msg: raise IRCError.from_name( 'needmoreparams', 'PRIVMSG :Not enough parameters') message = ':%s PRIVMSG %s %s' % (self.client_ident(), target, msg) if target.startswith('#') or target.startswith('$'): # Message to channel. Check if the channel exists. channel = self.server.channels.get(target) if not channel: raise IRCError.from_name('nosuchnick', 'PRIVMSG :%s' % target) if channel.name not in self.channels: # The user isn't in the channel. raise IRCError.from_name( 'cannotsendtochan', '%s :Cannot send to channel' % channel.name) self._send_to_others(message, channel) else: # Message to user client = self.server.clients.get(target, None) if not client: raise IRCError.from_name('nosuchnick', 'PRIVMSG :%s' % target) client.send_queue.append(message)
python
def handle_privmsg(self, params): """ Handle sending a private message to a user or channel. """ target, sep, msg = params.partition(' ') if not msg: raise IRCError.from_name( 'needmoreparams', 'PRIVMSG :Not enough parameters') message = ':%s PRIVMSG %s %s' % (self.client_ident(), target, msg) if target.startswith('#') or target.startswith('$'): # Message to channel. Check if the channel exists. channel = self.server.channels.get(target) if not channel: raise IRCError.from_name('nosuchnick', 'PRIVMSG :%s' % target) if channel.name not in self.channels: # The user isn't in the channel. raise IRCError.from_name( 'cannotsendtochan', '%s :Cannot send to channel' % channel.name) self._send_to_others(message, channel) else: # Message to user client = self.server.clients.get(target, None) if not client: raise IRCError.from_name('nosuchnick', 'PRIVMSG :%s' % target) client.send_queue.append(message)
[ "def", "handle_privmsg", "(", "self", ",", "params", ")", ":", "target", ",", "sep", ",", "msg", "=", "params", ".", "partition", "(", "' '", ")", "if", "not", "msg", ":", "raise", "IRCError", ".", "from_name", "(", "'needmoreparams'", ",", "'PRIVMSG :Not enough parameters'", ")", "message", "=", "':%s PRIVMSG %s %s'", "%", "(", "self", ".", "client_ident", "(", ")", ",", "target", ",", "msg", ")", "if", "target", ".", "startswith", "(", "'#'", ")", "or", "target", ".", "startswith", "(", "'$'", ")", ":", "# Message to channel. Check if the channel exists.", "channel", "=", "self", ".", "server", ".", "channels", ".", "get", "(", "target", ")", "if", "not", "channel", ":", "raise", "IRCError", ".", "from_name", "(", "'nosuchnick'", ",", "'PRIVMSG :%s'", "%", "target", ")", "if", "channel", ".", "name", "not", "in", "self", ".", "channels", ":", "# The user isn't in the channel.", "raise", "IRCError", ".", "from_name", "(", "'cannotsendtochan'", ",", "'%s :Cannot send to channel'", "%", "channel", ".", "name", ")", "self", ".", "_send_to_others", "(", "message", ",", "channel", ")", "else", ":", "# Message to user", "client", "=", "self", ".", "server", ".", "clients", ".", "get", "(", "target", ",", "None", ")", "if", "not", "client", ":", "raise", "IRCError", ".", "from_name", "(", "'nosuchnick'", ",", "'PRIVMSG :%s'", "%", "target", ")", "client", ".", "send_queue", ".", "append", "(", "message", ")" ]
Handle sending a private message to a user or channel.
[ "Handle", "sending", "a", "private", "message", "to", "a", "user", "or", "channel", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/server.py#L314-L344
-1
251,627
jaraco/irc
irc/server.py
IRCClient._send_to_others
def _send_to_others(self, message, channel): """ Send the message to all clients in the specified channel except for self. """ other_clients = [ client for client in channel.clients if not client == self] for client in other_clients: client.send_queue.append(message)
python
def _send_to_others(self, message, channel): """ Send the message to all clients in the specified channel except for self. """ other_clients = [ client for client in channel.clients if not client == self] for client in other_clients: client.send_queue.append(message)
[ "def", "_send_to_others", "(", "self", ",", "message", ",", "channel", ")", ":", "other_clients", "=", "[", "client", "for", "client", "in", "channel", ".", "clients", "if", "not", "client", "==", "self", "]", "for", "client", "in", "other_clients", ":", "client", ".", "send_queue", ".", "append", "(", "message", ")" ]
Send the message to all clients in the specified channel except for self.
[ "Send", "the", "message", "to", "all", "clients", "in", "the", "specified", "channel", "except", "for", "self", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/server.py#L346-L355
-1
251,628
jaraco/irc
irc/server.py
IRCClient.handle_topic
def handle_topic(self, params): """ Handle a topic command. """ channel_name, sep, topic = params.partition(' ') channel = self.server.channels.get(channel_name) if not channel: raise IRCError.from_name( 'nosuchnick', 'PRIVMSG :%s' % channel_name) if channel.name not in self.channels: # The user isn't in the channel. raise IRCError.from_name( 'cannotsendtochan', '%s :Cannot send to channel' % channel.name) if topic: channel.topic = topic.lstrip(':') channel.topic_by = self.nick message = ':%s TOPIC %s :%s' % ( self.client_ident(), channel_name, channel.topic) return message
python
def handle_topic(self, params): """ Handle a topic command. """ channel_name, sep, topic = params.partition(' ') channel = self.server.channels.get(channel_name) if not channel: raise IRCError.from_name( 'nosuchnick', 'PRIVMSG :%s' % channel_name) if channel.name not in self.channels: # The user isn't in the channel. raise IRCError.from_name( 'cannotsendtochan', '%s :Cannot send to channel' % channel.name) if topic: channel.topic = topic.lstrip(':') channel.topic_by = self.nick message = ':%s TOPIC %s :%s' % ( self.client_ident(), channel_name, channel.topic) return message
[ "def", "handle_topic", "(", "self", ",", "params", ")", ":", "channel_name", ",", "sep", ",", "topic", "=", "params", ".", "partition", "(", "' '", ")", "channel", "=", "self", ".", "server", ".", "channels", ".", "get", "(", "channel_name", ")", "if", "not", "channel", ":", "raise", "IRCError", ".", "from_name", "(", "'nosuchnick'", ",", "'PRIVMSG :%s'", "%", "channel_name", ")", "if", "channel", ".", "name", "not", "in", "self", ".", "channels", ":", "# The user isn't in the channel.", "raise", "IRCError", ".", "from_name", "(", "'cannotsendtochan'", ",", "'%s :Cannot send to channel'", "%", "channel", ".", "name", ")", "if", "topic", ":", "channel", ".", "topic", "=", "topic", ".", "lstrip", "(", "':'", ")", "channel", ".", "topic_by", "=", "self", ".", "nick", "message", "=", "':%s TOPIC %s :%s'", "%", "(", "self", ".", "client_ident", "(", ")", ",", "channel_name", ",", "channel", ".", "topic", ")", "return", "message" ]
Handle a topic command.
[ "Handle", "a", "topic", "command", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/server.py#L357-L379
-1
251,629
jaraco/irc
irc/server.py
IRCClient.handle_quit
def handle_quit(self, params): """ Handle the client breaking off the connection with a QUIT command. """ response = ':%s QUIT :%s' % (self.client_ident(), params.lstrip(':')) # Send quit message to all clients in all channels user is in, and # remove the user from the channels. for channel in self.channels.values(): for client in channel.clients: client.send_queue.append(response) channel.clients.remove(self)
python
def handle_quit(self, params): """ Handle the client breaking off the connection with a QUIT command. """ response = ':%s QUIT :%s' % (self.client_ident(), params.lstrip(':')) # Send quit message to all clients in all channels user is in, and # remove the user from the channels. for channel in self.channels.values(): for client in channel.clients: client.send_queue.append(response) channel.clients.remove(self)
[ "def", "handle_quit", "(", "self", ",", "params", ")", ":", "response", "=", "':%s QUIT :%s'", "%", "(", "self", ".", "client_ident", "(", ")", ",", "params", ".", "lstrip", "(", "':'", ")", ")", "# Send quit message to all clients in all channels user is in, and", "# remove the user from the channels.", "for", "channel", "in", "self", ".", "channels", ".", "values", "(", ")", ":", "for", "client", "in", "channel", ".", "clients", ":", "client", ".", "send_queue", ".", "append", "(", "response", ")", "channel", ".", "clients", ".", "remove", "(", "self", ")" ]
Handle the client breaking off the connection with a QUIT command.
[ "Handle", "the", "client", "breaking", "off", "the", "connection", "with", "a", "QUIT", "command", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/server.py#L401-L411
-1
251,630
jaraco/irc
irc/server.py
IRCClient.handle_dump
def handle_dump(self, params): """ Dump internal server information for debugging purposes. """ print("Clients:", self.server.clients) for client in self.server.clients.values(): print(" ", client) for channel in client.channels.values(): print(" ", channel.name) print("Channels:", self.server.channels) for channel in self.server.channels.values(): print(" ", channel.name, channel) for client in channel.clients: print(" ", client.nick, client)
python
def handle_dump(self, params): """ Dump internal server information for debugging purposes. """ print("Clients:", self.server.clients) for client in self.server.clients.values(): print(" ", client) for channel in client.channels.values(): print(" ", channel.name) print("Channels:", self.server.channels) for channel in self.server.channels.values(): print(" ", channel.name, channel) for client in channel.clients: print(" ", client.nick, client)
[ "def", "handle_dump", "(", "self", ",", "params", ")", ":", "print", "(", "\"Clients:\"", ",", "self", ".", "server", ".", "clients", ")", "for", "client", "in", "self", ".", "server", ".", "clients", ".", "values", "(", ")", ":", "print", "(", "\" \"", ",", "client", ")", "for", "channel", "in", "client", ".", "channels", ".", "values", "(", ")", ":", "print", "(", "\" \"", ",", "channel", ".", "name", ")", "print", "(", "\"Channels:\"", ",", "self", ".", "server", ".", "channels", ")", "for", "channel", "in", "self", ".", "server", ".", "channels", ".", "values", "(", ")", ":", "print", "(", "\" \"", ",", "channel", ".", "name", ",", "channel", ")", "for", "client", "in", "channel", ".", "clients", ":", "print", "(", "\" \"", ",", "client", ".", "nick", ",", "client", ")" ]
Dump internal server information for debugging purposes.
[ "Dump", "internal", "server", "information", "for", "debugging", "purposes", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/server.py#L413-L426
-1
251,631
jaraco/irc
irc/server.py
IRCClient.client_ident
def client_ident(self): """ Return the client identifier as included in many command replies. """ return irc.client.NickMask.from_params( self.nick, self.user, self.server.servername)
python
def client_ident(self): """ Return the client identifier as included in many command replies. """ return irc.client.NickMask.from_params( self.nick, self.user, self.server.servername)
[ "def", "client_ident", "(", "self", ")", ":", "return", "irc", ".", "client", ".", "NickMask", ".", "from_params", "(", "self", ".", "nick", ",", "self", ".", "user", ",", "self", ".", "server", ".", "servername", ")" ]
Return the client identifier as included in many command replies.
[ "Return", "the", "client", "identifier", "as", "included", "in", "many", "command", "replies", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/server.py#L442-L448
-1
251,632
jaraco/irc
irc/server.py
IRCClient.finish
def finish(self): """ The client conection is finished. Do some cleanup to ensure that the client doesn't linger around in any channel or the client list, in case the client didn't properly close the connection with PART and QUIT. """ log.info('Client disconnected: %s', self.client_ident()) response = ':%s QUIT :EOF from client' % self.client_ident() for channel in self.channels.values(): if self in channel.clients: # Client is gone without properly QUITing or PARTing this # channel. for client in channel.clients: client.send_queue.append(response) channel.clients.remove(self) if self.nick: self.server.clients.pop(self.nick) log.info('Connection finished: %s', self.client_ident())
python
def finish(self): """ The client conection is finished. Do some cleanup to ensure that the client doesn't linger around in any channel or the client list, in case the client didn't properly close the connection with PART and QUIT. """ log.info('Client disconnected: %s', self.client_ident()) response = ':%s QUIT :EOF from client' % self.client_ident() for channel in self.channels.values(): if self in channel.clients: # Client is gone without properly QUITing or PARTing this # channel. for client in channel.clients: client.send_queue.append(response) channel.clients.remove(self) if self.nick: self.server.clients.pop(self.nick) log.info('Connection finished: %s', self.client_ident())
[ "def", "finish", "(", "self", ")", ":", "log", ".", "info", "(", "'Client disconnected: %s'", ",", "self", ".", "client_ident", "(", ")", ")", "response", "=", "':%s QUIT :EOF from client'", "%", "self", ".", "client_ident", "(", ")", "for", "channel", "in", "self", ".", "channels", ".", "values", "(", ")", ":", "if", "self", "in", "channel", ".", "clients", ":", "# Client is gone without properly QUITing or PARTing this", "# channel.", "for", "client", "in", "channel", ".", "clients", ":", "client", ".", "send_queue", ".", "append", "(", "response", ")", "channel", ".", "clients", ".", "remove", "(", "self", ")", "if", "self", ".", "nick", ":", "self", ".", "server", ".", "clients", ".", "pop", "(", "self", ".", "nick", ")", "log", ".", "info", "(", "'Connection finished: %s'", ",", "self", ".", "client_ident", "(", ")", ")" ]
The client conection is finished. Do some cleanup to ensure that the client doesn't linger around in any channel or the client list, in case the client didn't properly close the connection with PART and QUIT.
[ "The", "client", "conection", "is", "finished", ".", "Do", "some", "cleanup", "to", "ensure", "that", "the", "client", "doesn", "t", "linger", "around", "in", "any", "channel", "or", "the", "client", "list", "in", "case", "the", "client", "didn", "t", "properly", "close", "the", "connection", "with", "PART", "and", "QUIT", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/server.py#L450-L467
-1
251,633
jaraco/irc
irc/client_aio.py
AioConnection.send_raw
def send_raw(self, string): """Send raw string to the server, via the asyncio transport. The string will be padded with appropriate CR LF. """ log.debug('RAW: {}'.format(string)) if self.transport is None: raise ServerNotConnectedError("Not connected.") self.transport.write(self._prep_message(string))
python
def send_raw(self, string): """Send raw string to the server, via the asyncio transport. The string will be padded with appropriate CR LF. """ log.debug('RAW: {}'.format(string)) if self.transport is None: raise ServerNotConnectedError("Not connected.") self.transport.write(self._prep_message(string))
[ "def", "send_raw", "(", "self", ",", "string", ")", ":", "log", ".", "debug", "(", "'RAW: {}'", ".", "format", "(", "string", ")", ")", "if", "self", ".", "transport", "is", "None", ":", "raise", "ServerNotConnectedError", "(", "\"Not connected.\"", ")", "self", ".", "transport", ".", "write", "(", "self", ".", "_prep_message", "(", "string", ")", ")" ]
Send raw string to the server, via the asyncio transport. The string will be padded with appropriate CR LF.
[ "Send", "raw", "string", "to", "the", "server", "via", "the", "asyncio", "transport", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client_aio.py#L175-L184
-1
251,634
jaraco/irc
irc/modes.py
_parse_modes
def _parse_modes(mode_string, unary_modes=""): """ Parse the mode_string and return a list of triples. If no string is supplied return an empty list. >>> _parse_modes('') [] If no sign is supplied, return an empty list. >>> _parse_modes('ab') [] Discard unused args. >>> _parse_modes('+a foo bar baz') [['+', 'a', None]] Return none for unary args when not provided >>> _parse_modes('+abc foo', unary_modes='abc') [['+', 'a', 'foo'], ['+', 'b', None], ['+', 'c', None]] This function never throws an error: >>> import random >>> def random_text(min_len = 3, max_len = 80): ... len = random.randint(min_len, max_len) ... chars_to_choose = [chr(x) for x in range(0,1024)] ... chars = (random.choice(chars_to_choose) for x in range(len)) ... return ''.join(chars) >>> def random_texts(min_len = 3, max_len = 80): ... while True: ... yield random_text(min_len, max_len) >>> import itertools >>> texts = itertools.islice(random_texts(), 1000) >>> set(type(_parse_modes(text)) for text in texts) == {list} True """ # mode_string must be non-empty and begin with a sign if not mode_string or not mode_string[0] in '+-': return [] modes = [] parts = mode_string.split() mode_part, args = parts[0], parts[1:] for ch in mode_part: if ch in "+-": sign = ch continue arg = args.pop(0) if ch in unary_modes and args else None modes.append([sign, ch, arg]) return modes
python
def _parse_modes(mode_string, unary_modes=""): """ Parse the mode_string and return a list of triples. If no string is supplied return an empty list. >>> _parse_modes('') [] If no sign is supplied, return an empty list. >>> _parse_modes('ab') [] Discard unused args. >>> _parse_modes('+a foo bar baz') [['+', 'a', None]] Return none for unary args when not provided >>> _parse_modes('+abc foo', unary_modes='abc') [['+', 'a', 'foo'], ['+', 'b', None], ['+', 'c', None]] This function never throws an error: >>> import random >>> def random_text(min_len = 3, max_len = 80): ... len = random.randint(min_len, max_len) ... chars_to_choose = [chr(x) for x in range(0,1024)] ... chars = (random.choice(chars_to_choose) for x in range(len)) ... return ''.join(chars) >>> def random_texts(min_len = 3, max_len = 80): ... while True: ... yield random_text(min_len, max_len) >>> import itertools >>> texts = itertools.islice(random_texts(), 1000) >>> set(type(_parse_modes(text)) for text in texts) == {list} True """ # mode_string must be non-empty and begin with a sign if not mode_string or not mode_string[0] in '+-': return [] modes = [] parts = mode_string.split() mode_part, args = parts[0], parts[1:] for ch in mode_part: if ch in "+-": sign = ch continue arg = args.pop(0) if ch in unary_modes and args else None modes.append([sign, ch, arg]) return modes
[ "def", "_parse_modes", "(", "mode_string", ",", "unary_modes", "=", "\"\"", ")", ":", "# mode_string must be non-empty and begin with a sign", "if", "not", "mode_string", "or", "not", "mode_string", "[", "0", "]", "in", "'+-'", ":", "return", "[", "]", "modes", "=", "[", "]", "parts", "=", "mode_string", ".", "split", "(", ")", "mode_part", ",", "args", "=", "parts", "[", "0", "]", ",", "parts", "[", "1", ":", "]", "for", "ch", "in", "mode_part", ":", "if", "ch", "in", "\"+-\"", ":", "sign", "=", "ch", "continue", "arg", "=", "args", ".", "pop", "(", "0", ")", "if", "ch", "in", "unary_modes", "and", "args", "else", "None", "modes", ".", "append", "(", "[", "sign", ",", "ch", ",", "arg", "]", ")", "return", "modes" ]
Parse the mode_string and return a list of triples. If no string is supplied return an empty list. >>> _parse_modes('') [] If no sign is supplied, return an empty list. >>> _parse_modes('ab') [] Discard unused args. >>> _parse_modes('+a foo bar baz') [['+', 'a', None]] Return none for unary args when not provided >>> _parse_modes('+abc foo', unary_modes='abc') [['+', 'a', 'foo'], ['+', 'b', None], ['+', 'c', None]] This function never throws an error: >>> import random >>> def random_text(min_len = 3, max_len = 80): ... len = random.randint(min_len, max_len) ... chars_to_choose = [chr(x) for x in range(0,1024)] ... chars = (random.choice(chars_to_choose) for x in range(len)) ... return ''.join(chars) >>> def random_texts(min_len = 3, max_len = 80): ... while True: ... yield random_text(min_len, max_len) >>> import itertools >>> texts = itertools.islice(random_texts(), 1000) >>> set(type(_parse_modes(text)) for text in texts) == {list} True
[ "Parse", "the", "mode_string", "and", "return", "a", "list", "of", "triples", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/modes.py#L32-L89
-1
251,635
jaraco/irc
irc/message.py
Tag.from_group
def from_group(cls, group): """ Construct tags from the regex group """ if not group: return tag_items = group.split(";") return list(map(cls.parse, tag_items))
python
def from_group(cls, group): """ Construct tags from the regex group """ if not group: return tag_items = group.split(";") return list(map(cls.parse, tag_items))
[ "def", "from_group", "(", "cls", ",", "group", ")", ":", "if", "not", "group", ":", "return", "tag_items", "=", "group", ".", "split", "(", "\";\"", ")", "return", "list", "(", "map", "(", "cls", ".", "parse", ",", "tag_items", ")", ")" ]
Construct tags from the regex group
[ "Construct", "tags", "from", "the", "regex", "group" ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/message.py#L39-L46
-1
251,636
jaraco/irc
irc/message.py
Arguments.from_group
def from_group(group): """ Construct arguments from the regex group >>> Arguments.from_group('foo') ['foo'] >>> Arguments.from_group(None) [] >>> Arguments.from_group('') [] >>> Arguments.from_group('foo bar') ['foo', 'bar'] >>> Arguments.from_group('foo bar :baz') ['foo', 'bar', 'baz'] >>> Arguments.from_group('foo bar :baz bing') ['foo', 'bar', 'baz bing'] """ if not group: return [] main, sep, ext = group.partition(" :") arguments = main.split() if sep: arguments.append(ext) return arguments
python
def from_group(group): """ Construct arguments from the regex group >>> Arguments.from_group('foo') ['foo'] >>> Arguments.from_group(None) [] >>> Arguments.from_group('') [] >>> Arguments.from_group('foo bar') ['foo', 'bar'] >>> Arguments.from_group('foo bar :baz') ['foo', 'bar', 'baz'] >>> Arguments.from_group('foo bar :baz bing') ['foo', 'bar', 'baz bing'] """ if not group: return [] main, sep, ext = group.partition(" :") arguments = main.split() if sep: arguments.append(ext) return arguments
[ "def", "from_group", "(", "group", ")", ":", "if", "not", "group", ":", "return", "[", "]", "main", ",", "sep", ",", "ext", "=", "group", ".", "partition", "(", "\" :\"", ")", "arguments", "=", "main", ".", "split", "(", ")", "if", "sep", ":", "arguments", ".", "append", "(", "ext", ")", "return", "arguments" ]
Construct arguments from the regex group >>> Arguments.from_group('foo') ['foo'] >>> Arguments.from_group(None) [] >>> Arguments.from_group('') [] >>> Arguments.from_group('foo bar') ['foo', 'bar'] >>> Arguments.from_group('foo bar :baz') ['foo', 'bar', 'baz'] >>> Arguments.from_group('foo bar :baz bing') ['foo', 'bar', 'baz bing']
[ "Construct", "arguments", "from", "the", "regex", "group" ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/message.py#L51-L81
-1
251,637
jaraco/irc
irc/features.py
FeatureSet.set
def set(self, name, value=True): "set a feature value" setattr(self, name.lower(), value)
python
def set(self, name, value=True): "set a feature value" setattr(self, name.lower(), value)
[ "def", "set", "(", "self", ",", "name", ",", "value", "=", "True", ")", ":", "setattr", "(", "self", ",", "name", ".", "lower", "(", ")", ",", "value", ")" ]
set a feature value
[ "set", "a", "feature", "value" ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/features.py#L36-L38
-1
251,638
jaraco/irc
irc/features.py
FeatureSet.load
def load(self, arguments): "Load the values from the a ServerConnection arguments" features = arguments[1:-1] list(map(self.load_feature, features))
python
def load(self, arguments): "Load the values from the a ServerConnection arguments" features = arguments[1:-1] list(map(self.load_feature, features))
[ "def", "load", "(", "self", ",", "arguments", ")", ":", "features", "=", "arguments", "[", "1", ":", "-", "1", "]", "list", "(", "map", "(", "self", ".", "load_feature", ",", "features", ")", ")" ]
Load the values from the a ServerConnection arguments
[ "Load", "the", "values", "from", "the", "a", "ServerConnection", "arguments" ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/features.py#L44-L47
-1
251,639
jaraco/irc
irc/features.py
FeatureSet._parse_PREFIX
def _parse_PREFIX(value): "channel user prefixes" channel_modes, channel_chars = value.split(')') channel_modes = channel_modes[1:] return collections.OrderedDict(zip(channel_chars, channel_modes))
python
def _parse_PREFIX(value): "channel user prefixes" channel_modes, channel_chars = value.split(')') channel_modes = channel_modes[1:] return collections.OrderedDict(zip(channel_chars, channel_modes))
[ "def", "_parse_PREFIX", "(", "value", ")", ":", "channel_modes", ",", "channel_chars", "=", "value", ".", "split", "(", "')'", ")", "channel_modes", "=", "channel_modes", "[", "1", ":", "]", "return", "collections", ".", "OrderedDict", "(", "zip", "(", "channel_chars", ",", "channel_modes", ")", ")" ]
channel user prefixes
[ "channel", "user", "prefixes" ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/features.py#L68-L72
-1
251,640
jaraco/irc
irc/bot.py
SingleServerIRCBot._connect
def _connect(self): """ Establish a connection to the server at the front of the server_list. """ server = self.servers.peek() try: self.connect( server.host, server.port, self._nickname, server.password, ircname=self._realname, **self.__connect_params) except irc.client.ServerConnectionError: pass
python
def _connect(self): """ Establish a connection to the server at the front of the server_list. """ server = self.servers.peek() try: self.connect( server.host, server.port, self._nickname, server.password, ircname=self._realname, **self.__connect_params) except irc.client.ServerConnectionError: pass
[ "def", "_connect", "(", "self", ")", ":", "server", "=", "self", ".", "servers", ".", "peek", "(", ")", "try", ":", "self", ".", "connect", "(", "server", ".", "host", ",", "server", ".", "port", ",", "self", ".", "_nickname", ",", "server", ".", "password", ",", "ircname", "=", "self", ".", "_realname", ",", "*", "*", "self", ".", "__connect_params", ")", "except", "irc", ".", "client", ".", "ServerConnectionError", ":", "pass" ]
Establish a connection to the server at the front of the server_list.
[ "Establish", "a", "connection", "to", "the", "server", "at", "the", "front", "of", "the", "server_list", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/bot.py#L173-L184
-1
251,641
jaraco/irc
irc/bot.py
SingleServerIRCBot.jump_server
def jump_server(self, msg="Changing servers"): """Connect to a new server, possibly disconnecting from the current. The bot will skip to next server in the server_list each time jump_server is called. """ if self.connection.is_connected(): self.connection.disconnect(msg) next(self.servers) self._connect()
python
def jump_server(self, msg="Changing servers"): """Connect to a new server, possibly disconnecting from the current. The bot will skip to next server in the server_list each time jump_server is called. """ if self.connection.is_connected(): self.connection.disconnect(msg) next(self.servers) self._connect()
[ "def", "jump_server", "(", "self", ",", "msg", "=", "\"Changing servers\"", ")", ":", "if", "self", ".", "connection", ".", "is_connected", "(", ")", ":", "self", ".", "connection", ".", "disconnect", "(", "msg", ")", "next", "(", "self", ".", "servers", ")", "self", ".", "_connect", "(", ")" ]
Connect to a new server, possibly disconnecting from the current. The bot will skip to next server in the server_list each time jump_server is called.
[ "Connect", "to", "a", "new", "server", "possibly", "disconnecting", "from", "the", "current", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/bot.py#L298-L308
-1
251,642
jaraco/irc
irc/bot.py
SingleServerIRCBot.on_ctcp
def on_ctcp(self, connection, event): """Default handler for ctcp events. Replies to VERSION and PING requests and relays DCC requests to the on_dccchat method. """ nick = event.source.nick if event.arguments[0] == "VERSION": connection.ctcp_reply(nick, "VERSION " + self.get_version()) elif event.arguments[0] == "PING": if len(event.arguments) > 1: connection.ctcp_reply(nick, "PING " + event.arguments[1]) elif ( event.arguments[0] == "DCC" and event.arguments[1].split(" ", 1)[0] == "CHAT"): self.on_dccchat(connection, event)
python
def on_ctcp(self, connection, event): """Default handler for ctcp events. Replies to VERSION and PING requests and relays DCC requests to the on_dccchat method. """ nick = event.source.nick if event.arguments[0] == "VERSION": connection.ctcp_reply(nick, "VERSION " + self.get_version()) elif event.arguments[0] == "PING": if len(event.arguments) > 1: connection.ctcp_reply(nick, "PING " + event.arguments[1]) elif ( event.arguments[0] == "DCC" and event.arguments[1].split(" ", 1)[0] == "CHAT"): self.on_dccchat(connection, event)
[ "def", "on_ctcp", "(", "self", ",", "connection", ",", "event", ")", ":", "nick", "=", "event", ".", "source", ".", "nick", "if", "event", ".", "arguments", "[", "0", "]", "==", "\"VERSION\"", ":", "connection", ".", "ctcp_reply", "(", "nick", ",", "\"VERSION \"", "+", "self", ".", "get_version", "(", ")", ")", "elif", "event", ".", "arguments", "[", "0", "]", "==", "\"PING\"", ":", "if", "len", "(", "event", ".", "arguments", ")", ">", "1", ":", "connection", ".", "ctcp_reply", "(", "nick", ",", "\"PING \"", "+", "event", ".", "arguments", "[", "1", "]", ")", "elif", "(", "event", ".", "arguments", "[", "0", "]", "==", "\"DCC\"", "and", "event", ".", "arguments", "[", "1", "]", ".", "split", "(", "\" \"", ",", "1", ")", "[", "0", "]", "==", "\"CHAT\"", ")", ":", "self", ".", "on_dccchat", "(", "connection", ",", "event", ")" ]
Default handler for ctcp events. Replies to VERSION and PING requests and relays DCC requests to the on_dccchat method.
[ "Default", "handler", "for", "ctcp", "events", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/bot.py#L310-L325
-1
251,643
jaraco/irc
irc/bot.py
Channel.set_mode
def set_mode(self, mode, value=None): """Set mode on the channel. Arguments: mode -- The mode (a single-character string). value -- Value """ if mode in self.user_modes: self.mode_users[mode][value] = 1 else: self.modes[mode] = value
python
def set_mode(self, mode, value=None): """Set mode on the channel. Arguments: mode -- The mode (a single-character string). value -- Value """ if mode in self.user_modes: self.mode_users[mode][value] = 1 else: self.modes[mode] = value
[ "def", "set_mode", "(", "self", ",", "mode", ",", "value", "=", "None", ")", ":", "if", "mode", "in", "self", ".", "user_modes", ":", "self", ".", "mode_users", "[", "mode", "]", "[", "value", "]", "=", "1", "else", ":", "self", ".", "modes", "[", "mode", "]", "=", "value" ]
Set mode on the channel. Arguments: mode -- The mode (a single-character string). value -- Value
[ "Set", "mode", "on", "the", "channel", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/bot.py#L424-L436
-1
251,644
jaraco/irc
irc/bot.py
Channel.clear_mode
def clear_mode(self, mode, value=None): """Clear mode on the channel. Arguments: mode -- The mode (a single-character string). value -- Value """ try: if mode in self.user_modes: del self.mode_users[mode][value] else: del self.modes[mode] except KeyError: pass
python
def clear_mode(self, mode, value=None): """Clear mode on the channel. Arguments: mode -- The mode (a single-character string). value -- Value """ try: if mode in self.user_modes: del self.mode_users[mode][value] else: del self.modes[mode] except KeyError: pass
[ "def", "clear_mode", "(", "self", ",", "mode", ",", "value", "=", "None", ")", ":", "try", ":", "if", "mode", "in", "self", ".", "user_modes", ":", "del", "self", ".", "mode_users", "[", "mode", "]", "[", "value", "]", "else", ":", "del", "self", ".", "modes", "[", "mode", "]", "except", "KeyError", ":", "pass" ]
Clear mode on the channel. Arguments: mode -- The mode (a single-character string). value -- Value
[ "Clear", "mode", "on", "the", "channel", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/bot.py#L438-L453
-1
251,645
jaraco/irc
irc/client.py
ip_numstr_to_quad
def ip_numstr_to_quad(num): """ Convert an IP number as an integer given in ASCII representation to an IP address string. >>> ip_numstr_to_quad('3232235521') '192.168.0.1' >>> ip_numstr_to_quad(3232235521) '192.168.0.1' """ packed = struct.pack('>L', int(num)) bytes = struct.unpack('BBBB', packed) return ".".join(map(str, bytes))
python
def ip_numstr_to_quad(num): """ Convert an IP number as an integer given in ASCII representation to an IP address string. >>> ip_numstr_to_quad('3232235521') '192.168.0.1' >>> ip_numstr_to_quad(3232235521) '192.168.0.1' """ packed = struct.pack('>L', int(num)) bytes = struct.unpack('BBBB', packed) return ".".join(map(str, bytes))
[ "def", "ip_numstr_to_quad", "(", "num", ")", ":", "packed", "=", "struct", ".", "pack", "(", "'>L'", ",", "int", "(", "num", ")", ")", "bytes", "=", "struct", ".", "unpack", "(", "'BBBB'", ",", "packed", ")", "return", "\".\"", ".", "join", "(", "map", "(", "str", ",", "bytes", ")", ")" ]
Convert an IP number as an integer given in ASCII representation to an IP address string. >>> ip_numstr_to_quad('3232235521') '192.168.0.1' >>> ip_numstr_to_quad(3232235521) '192.168.0.1'
[ "Convert", "an", "IP", "number", "as", "an", "integer", "given", "in", "ASCII", "representation", "to", "an", "IP", "address", "string", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L1249-L1261
-1
251,646
jaraco/irc
irc/client.py
ServerConnection.as_nick
def as_nick(self, name): """ Set the nick for the duration of the context. """ orig = self.get_nickname() self.nick(name) try: yield orig finally: self.nick(orig)
python
def as_nick(self, name): """ Set the nick for the duration of the context. """ orig = self.get_nickname() self.nick(name) try: yield orig finally: self.nick(orig)
[ "def", "as_nick", "(", "self", ",", "name", ")", ":", "orig", "=", "self", ".", "get_nickname", "(", ")", "self", ".", "nick", "(", "name", ")", "try", ":", "yield", "orig", "finally", ":", "self", ".", "nick", "(", "orig", ")" ]
Set the nick for the duration of the context.
[ "Set", "the", "nick", "for", "the", "duration", "of", "the", "context", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L238-L247
-1
251,647
jaraco/irc
irc/client.py
ServerConnection.process_data
def process_data(self): "read and process input from self.socket" try: reader = getattr(self.socket, 'read', self.socket.recv) new_data = reader(2 ** 14) except socket.error: # The server hung up. self.disconnect("Connection reset by peer") return if not new_data: # Read nothing: connection must be down. self.disconnect("Connection reset by peer") return self.buffer.feed(new_data) # process each non-empty line after logging all lines for line in self.buffer: log.debug("FROM SERVER: %s", line) if not line: continue self._process_line(line)
python
def process_data(self): "read and process input from self.socket" try: reader = getattr(self.socket, 'read', self.socket.recv) new_data = reader(2 ** 14) except socket.error: # The server hung up. self.disconnect("Connection reset by peer") return if not new_data: # Read nothing: connection must be down. self.disconnect("Connection reset by peer") return self.buffer.feed(new_data) # process each non-empty line after logging all lines for line in self.buffer: log.debug("FROM SERVER: %s", line) if not line: continue self._process_line(line)
[ "def", "process_data", "(", "self", ")", ":", "try", ":", "reader", "=", "getattr", "(", "self", ".", "socket", ",", "'read'", ",", "self", ".", "socket", ".", "recv", ")", "new_data", "=", "reader", "(", "2", "**", "14", ")", "except", "socket", ".", "error", ":", "# The server hung up.", "self", ".", "disconnect", "(", "\"Connection reset by peer\"", ")", "return", "if", "not", "new_data", ":", "# Read nothing: connection must be down.", "self", ".", "disconnect", "(", "\"Connection reset by peer\"", ")", "return", "self", ".", "buffer", ".", "feed", "(", "new_data", ")", "# process each non-empty line after logging all lines", "for", "line", "in", "self", ".", "buffer", ":", "log", ".", "debug", "(", "\"FROM SERVER: %s\"", ",", "line", ")", "if", "not", "line", ":", "continue", "self", ".", "_process_line", "(", "line", ")" ]
read and process input from self.socket
[ "read", "and", "process", "input", "from", "self", ".", "socket" ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L249-L271
-1
251,648
jaraco/irc
irc/client.py
ServerConnection.ctcp
def ctcp(self, ctcptype, target, parameter=""): """Send a CTCP command.""" ctcptype = ctcptype.upper() tmpl = ( "\001{ctcptype} {parameter}\001" if parameter else "\001{ctcptype}\001" ) self.privmsg(target, tmpl.format(**vars()))
python
def ctcp(self, ctcptype, target, parameter=""): """Send a CTCP command.""" ctcptype = ctcptype.upper() tmpl = ( "\001{ctcptype} {parameter}\001" if parameter else "\001{ctcptype}\001" ) self.privmsg(target, tmpl.format(**vars()))
[ "def", "ctcp", "(", "self", ",", "ctcptype", ",", "target", ",", "parameter", "=", "\"\"", ")", ":", "ctcptype", "=", "ctcptype", ".", "upper", "(", ")", "tmpl", "=", "(", "\"\\001{ctcptype} {parameter}\\001\"", "if", "parameter", "else", "\"\\001{ctcptype}\\001\"", ")", "self", ".", "privmsg", "(", "target", ",", "tmpl", ".", "format", "(", "*", "*", "vars", "(", ")", ")", ")" ]
Send a CTCP command.
[ "Send", "a", "CTCP", "command", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L441-L448
-1
251,649
jaraco/irc
irc/client.py
ServerConnection.kick
def kick(self, channel, nick, comment=""): """Send a KICK command.""" self.send_items('KICK', channel, nick, comment and ':' + comment)
python
def kick(self, channel, nick, comment=""): """Send a KICK command.""" self.send_items('KICK', channel, nick, comment and ':' + comment)
[ "def", "kick", "(", "self", ",", "channel", ",", "nick", ",", "comment", "=", "\"\"", ")", ":", "self", ".", "send_items", "(", "'KICK'", ",", "channel", ",", "nick", ",", "comment", "and", "':'", "+", "comment", ")" ]
Send a KICK command.
[ "Send", "a", "KICK", "command", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L501-L503
-1
251,650
jaraco/irc
irc/client.py
ServerConnection.list
def list(self, channels=None, server=""): """Send a LIST command.""" self.send_items('LIST', ','.join(always_iterable(channels)), server)
python
def list(self, channels=None, server=""): """Send a LIST command.""" self.send_items('LIST', ','.join(always_iterable(channels)), server)
[ "def", "list", "(", "self", ",", "channels", "=", "None", ",", "server", "=", "\"\"", ")", ":", "self", ".", "send_items", "(", "'LIST'", ",", "','", ".", "join", "(", "always_iterable", "(", "channels", ")", ")", ",", "server", ")" ]
Send a LIST command.
[ "Send", "a", "LIST", "command", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L509-L511
-1
251,651
jaraco/irc
irc/client.py
ServerConnection.part
def part(self, channels, message=""): """Send a PART command.""" self.send_items('PART', ','.join(always_iterable(channels)), message)
python
def part(self, channels, message=""): """Send a PART command.""" self.send_items('PART', ','.join(always_iterable(channels)), message)
[ "def", "part", "(", "self", ",", "channels", ",", "message", "=", "\"\"", ")", ":", "self", ".", "send_items", "(", "'PART'", ",", "','", ".", "join", "(", "always_iterable", "(", "channels", ")", ")", ",", "message", ")" ]
Send a PART command.
[ "Send", "a", "PART", "command", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L542-L544
-1
251,652
jaraco/irc
irc/client.py
ServerConnection.privmsg_many
def privmsg_many(self, targets, text): """Send a PRIVMSG command to multiple targets.""" target = ','.join(targets) return self.privmsg(target, text)
python
def privmsg_many(self, targets, text): """Send a PRIVMSG command to multiple targets.""" target = ','.join(targets) return self.privmsg(target, text)
[ "def", "privmsg_many", "(", "self", ",", "targets", ",", "text", ")", ":", "target", "=", "','", ".", "join", "(", "targets", ")", "return", "self", ".", "privmsg", "(", "target", ",", "text", ")" ]
Send a PRIVMSG command to multiple targets.
[ "Send", "a", "PRIVMSG", "command", "to", "multiple", "targets", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L562-L565
-1
251,653
jaraco/irc
irc/client.py
ServerConnection.user
def user(self, username, realname): """Send a USER command.""" cmd = 'USER {username} 0 * :{realname}'.format(**locals()) self.send_raw(cmd)
python
def user(self, username, realname): """Send a USER command.""" cmd = 'USER {username} 0 * :{realname}'.format(**locals()) self.send_raw(cmd)
[ "def", "user", "(", "self", ",", "username", ",", "realname", ")", ":", "cmd", "=", "'USER {username} 0 * :{realname}'", ".", "format", "(", "*", "*", "locals", "(", ")", ")", "self", ".", "send_raw", "(", "cmd", ")" ]
Send a USER command.
[ "Send", "a", "USER", "command", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L628-L631
-1
251,654
jaraco/irc
irc/client.py
ServerConnection.whowas
def whowas(self, nick, max="", server=""): """Send a WHOWAS command.""" self.send_items('WHOWAS', nick, max, server)
python
def whowas(self, nick, max="", server=""): """Send a WHOWAS command.""" self.send_items('WHOWAS', nick, max, server)
[ "def", "whowas", "(", "self", ",", "nick", ",", "max", "=", "\"\"", ",", "server", "=", "\"\"", ")", ":", "self", ".", "send_items", "(", "'WHOWAS'", ",", "nick", ",", "max", ",", "server", ")" ]
Send a WHOWAS command.
[ "Send", "a", "WHOWAS", "command", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L657-L659
-1
251,655
jaraco/irc
irc/client.py
ServerConnection.set_keepalive
def set_keepalive(self, interval): """ Set a keepalive to occur every ``interval`` on this connection. """ pinger = functools.partial(self.ping, 'keep-alive') self.reactor.scheduler.execute_every(period=interval, func=pinger)
python
def set_keepalive(self, interval): """ Set a keepalive to occur every ``interval`` on this connection. """ pinger = functools.partial(self.ping, 'keep-alive') self.reactor.scheduler.execute_every(period=interval, func=pinger)
[ "def", "set_keepalive", "(", "self", ",", "interval", ")", ":", "pinger", "=", "functools", ".", "partial", "(", "self", ".", "ping", ",", "'keep-alive'", ")", "self", ".", "reactor", ".", "scheduler", ".", "execute_every", "(", "period", "=", "interval", ",", "func", "=", "pinger", ")" ]
Set a keepalive to occur every ``interval`` on this connection.
[ "Set", "a", "keepalive", "to", "occur", "every", "interval", "on", "this", "connection", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L668-L673
-1
251,656
jaraco/irc
irc/client.py
Reactor.server
def server(self): """Creates and returns a ServerConnection object.""" conn = self.connection_class(self) with self.mutex: self.connections.append(conn) return conn
python
def server(self): """Creates and returns a ServerConnection object.""" conn = self.connection_class(self) with self.mutex: self.connections.append(conn) return conn
[ "def", "server", "(", "self", ")", ":", "conn", "=", "self", ".", "connection_class", "(", "self", ")", "with", "self", ".", "mutex", ":", "self", ".", "connections", ".", "append", "(", "conn", ")", "return", "conn" ]
Creates and returns a ServerConnection object.
[ "Creates", "and", "returns", "a", "ServerConnection", "object", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L766-L772
-1
251,657
jaraco/irc
irc/client.py
Reactor.process_data
def process_data(self, sockets): """Called when there is more data to read on connection sockets. Arguments: sockets -- A list of socket objects. See documentation for Reactor.__init__. """ with self.mutex: log.log(logging.DEBUG - 2, "process_data()") for sock, conn in itertools.product(sockets, self.connections): if sock == conn.socket: conn.process_data()
python
def process_data(self, sockets): """Called when there is more data to read on connection sockets. Arguments: sockets -- A list of socket objects. See documentation for Reactor.__init__. """ with self.mutex: log.log(logging.DEBUG - 2, "process_data()") for sock, conn in itertools.product(sockets, self.connections): if sock == conn.socket: conn.process_data()
[ "def", "process_data", "(", "self", ",", "sockets", ")", ":", "with", "self", ".", "mutex", ":", "log", ".", "log", "(", "logging", ".", "DEBUG", "-", "2", ",", "\"process_data()\"", ")", "for", "sock", ",", "conn", "in", "itertools", ".", "product", "(", "sockets", ",", "self", ".", "connections", ")", ":", "if", "sock", "==", "conn", ".", "socket", ":", "conn", ".", "process_data", "(", ")" ]
Called when there is more data to read on connection sockets. Arguments: sockets -- A list of socket objects. See documentation for Reactor.__init__.
[ "Called", "when", "there", "is", "more", "data", "to", "read", "on", "connection", "sockets", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L774-L787
-1
251,658
jaraco/irc
irc/client.py
Reactor.process_once
def process_once(self, timeout=0): """Process data from connections once. Arguments: timeout -- How long the select() call should wait if no data is available. This method should be called periodically to check and process incoming data, if there are any. If that seems boring, look at the process_forever method. """ log.log(logging.DEBUG - 2, "process_once()") sockets = self.sockets if sockets: in_, out, err = select.select(sockets, [], [], timeout) self.process_data(in_) else: time.sleep(timeout) self.process_timeout()
python
def process_once(self, timeout=0): """Process data from connections once. Arguments: timeout -- How long the select() call should wait if no data is available. This method should be called periodically to check and process incoming data, if there are any. If that seems boring, look at the process_forever method. """ log.log(logging.DEBUG - 2, "process_once()") sockets = self.sockets if sockets: in_, out, err = select.select(sockets, [], [], timeout) self.process_data(in_) else: time.sleep(timeout) self.process_timeout()
[ "def", "process_once", "(", "self", ",", "timeout", "=", "0", ")", ":", "log", ".", "log", "(", "logging", ".", "DEBUG", "-", "2", ",", "\"process_once()\"", ")", "sockets", "=", "self", ".", "sockets", "if", "sockets", ":", "in_", ",", "out", ",", "err", "=", "select", ".", "select", "(", "sockets", ",", "[", "]", ",", "[", "]", ",", "timeout", ")", "self", ".", "process_data", "(", "in_", ")", "else", ":", "time", ".", "sleep", "(", "timeout", ")", "self", ".", "process_timeout", "(", ")" ]
Process data from connections once. Arguments: timeout -- How long the select() call should wait if no data is available. This method should be called periodically to check and process incoming data, if there are any. If that seems boring, look at the process_forever method.
[ "Process", "data", "from", "connections", "once", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L807-L826
-1
251,659
jaraco/irc
irc/client.py
Reactor.disconnect_all
def disconnect_all(self, message=""): """Disconnects all connections.""" with self.mutex: for conn in self.connections: conn.disconnect(message)
python
def disconnect_all(self, message=""): """Disconnects all connections.""" with self.mutex: for conn in self.connections: conn.disconnect(message)
[ "def", "disconnect_all", "(", "self", ",", "message", "=", "\"\"", ")", ":", "with", "self", ".", "mutex", ":", "for", "conn", "in", "self", ".", "connections", ":", "conn", ".", "disconnect", "(", "message", ")" ]
Disconnects all connections.
[ "Disconnects", "all", "connections", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L844-L848
-1
251,660
jaraco/irc
irc/client.py
Reactor.add_global_handler
def add_global_handler(self, event, handler, priority=0): """Adds a global handler function for a specific event type. Arguments: event -- Event type (a string). Check the values of numeric_events for possible event types. handler -- Callback function taking 'connection' and 'event' parameters. priority -- A number (the lower number, the higher priority). The handler function is called whenever the specified event is triggered in any of the connections. See documentation for the Event class. The handler functions are called in priority order (lowest number is highest priority). If a handler function returns "NO MORE", no more handlers will be called. """ handler = PrioritizedHandler(priority, handler) with self.mutex: event_handlers = self.handlers.setdefault(event, []) bisect.insort(event_handlers, handler)
python
def add_global_handler(self, event, handler, priority=0): """Adds a global handler function for a specific event type. Arguments: event -- Event type (a string). Check the values of numeric_events for possible event types. handler -- Callback function taking 'connection' and 'event' parameters. priority -- A number (the lower number, the higher priority). The handler function is called whenever the specified event is triggered in any of the connections. See documentation for the Event class. The handler functions are called in priority order (lowest number is highest priority). If a handler function returns "NO MORE", no more handlers will be called. """ handler = PrioritizedHandler(priority, handler) with self.mutex: event_handlers = self.handlers.setdefault(event, []) bisect.insort(event_handlers, handler)
[ "def", "add_global_handler", "(", "self", ",", "event", ",", "handler", ",", "priority", "=", "0", ")", ":", "handler", "=", "PrioritizedHandler", "(", "priority", ",", "handler", ")", "with", "self", ".", "mutex", ":", "event_handlers", "=", "self", ".", "handlers", ".", "setdefault", "(", "event", ",", "[", "]", ")", "bisect", ".", "insort", "(", "event_handlers", ",", "handler", ")" ]
Adds a global handler function for a specific event type. Arguments: event -- Event type (a string). Check the values of numeric_events for possible event types. handler -- Callback function taking 'connection' and 'event' parameters. priority -- A number (the lower number, the higher priority). The handler function is called whenever the specified event is triggered in any of the connections. See documentation for the Event class. The handler functions are called in priority order (lowest number is highest priority). If a handler function returns "NO MORE", no more handlers will be called.
[ "Adds", "a", "global", "handler", "function", "for", "a", "specific", "event", "type", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L850-L874
-1
251,661
jaraco/irc
irc/client.py
Reactor.remove_global_handler
def remove_global_handler(self, event, handler): """Removes a global handler function. Arguments: event -- Event type (a string). handler -- Callback function. Returns 1 on success, otherwise 0. """ with self.mutex: if event not in self.handlers: return 0 for h in self.handlers[event]: if handler == h.callback: self.handlers[event].remove(h) return 1
python
def remove_global_handler(self, event, handler): """Removes a global handler function. Arguments: event -- Event type (a string). handler -- Callback function. Returns 1 on success, otherwise 0. """ with self.mutex: if event not in self.handlers: return 0 for h in self.handlers[event]: if handler == h.callback: self.handlers[event].remove(h) return 1
[ "def", "remove_global_handler", "(", "self", ",", "event", ",", "handler", ")", ":", "with", "self", ".", "mutex", ":", "if", "event", "not", "in", "self", ".", "handlers", ":", "return", "0", "for", "h", "in", "self", ".", "handlers", "[", "event", "]", ":", "if", "handler", "==", "h", ".", "callback", ":", "self", ".", "handlers", "[", "event", "]", ".", "remove", "(", "h", ")", "return", "1" ]
Removes a global handler function. Arguments: event -- Event type (a string). handler -- Callback function. Returns 1 on success, otherwise 0.
[ "Removes", "a", "global", "handler", "function", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L876-L892
-1
251,662
jaraco/irc
irc/client.py
Reactor.dcc
def dcc(self, dcctype="chat"): """Creates and returns a DCCConnection object. Arguments: dcctype -- "chat" for DCC CHAT connections or "raw" for DCC SEND (or other DCC types). If "chat", incoming data will be split in newline-separated chunks. If "raw", incoming data is not touched. """ with self.mutex: conn = DCCConnection(self, dcctype) self.connections.append(conn) return conn
python
def dcc(self, dcctype="chat"): """Creates and returns a DCCConnection object. Arguments: dcctype -- "chat" for DCC CHAT connections or "raw" for DCC SEND (or other DCC types). If "chat", incoming data will be split in newline-separated chunks. If "raw", incoming data is not touched. """ with self.mutex: conn = DCCConnection(self, dcctype) self.connections.append(conn) return conn
[ "def", "dcc", "(", "self", ",", "dcctype", "=", "\"chat\"", ")", ":", "with", "self", ".", "mutex", ":", "conn", "=", "DCCConnection", "(", "self", ",", "dcctype", ")", "self", ".", "connections", ".", "append", "(", "conn", ")", "return", "conn" ]
Creates and returns a DCCConnection object. Arguments: dcctype -- "chat" for DCC CHAT connections or "raw" for DCC SEND (or other DCC types). If "chat", incoming data will be split in newline-separated chunks. If "raw", incoming data is not touched.
[ "Creates", "and", "returns", "a", "DCCConnection", "object", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L894-L907
-1
251,663
jaraco/irc
irc/client.py
Reactor._handle_event
def _handle_event(self, connection, event): """ Handle an Event event incoming on ServerConnection connection. """ with self.mutex: matching_handlers = sorted( self.handlers.get("all_events", []) + self.handlers.get(event.type, []) ) for handler in matching_handlers: result = handler.callback(connection, event) if result == "NO MORE": return
python
def _handle_event(self, connection, event): """ Handle an Event event incoming on ServerConnection connection. """ with self.mutex: matching_handlers = sorted( self.handlers.get("all_events", []) + self.handlers.get(event.type, []) ) for handler in matching_handlers: result = handler.callback(connection, event) if result == "NO MORE": return
[ "def", "_handle_event", "(", "self", ",", "connection", ",", "event", ")", ":", "with", "self", ".", "mutex", ":", "matching_handlers", "=", "sorted", "(", "self", ".", "handlers", ".", "get", "(", "\"all_events\"", ",", "[", "]", ")", "+", "self", ".", "handlers", ".", "get", "(", "event", ".", "type", ",", "[", "]", ")", ")", "for", "handler", "in", "matching_handlers", ":", "result", "=", "handler", ".", "callback", "(", "connection", ",", "event", ")", "if", "result", "==", "\"NO MORE\"", ":", "return" ]
Handle an Event event incoming on ServerConnection connection.
[ "Handle", "an", "Event", "event", "incoming", "on", "ServerConnection", "connection", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L909-L921
-1
251,664
jaraco/irc
irc/client.py
DCCConnection.disconnect
def disconnect(self, message=""): """Hang up the connection and close the object. Arguments: message -- Quit message. """ try: del self.connected except AttributeError: return try: self.socket.shutdown(socket.SHUT_WR) self.socket.close() except socket.error: pass del self.socket self.reactor._handle_event( self, Event("dcc_disconnect", self.peeraddress, "", [message])) self.reactor._remove_connection(self)
python
def disconnect(self, message=""): """Hang up the connection and close the object. Arguments: message -- Quit message. """ try: del self.connected except AttributeError: return try: self.socket.shutdown(socket.SHUT_WR) self.socket.close() except socket.error: pass del self.socket self.reactor._handle_event( self, Event("dcc_disconnect", self.peeraddress, "", [message])) self.reactor._remove_connection(self)
[ "def", "disconnect", "(", "self", ",", "message", "=", "\"\"", ")", ":", "try", ":", "del", "self", ".", "connected", "except", "AttributeError", ":", "return", "try", ":", "self", ".", "socket", ".", "shutdown", "(", "socket", ".", "SHUT_WR", ")", "self", ".", "socket", ".", "close", "(", ")", "except", "socket", ".", "error", ":", "pass", "del", "self", ".", "socket", "self", ".", "reactor", ".", "_handle_event", "(", "self", ",", "Event", "(", "\"dcc_disconnect\"", ",", "self", ".", "peeraddress", ",", "\"\"", ",", "[", "message", "]", ")", ")", "self", ".", "reactor", ".", "_remove_connection", "(", "self", ")" ]
Hang up the connection and close the object. Arguments: message -- Quit message.
[ "Hang", "up", "the", "connection", "and", "close", "the", "object", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L1004-L1025
-1
251,665
jaraco/irc
irc/client.py
DCCConnection.privmsg
def privmsg(self, text): """ Send text to DCC peer. The text will be padded with a newline if it's a DCC CHAT session. """ if self.dcctype == 'chat': text += '\n' return self.send_bytes(self.encode(text))
python
def privmsg(self, text): """ Send text to DCC peer. The text will be padded with a newline if it's a DCC CHAT session. """ if self.dcctype == 'chat': text += '\n' return self.send_bytes(self.encode(text))
[ "def", "privmsg", "(", "self", ",", "text", ")", ":", "if", "self", ".", "dcctype", "==", "'chat'", ":", "text", "+=", "'\\n'", "return", "self", ".", "send_bytes", "(", "self", ".", "encode", "(", "text", ")", ")" ]
Send text to DCC peer. The text will be padded with a newline if it's a DCC CHAT session.
[ "Send", "text", "to", "DCC", "peer", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L1081-L1089
-1
251,666
jaraco/irc
irc/client.py
DCCConnection.send_bytes
def send_bytes(self, bytes): """ Send data to DCC peer. """ try: self.socket.send(bytes) log.debug("TO PEER: %r\n", bytes) except socket.error: self.disconnect("Connection reset by peer.")
python
def send_bytes(self, bytes): """ Send data to DCC peer. """ try: self.socket.send(bytes) log.debug("TO PEER: %r\n", bytes) except socket.error: self.disconnect("Connection reset by peer.")
[ "def", "send_bytes", "(", "self", ",", "bytes", ")", ":", "try", ":", "self", ".", "socket", ".", "send", "(", "bytes", ")", "log", ".", "debug", "(", "\"TO PEER: %r\\n\"", ",", "bytes", ")", "except", "socket", ".", "error", ":", "self", ".", "disconnect", "(", "\"Connection reset by peer.\"", ")" ]
Send data to DCC peer.
[ "Send", "data", "to", "DCC", "peer", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L1091-L1099
-1
251,667
jaraco/irc
irc/client.py
SimpleIRCClient.dcc
def dcc(self, *args, **kwargs): """Create and associate a new DCCConnection object. Use the returned object to listen for or connect to a DCC peer. """ dcc = self.reactor.dcc(*args, **kwargs) self.dcc_connections.append(dcc) return dcc
python
def dcc(self, *args, **kwargs): """Create and associate a new DCCConnection object. Use the returned object to listen for or connect to a DCC peer. """ dcc = self.reactor.dcc(*args, **kwargs) self.dcc_connections.append(dcc) return dcc
[ "def", "dcc", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "dcc", "=", "self", ".", "reactor", ".", "dcc", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "dcc_connections", ".", "append", "(", "dcc", ")", "return", "dcc" ]
Create and associate a new DCCConnection object. Use the returned object to listen for or connect to a DCC peer.
[ "Create", "and", "associate", "a", "new", "DCCConnection", "object", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L1162-L1170
-1
251,668
jaraco/irc
irc/client.py
SimpleIRCClient.dcc_connect
def dcc_connect(self, address, port, dcctype="chat"): """Connect to a DCC peer. Arguments: address -- IP address of the peer. port -- Port to connect to. Returns a DCCConnection instance. """ warnings.warn("Use self.dcc(type).connect()", DeprecationWarning) return self.dcc(dcctype).connect(address, port)
python
def dcc_connect(self, address, port, dcctype="chat"): """Connect to a DCC peer. Arguments: address -- IP address of the peer. port -- Port to connect to. Returns a DCCConnection instance. """ warnings.warn("Use self.dcc(type).connect()", DeprecationWarning) return self.dcc(dcctype).connect(address, port)
[ "def", "dcc_connect", "(", "self", ",", "address", ",", "port", ",", "dcctype", "=", "\"chat\"", ")", ":", "warnings", ".", "warn", "(", "\"Use self.dcc(type).connect()\"", ",", "DeprecationWarning", ")", "return", "self", ".", "dcc", "(", "dcctype", ")", ".", "connect", "(", "address", ",", "port", ")" ]
Connect to a DCC peer. Arguments: address -- IP address of the peer. port -- Port to connect to. Returns a DCCConnection instance.
[ "Connect", "to", "a", "DCC", "peer", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L1172-L1184
-1
251,669
jaraco/irc
irc/client.py
SimpleIRCClient.dcc_listen
def dcc_listen(self, dcctype="chat"): """Listen for connections from a DCC peer. Returns a DCCConnection instance. """ warnings.warn("Use self.dcc(type).listen()", DeprecationWarning) return self.dcc(dcctype).listen()
python
def dcc_listen(self, dcctype="chat"): """Listen for connections from a DCC peer. Returns a DCCConnection instance. """ warnings.warn("Use self.dcc(type).listen()", DeprecationWarning) return self.dcc(dcctype).listen()
[ "def", "dcc_listen", "(", "self", ",", "dcctype", "=", "\"chat\"", ")", ":", "warnings", ".", "warn", "(", "\"Use self.dcc(type).listen()\"", ",", "DeprecationWarning", ")", "return", "self", ".", "dcc", "(", "dcctype", ")", ".", "listen", "(", ")" ]
Listen for connections from a DCC peer. Returns a DCCConnection instance.
[ "Listen", "for", "connections", "from", "a", "DCC", "peer", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L1186-L1192
-1
251,670
jaraco/irc
irc/ctcp.py
dequote
def dequote(message): """ Dequote a message according to CTCP specifications. The function returns a list where each element can be either a string (normal message) or a tuple of one or two strings (tagged messages). If a tuple has only one element (ie is a singleton), that element is the tag; otherwise the tuple has two elements: the tag and the data. Arguments: message -- The message to be decoded. """ # Perform the substitution message = low_level_regexp.sub(_low_level_replace, message) if DELIMITER not in message: return [message] # Split it into parts. chunks = message.split(DELIMITER) return list(_gen_messages(chunks))
python
def dequote(message): """ Dequote a message according to CTCP specifications. The function returns a list where each element can be either a string (normal message) or a tuple of one or two strings (tagged messages). If a tuple has only one element (ie is a singleton), that element is the tag; otherwise the tuple has two elements: the tag and the data. Arguments: message -- The message to be decoded. """ # Perform the substitution message = low_level_regexp.sub(_low_level_replace, message) if DELIMITER not in message: return [message] # Split it into parts. chunks = message.split(DELIMITER) return list(_gen_messages(chunks))
[ "def", "dequote", "(", "message", ")", ":", "# Perform the substitution", "message", "=", "low_level_regexp", ".", "sub", "(", "_low_level_replace", ",", "message", ")", "if", "DELIMITER", "not", "in", "message", ":", "return", "[", "message", "]", "# Split it into parts.", "chunks", "=", "message", ".", "split", "(", "DELIMITER", ")", "return", "list", "(", "_gen_messages", "(", "chunks", ")", ")" ]
Dequote a message according to CTCP specifications. The function returns a list where each element can be either a string (normal message) or a tuple of one or two strings (tagged messages). If a tuple has only one element (ie is a singleton), that element is the tag; otherwise the tuple has two elements: the tag and the data. Arguments: message -- The message to be decoded.
[ "Dequote", "a", "message", "according", "to", "CTCP", "specifications", "." ]
571c1f448d5d5bb92bbe2605c33148bf6e698413
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/ctcp.py#L30-L54
-1
251,671
sibson/vncdotool
vncdotool/api.py
connect
def connect(server, password=None, factory_class=VNCDoToolFactory, proxy=ThreadedVNCClientProxy, timeout=None): """ Connect to a VNCServer and return a Client instance that is usable in the main thread of non-Twisted Python Applications, EXPERIMENTAL. >>> from vncdotool import api >>> with api.connect('host') as client >>> client.keyPress('c') You may then call any regular VNCDoToolClient method on client from your application code. If you are using a GUI toolkit or other major async library please read http://twistedmatrix.com/documents/13.0.0/core/howto/choosing-reactor.html for a better method of intergrating vncdotool. """ if not reactor.running: global _THREAD _THREAD = threading.Thread(target=reactor.run, name='Twisted', kwargs={'installSignalHandlers': False}) _THREAD.daemon = True _THREAD.start() observer = PythonLoggingObserver() observer.start() factory = factory_class() if password is not None: factory.password = password family, host, port = command.parse_server(server) client = proxy(factory, timeout) client.connect(host, port=port, family=family) return client
python
def connect(server, password=None, factory_class=VNCDoToolFactory, proxy=ThreadedVNCClientProxy, timeout=None): """ Connect to a VNCServer and return a Client instance that is usable in the main thread of non-Twisted Python Applications, EXPERIMENTAL. >>> from vncdotool import api >>> with api.connect('host') as client >>> client.keyPress('c') You may then call any regular VNCDoToolClient method on client from your application code. If you are using a GUI toolkit or other major async library please read http://twistedmatrix.com/documents/13.0.0/core/howto/choosing-reactor.html for a better method of intergrating vncdotool. """ if not reactor.running: global _THREAD _THREAD = threading.Thread(target=reactor.run, name='Twisted', kwargs={'installSignalHandlers': False}) _THREAD.daemon = True _THREAD.start() observer = PythonLoggingObserver() observer.start() factory = factory_class() if password is not None: factory.password = password family, host, port = command.parse_server(server) client = proxy(factory, timeout) client.connect(host, port=port, family=family) return client
[ "def", "connect", "(", "server", ",", "password", "=", "None", ",", "factory_class", "=", "VNCDoToolFactory", ",", "proxy", "=", "ThreadedVNCClientProxy", ",", "timeout", "=", "None", ")", ":", "if", "not", "reactor", ".", "running", ":", "global", "_THREAD", "_THREAD", "=", "threading", ".", "Thread", "(", "target", "=", "reactor", ".", "run", ",", "name", "=", "'Twisted'", ",", "kwargs", "=", "{", "'installSignalHandlers'", ":", "False", "}", ")", "_THREAD", ".", "daemon", "=", "True", "_THREAD", ".", "start", "(", ")", "observer", "=", "PythonLoggingObserver", "(", ")", "observer", ".", "start", "(", ")", "factory", "=", "factory_class", "(", ")", "if", "password", "is", "not", "None", ":", "factory", ".", "password", "=", "password", "family", ",", "host", ",", "port", "=", "command", ".", "parse_server", "(", "server", ")", "client", "=", "proxy", "(", "factory", ",", "timeout", ")", "client", ".", "connect", "(", "host", ",", "port", "=", "port", ",", "family", "=", "family", ")", "return", "client" ]
Connect to a VNCServer and return a Client instance that is usable in the main thread of non-Twisted Python Applications, EXPERIMENTAL. >>> from vncdotool import api >>> with api.connect('host') as client >>> client.keyPress('c') You may then call any regular VNCDoToolClient method on client from your application code. If you are using a GUI toolkit or other major async library please read http://twistedmatrix.com/documents/13.0.0/core/howto/choosing-reactor.html for a better method of intergrating vncdotool.
[ "Connect", "to", "a", "VNCServer", "and", "return", "a", "Client", "instance", "that", "is", "usable", "in", "the", "main", "thread", "of", "non", "-", "Twisted", "Python", "Applications", "EXPERIMENTAL", "." ]
e133a8916efaa0f5ed421e0aa737196624635b0c
https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/api.py#L121-L156
-1
251,672
sibson/vncdotool
vncdotool/client.py
VNCDoToolClient.keyPress
def keyPress(self, key): """ Send a key press to the server key: string: either [a-z] or a from KEYMAP """ log.debug('keyPress %s', key) self.keyDown(key) self.keyUp(key) return self
python
def keyPress(self, key): """ Send a key press to the server key: string: either [a-z] or a from KEYMAP """ log.debug('keyPress %s', key) self.keyDown(key) self.keyUp(key) return self
[ "def", "keyPress", "(", "self", ",", "key", ")", ":", "log", ".", "debug", "(", "'keyPress %s'", ",", "key", ")", "self", ".", "keyDown", "(", "key", ")", "self", ".", "keyUp", "(", "key", ")", "return", "self" ]
Send a key press to the server key: string: either [a-z] or a from KEYMAP
[ "Send", "a", "key", "press", "to", "the", "server" ]
e133a8916efaa0f5ed421e0aa737196624635b0c
https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/client.py#L165-L174
-1
251,673
sibson/vncdotool
vncdotool/client.py
VNCDoToolClient.mousePress
def mousePress(self, button): """ Send a mouse click at the last set position button: int: [1-n] """ log.debug('mousePress %s', button) buttons = self.buttons | (1 << (button - 1)) self.mouseDown(button) self.mouseUp(button) return self
python
def mousePress(self, button): """ Send a mouse click at the last set position button: int: [1-n] """ log.debug('mousePress %s', button) buttons = self.buttons | (1 << (button - 1)) self.mouseDown(button) self.mouseUp(button) return self
[ "def", "mousePress", "(", "self", ",", "button", ")", ":", "log", ".", "debug", "(", "'mousePress %s'", ",", "button", ")", "buttons", "=", "self", ".", "buttons", "|", "(", "1", "<<", "(", "button", "-", "1", ")", ")", "self", ".", "mouseDown", "(", "button", ")", "self", ".", "mouseUp", "(", "button", ")", "return", "self" ]
Send a mouse click at the last set position button: int: [1-n]
[ "Send", "a", "mouse", "click", "at", "the", "last", "set", "position" ]
e133a8916efaa0f5ed421e0aa737196624635b0c
https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/client.py#L192-L203
-1
251,674
sibson/vncdotool
vncdotool/client.py
VNCDoToolClient.mouseDown
def mouseDown(self, button): """ Send a mouse button down at the last set position button: int: [1-n] """ log.debug('mouseDown %s', button) self.buttons |= 1 << (button - 1) self.pointerEvent(self.x, self.y, buttonmask=self.buttons) return self
python
def mouseDown(self, button): """ Send a mouse button down at the last set position button: int: [1-n] """ log.debug('mouseDown %s', button) self.buttons |= 1 << (button - 1) self.pointerEvent(self.x, self.y, buttonmask=self.buttons) return self
[ "def", "mouseDown", "(", "self", ",", "button", ")", ":", "log", ".", "debug", "(", "'mouseDown %s'", ",", "button", ")", "self", ".", "buttons", "|=", "1", "<<", "(", "button", "-", "1", ")", "self", ".", "pointerEvent", "(", "self", ".", "x", ",", "self", ".", "y", ",", "buttonmask", "=", "self", ".", "buttons", ")", "return", "self" ]
Send a mouse button down at the last set position button: int: [1-n]
[ "Send", "a", "mouse", "button", "down", "at", "the", "last", "set", "position" ]
e133a8916efaa0f5ed421e0aa737196624635b0c
https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/client.py#L205-L215
-1
251,675
sibson/vncdotool
vncdotool/client.py
VNCDoToolClient.captureRegion
def captureRegion(self, filename, x, y, w, h): """ Save a region of the current display to filename """ log.debug('captureRegion %s', filename) return self._capture(filename, x, y, x+w, y+h)
python
def captureRegion(self, filename, x, y, w, h): """ Save a region of the current display to filename """ log.debug('captureRegion %s', filename) return self._capture(filename, x, y, x+w, y+h)
[ "def", "captureRegion", "(", "self", ",", "filename", ",", "x", ",", "y", ",", "w", ",", "h", ")", ":", "log", ".", "debug", "(", "'captureRegion %s'", ",", "filename", ")", "return", "self", ".", "_capture", "(", "filename", ",", "x", ",", "y", ",", "x", "+", "w", ",", "y", "+", "h", ")" ]
Save a region of the current display to filename
[ "Save", "a", "region", "of", "the", "current", "display", "to", "filename" ]
e133a8916efaa0f5ed421e0aa737196624635b0c
https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/client.py#L235-L239
-1
251,676
sibson/vncdotool
vncdotool/client.py
VNCDoToolClient.expectScreen
def expectScreen(self, filename, maxrms=0): """ Wait until the display matches a target image filename: an image file to read and compare against maxrms: the maximum root mean square between histograms of the screen and target image """ log.debug('expectScreen %s', filename) return self._expectFramebuffer(filename, 0, 0, maxrms)
python
def expectScreen(self, filename, maxrms=0): """ Wait until the display matches a target image filename: an image file to read and compare against maxrms: the maximum root mean square between histograms of the screen and target image """ log.debug('expectScreen %s', filename) return self._expectFramebuffer(filename, 0, 0, maxrms)
[ "def", "expectScreen", "(", "self", ",", "filename", ",", "maxrms", "=", "0", ")", ":", "log", ".", "debug", "(", "'expectScreen %s'", ",", "filename", ")", "return", "self", ".", "_expectFramebuffer", "(", "filename", ",", "0", ",", "0", ",", "maxrms", ")" ]
Wait until the display matches a target image filename: an image file to read and compare against maxrms: the maximum root mean square between histograms of the screen and target image
[ "Wait", "until", "the", "display", "matches", "a", "target", "image" ]
e133a8916efaa0f5ed421e0aa737196624635b0c
https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/client.py#L261-L269
-1
251,677
sibson/vncdotool
vncdotool/client.py
VNCDoToolClient.expectRegion
def expectRegion(self, filename, x, y, maxrms=0): """ Wait until a portion of the screen matches the target image The region compared is defined by the box (x, y), (x + image.width, y + image.height) """ log.debug('expectRegion %s (%s, %s)', filename, x, y) return self._expectFramebuffer(filename, x, y, maxrms)
python
def expectRegion(self, filename, x, y, maxrms=0): """ Wait until a portion of the screen matches the target image The region compared is defined by the box (x, y), (x + image.width, y + image.height) """ log.debug('expectRegion %s (%s, %s)', filename, x, y) return self._expectFramebuffer(filename, x, y, maxrms)
[ "def", "expectRegion", "(", "self", ",", "filename", ",", "x", ",", "y", ",", "maxrms", "=", "0", ")", ":", "log", ".", "debug", "(", "'expectRegion %s (%s, %s)'", ",", "filename", ",", "x", ",", "y", ")", "return", "self", ".", "_expectFramebuffer", "(", "filename", ",", "x", ",", "y", ",", "maxrms", ")" ]
Wait until a portion of the screen matches the target image The region compared is defined by the box (x, y), (x + image.width, y + image.height)
[ "Wait", "until", "a", "portion", "of", "the", "screen", "matches", "the", "target", "image" ]
e133a8916efaa0f5ed421e0aa737196624635b0c
https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/client.py#L271-L278
-1
251,678
sibson/vncdotool
vncdotool/client.py
VNCDoToolClient.setImageMode
def setImageMode(self): """ Extracts color ordering and 24 vs. 32 bpp info out of the pixel format information """ if self._version_server == 3.889: self.setPixelFormat( bpp = 16, depth = 16, bigendian = 0, truecolor = 1, redmax = 31, greenmax = 63, bluemax = 31, redshift = 11, greenshift = 5, blueshift = 0 ) self.image_mode = "BGR;16" elif (self.truecolor and (not self.bigendian) and self.depth == 24 and self.redmax == 255 and self.greenmax == 255 and self.bluemax == 255): pixel = ["X"] * self.bypp offsets = [offset // 8 for offset in (self.redshift, self.greenshift, self.blueshift)] for offset, color in zip(offsets, "RGB"): pixel[offset] = color self.image_mode = "".join(pixel) else: self.setPixelFormat()
python
def setImageMode(self): """ Extracts color ordering and 24 vs. 32 bpp info out of the pixel format information """ if self._version_server == 3.889: self.setPixelFormat( bpp = 16, depth = 16, bigendian = 0, truecolor = 1, redmax = 31, greenmax = 63, bluemax = 31, redshift = 11, greenshift = 5, blueshift = 0 ) self.image_mode = "BGR;16" elif (self.truecolor and (not self.bigendian) and self.depth == 24 and self.redmax == 255 and self.greenmax == 255 and self.bluemax == 255): pixel = ["X"] * self.bypp offsets = [offset // 8 for offset in (self.redshift, self.greenshift, self.blueshift)] for offset, color in zip(offsets, "RGB"): pixel[offset] = color self.image_mode = "".join(pixel) else: self.setPixelFormat()
[ "def", "setImageMode", "(", "self", ")", ":", "if", "self", ".", "_version_server", "==", "3.889", ":", "self", ".", "setPixelFormat", "(", "bpp", "=", "16", ",", "depth", "=", "16", ",", "bigendian", "=", "0", ",", "truecolor", "=", "1", ",", "redmax", "=", "31", ",", "greenmax", "=", "63", ",", "bluemax", "=", "31", ",", "redshift", "=", "11", ",", "greenshift", "=", "5", ",", "blueshift", "=", "0", ")", "self", ".", "image_mode", "=", "\"BGR;16\"", "elif", "(", "self", ".", "truecolor", "and", "(", "not", "self", ".", "bigendian", ")", "and", "self", ".", "depth", "==", "24", "and", "self", ".", "redmax", "==", "255", "and", "self", ".", "greenmax", "==", "255", "and", "self", ".", "bluemax", "==", "255", ")", ":", "pixel", "=", "[", "\"X\"", "]", "*", "self", ".", "bypp", "offsets", "=", "[", "offset", "//", "8", "for", "offset", "in", "(", "self", ".", "redshift", ",", "self", ".", "greenshift", ",", "self", ".", "blueshift", ")", "]", "for", "offset", ",", "color", "in", "zip", "(", "offsets", ",", "\"RGB\"", ")", ":", "pixel", "[", "offset", "]", "=", "color", "self", ".", "image_mode", "=", "\"\"", ".", "join", "(", "pixel", ")", "else", ":", "self", ".", "setPixelFormat", "(", ")" ]
Extracts color ordering and 24 vs. 32 bpp info out of the pixel format information
[ "Extracts", "color", "ordering", "and", "24", "vs", ".", "32", "bpp", "info", "out", "of", "the", "pixel", "format", "information" ]
e133a8916efaa0f5ed421e0aa737196624635b0c
https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/client.py#L344-L363
-1
251,679
sibson/vncdotool
vncdotool/rfb.py
RFBClient._handleDecodeHextileRAW
def _handleDecodeHextileRAW(self, block, bg, color, x, y, width, height, tx, ty, tw, th): """the tile is in raw encoding""" self.updateRectangle(tx, ty, tw, th, block) self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
python
def _handleDecodeHextileRAW(self, block, bg, color, x, y, width, height, tx, ty, tw, th): """the tile is in raw encoding""" self.updateRectangle(tx, ty, tw, th, block) self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
[ "def", "_handleDecodeHextileRAW", "(", "self", ",", "block", ",", "bg", ",", "color", ",", "x", ",", "y", ",", "width", ",", "height", ",", "tx", ",", "ty", ",", "tw", ",", "th", ")", ":", "self", ".", "updateRectangle", "(", "tx", ",", "ty", ",", "tw", ",", "th", ",", "block", ")", "self", ".", "_doNextHextileSubrect", "(", "bg", ",", "color", ",", "x", ",", "y", ",", "width", ",", "height", ",", "tx", ",", "ty", ")" ]
the tile is in raw encoding
[ "the", "tile", "is", "in", "raw", "encoding" ]
e133a8916efaa0f5ed421e0aa737196624635b0c
https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/rfb.py#L452-L455
-1
251,680
sibson/vncdotool
vncdotool/rfb.py
RFBClient._handleDecodeHextileSubrectsColoured
def _handleDecodeHextileSubrectsColoured(self, block, bg, color, subrects, x, y, width, height, tx, ty, tw, th): """subrects with their own color""" sz = self.bypp + 2 pos = 0 end = len(block) while pos < end: pos2 = pos + self.bypp color = block[pos:pos2] xy = ord(block[pos2]) wh = ord(block[pos2+1]) sx = xy >> 4 sy = xy & 0xf sw = (wh >> 4) + 1 sh = (wh & 0xf) + 1 self.fillRectangle(tx + sx, ty + sy, sw, sh, color) pos += sz self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
python
def _handleDecodeHextileSubrectsColoured(self, block, bg, color, subrects, x, y, width, height, tx, ty, tw, th): """subrects with their own color""" sz = self.bypp + 2 pos = 0 end = len(block) while pos < end: pos2 = pos + self.bypp color = block[pos:pos2] xy = ord(block[pos2]) wh = ord(block[pos2+1]) sx = xy >> 4 sy = xy & 0xf sw = (wh >> 4) + 1 sh = (wh & 0xf) + 1 self.fillRectangle(tx + sx, ty + sy, sw, sh, color) pos += sz self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
[ "def", "_handleDecodeHextileSubrectsColoured", "(", "self", ",", "block", ",", "bg", ",", "color", ",", "subrects", ",", "x", ",", "y", ",", "width", ",", "height", ",", "tx", ",", "ty", ",", "tw", ",", "th", ")", ":", "sz", "=", "self", ".", "bypp", "+", "2", "pos", "=", "0", "end", "=", "len", "(", "block", ")", "while", "pos", "<", "end", ":", "pos2", "=", "pos", "+", "self", ".", "bypp", "color", "=", "block", "[", "pos", ":", "pos2", "]", "xy", "=", "ord", "(", "block", "[", "pos2", "]", ")", "wh", "=", "ord", "(", "block", "[", "pos2", "+", "1", "]", ")", "sx", "=", "xy", ">>", "4", "sy", "=", "xy", "&", "0xf", "sw", "=", "(", "wh", ">>", "4", ")", "+", "1", "sh", "=", "(", "wh", "&", "0xf", ")", "+", "1", "self", ".", "fillRectangle", "(", "tx", "+", "sx", ",", "ty", "+", "sy", ",", "sw", ",", "sh", ",", "color", ")", "pos", "+=", "sz", "self", ".", "_doNextHextileSubrect", "(", "bg", ",", "color", ",", "x", ",", "y", ",", "width", ",", "height", ",", "tx", ",", "ty", ")" ]
subrects with their own color
[ "subrects", "with", "their", "own", "color" ]
e133a8916efaa0f5ed421e0aa737196624635b0c
https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/rfb.py#L457-L473
-1
251,681
sibson/vncdotool
vncdotool/rfb.py
RFBClient.fillRectangle
def fillRectangle(self, x, y, width, height, color): """fill the area with the color. the color is a string in the pixel format set up earlier""" #fallback variant, use update recatngle #override with specialized function for better performance self.updateRectangle(x, y, width, height, color*width*height)
python
def fillRectangle(self, x, y, width, height, color): """fill the area with the color. the color is a string in the pixel format set up earlier""" #fallback variant, use update recatngle #override with specialized function for better performance self.updateRectangle(x, y, width, height, color*width*height)
[ "def", "fillRectangle", "(", "self", ",", "x", ",", "y", ",", "width", ",", "height", ",", "color", ")", ":", "#fallback variant, use update recatngle", "#override with specialized function for better performance", "self", ".", "updateRectangle", "(", "x", ",", "y", ",", "width", ",", "height", ",", "color", "*", "width", "*", "height", ")" ]
fill the area with the color. the color is a string in the pixel format set up earlier
[ "fill", "the", "area", "with", "the", "color", ".", "the", "color", "is", "a", "string", "in", "the", "pixel", "format", "set", "up", "earlier" ]
e133a8916efaa0f5ed421e0aa737196624635b0c
https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/rfb.py#L634-L639
-1
251,682
sibson/vncdotool
vncdotool/rfb.py
RFBDes.setKey
def setKey(self, key): """RFB protocol for authentication requires client to encrypt challenge sent by server with password using DES method. However, bits in each byte of the password are put in reverse order before using it as encryption key.""" newkey = [] for ki in range(len(key)): bsrc = ord(key[ki]) btgt = 0 for i in range(8): if bsrc & (1 << i): btgt = btgt | (1 << 7-i) newkey.append(chr(btgt)) super(RFBDes, self).setKey(newkey)
python
def setKey(self, key): """RFB protocol for authentication requires client to encrypt challenge sent by server with password using DES method. However, bits in each byte of the password are put in reverse order before using it as encryption key.""" newkey = [] for ki in range(len(key)): bsrc = ord(key[ki]) btgt = 0 for i in range(8): if bsrc & (1 << i): btgt = btgt | (1 << 7-i) newkey.append(chr(btgt)) super(RFBDes, self).setKey(newkey)
[ "def", "setKey", "(", "self", ",", "key", ")", ":", "newkey", "=", "[", "]", "for", "ki", "in", "range", "(", "len", "(", "key", ")", ")", ":", "bsrc", "=", "ord", "(", "key", "[", "ki", "]", ")", "btgt", "=", "0", "for", "i", "in", "range", "(", "8", ")", ":", "if", "bsrc", "&", "(", "1", "<<", "i", ")", ":", "btgt", "=", "btgt", "|", "(", "1", "<<", "7", "-", "i", ")", "newkey", ".", "append", "(", "chr", "(", "btgt", ")", ")", "super", "(", "RFBDes", ",", "self", ")", ".", "setKey", "(", "newkey", ")" ]
RFB protocol for authentication requires client to encrypt challenge sent by server with password using DES method. However, bits in each byte of the password are put in reverse order before using it as encryption key.
[ "RFB", "protocol", "for", "authentication", "requires", "client", "to", "encrypt", "challenge", "sent", "by", "server", "with", "password", "using", "DES", "method", ".", "However", "bits", "in", "each", "byte", "of", "the", "password", "are", "put", "in", "reverse", "order", "before", "using", "it", "as", "encryption", "key", "." ]
e133a8916efaa0f5ed421e0aa737196624635b0c
https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/rfb.py#L667-L680
-1
251,683
meraki-analytics/cassiopeia
cassiopeia/core/league.py
MiniSeries.not_played
def not_played(self) -> int: """The number of games in the player's promos that they haven't played yet.""" return len(self._data[MiniSeriesData].progress) - len(self.progress)
python
def not_played(self) -> int: """The number of games in the player's promos that they haven't played yet.""" return len(self._data[MiniSeriesData].progress) - len(self.progress)
[ "def", "not_played", "(", "self", ")", "->", "int", ":", "return", "len", "(", "self", ".", "_data", "[", "MiniSeriesData", "]", ".", "progress", ")", "-", "len", "(", "self", ".", "progress", ")" ]
The number of games in the player's promos that they haven't played yet.
[ "The", "number", "of", "games", "in", "the", "player", "s", "promos", "that", "they", "haven", "t", "played", "yet", "." ]
de3db568586b34c0edf1f7736279485a4510822f
https://github.com/meraki-analytics/cassiopeia/blob/de3db568586b34c0edf1f7736279485a4510822f/cassiopeia/core/league.py#L134-L136
-1
251,684
meraki-analytics/cassiopeia
cassiopeia/datastores/uniquekeys.py
_rgetattr
def _rgetattr(obj, key): """Recursive getattr for handling dots in keys.""" for k in key.split("."): obj = getattr(obj, k) return obj
python
def _rgetattr(obj, key): """Recursive getattr for handling dots in keys.""" for k in key.split("."): obj = getattr(obj, k) return obj
[ "def", "_rgetattr", "(", "obj", ",", "key", ")", ":", "for", "k", "in", "key", ".", "split", "(", "\".\"", ")", ":", "obj", "=", "getattr", "(", "obj", ",", "k", ")", "return", "obj" ]
Recursive getattr for handling dots in keys.
[ "Recursive", "getattr", "for", "handling", "dots", "in", "keys", "." ]
de3db568586b34c0edf1f7736279485a4510822f
https://github.com/meraki-analytics/cassiopeia/blob/de3db568586b34c0edf1f7736279485a4510822f/cassiopeia/datastores/uniquekeys.py#L37-L41
-1
251,685
wong2/pick
pick/__init__.py
Picker.draw
def draw(self): """draw the curses ui on the screen, handle scroll if needed""" self.screen.clear() x, y = 1, 1 # start point max_y, max_x = self.screen.getmaxyx() max_rows = max_y - y # the max rows we can draw lines, current_line = self.get_lines() # calculate how many lines we should scroll, relative to the top scroll_top = getattr(self, 'scroll_top', 0) if current_line <= scroll_top: scroll_top = 0 elif current_line - scroll_top > max_rows: scroll_top = current_line - max_rows self.scroll_top = scroll_top lines_to_draw = lines[scroll_top:scroll_top+max_rows] for line in lines_to_draw: if type(line) is tuple: self.screen.addnstr(y, x, line[0], max_x-2, line[1]) else: self.screen.addnstr(y, x, line, max_x-2) y += 1 self.screen.refresh()
python
def draw(self): """draw the curses ui on the screen, handle scroll if needed""" self.screen.clear() x, y = 1, 1 # start point max_y, max_x = self.screen.getmaxyx() max_rows = max_y - y # the max rows we can draw lines, current_line = self.get_lines() # calculate how many lines we should scroll, relative to the top scroll_top = getattr(self, 'scroll_top', 0) if current_line <= scroll_top: scroll_top = 0 elif current_line - scroll_top > max_rows: scroll_top = current_line - max_rows self.scroll_top = scroll_top lines_to_draw = lines[scroll_top:scroll_top+max_rows] for line in lines_to_draw: if type(line) is tuple: self.screen.addnstr(y, x, line[0], max_x-2, line[1]) else: self.screen.addnstr(y, x, line, max_x-2) y += 1 self.screen.refresh()
[ "def", "draw", "(", "self", ")", ":", "self", ".", "screen", ".", "clear", "(", ")", "x", ",", "y", "=", "1", ",", "1", "# start point", "max_y", ",", "max_x", "=", "self", ".", "screen", ".", "getmaxyx", "(", ")", "max_rows", "=", "max_y", "-", "y", "# the max rows we can draw", "lines", ",", "current_line", "=", "self", ".", "get_lines", "(", ")", "# calculate how many lines we should scroll, relative to the top", "scroll_top", "=", "getattr", "(", "self", ",", "'scroll_top'", ",", "0", ")", "if", "current_line", "<=", "scroll_top", ":", "scroll_top", "=", "0", "elif", "current_line", "-", "scroll_top", ">", "max_rows", ":", "scroll_top", "=", "current_line", "-", "max_rows", "self", ".", "scroll_top", "=", "scroll_top", "lines_to_draw", "=", "lines", "[", "scroll_top", ":", "scroll_top", "+", "max_rows", "]", "for", "line", "in", "lines_to_draw", ":", "if", "type", "(", "line", ")", "is", "tuple", ":", "self", ".", "screen", ".", "addnstr", "(", "y", ",", "x", ",", "line", "[", "0", "]", ",", "max_x", "-", "2", ",", "line", "[", "1", "]", ")", "else", ":", "self", ".", "screen", ".", "addnstr", "(", "y", ",", "x", ",", "line", ",", "max_x", "-", "2", ")", "y", "+=", "1", "self", ".", "screen", ".", "refresh", "(", ")" ]
draw the curses ui on the screen, handle scroll if needed
[ "draw", "the", "curses", "ui", "on", "the", "screen", "handle", "scroll", "if", "needed" ]
bde1809387b17a0dd0b3250f03039e9123ecd9c7
https://github.com/wong2/pick/blob/bde1809387b17a0dd0b3250f03039e9123ecd9c7/pick/__init__.py#L114-L141
-1
251,686
chovanecm/sacredboard
sacredboard/app/webapi/files.py
get_file
def get_file(file_id: str, download): """ Get a specific file from GridFS. Returns a binary stream response or HTTP 404 if not found. """ data = current_app.config["data"] # type: DataStorage dao = data.get_files_dao() file_fp, filename, upload_date = dao.get(file_id) if download: mime = mimetypes.guess_type(filename)[0] if mime is None: # unknown type mime = "binary/octet-stream" basename = os.path.basename(filename) return send_file(file_fp, mimetype=mime, attachment_filename=basename, as_attachment=True) else: rawdata = file_fp.read() try: text = rawdata.decode('utf-8') except UnicodeDecodeError: # not decodable as utf-8 text = _get_binary_info(rawdata) html = render_template("api/file_view.html", content=text) file_fp.close() return Response(html)
python
def get_file(file_id: str, download): """ Get a specific file from GridFS. Returns a binary stream response or HTTP 404 if not found. """ data = current_app.config["data"] # type: DataStorage dao = data.get_files_dao() file_fp, filename, upload_date = dao.get(file_id) if download: mime = mimetypes.guess_type(filename)[0] if mime is None: # unknown type mime = "binary/octet-stream" basename = os.path.basename(filename) return send_file(file_fp, mimetype=mime, attachment_filename=basename, as_attachment=True) else: rawdata = file_fp.read() try: text = rawdata.decode('utf-8') except UnicodeDecodeError: # not decodable as utf-8 text = _get_binary_info(rawdata) html = render_template("api/file_view.html", content=text) file_fp.close() return Response(html)
[ "def", "get_file", "(", "file_id", ":", "str", ",", "download", ")", ":", "data", "=", "current_app", ".", "config", "[", "\"data\"", "]", "# type: DataStorage", "dao", "=", "data", ".", "get_files_dao", "(", ")", "file_fp", ",", "filename", ",", "upload_date", "=", "dao", ".", "get", "(", "file_id", ")", "if", "download", ":", "mime", "=", "mimetypes", ".", "guess_type", "(", "filename", ")", "[", "0", "]", "if", "mime", "is", "None", ":", "# unknown type", "mime", "=", "\"binary/octet-stream\"", "basename", "=", "os", ".", "path", ".", "basename", "(", "filename", ")", "return", "send_file", "(", "file_fp", ",", "mimetype", "=", "mime", ",", "attachment_filename", "=", "basename", ",", "as_attachment", "=", "True", ")", "else", ":", "rawdata", "=", "file_fp", ".", "read", "(", ")", "try", ":", "text", "=", "rawdata", ".", "decode", "(", "'utf-8'", ")", "except", "UnicodeDecodeError", ":", "# not decodable as utf-8", "text", "=", "_get_binary_info", "(", "rawdata", ")", "html", "=", "render_template", "(", "\"api/file_view.html\"", ",", "content", "=", "text", ")", "file_fp", ".", "close", "(", ")", "return", "Response", "(", "html", ")" ]
Get a specific file from GridFS. Returns a binary stream response or HTTP 404 if not found.
[ "Get", "a", "specific", "file", "from", "GridFS", "." ]
47e1c99e3be3c1b099d3772bc077f5666020eb0b
https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/webapi/files.py#L36-L64
-1
251,687
chovanecm/sacredboard
sacredboard/app/webapi/files.py
get_files_zip
def get_files_zip(run_id: int, filetype: _FileType): """Send all artifacts or sources of a run as ZIP.""" data = current_app.config["data"] dao_runs = data.get_run_dao() dao_files = data.get_files_dao() run = dao_runs.get(run_id) if filetype == _FileType.ARTIFACT: target_files = run['artifacts'] elif filetype == _FileType.SOURCE: target_files = run['experiment']['sources'] else: raise Exception("Unknown file type: %s" % filetype) memory_file = io.BytesIO() with zipfile.ZipFile(memory_file, 'w') as zf: for f in target_files: # source and artifact files use a different data structure file_id = f['file_id'] if 'file_id' in f else f[1] file, filename, upload_date = dao_files.get(file_id) data = zipfile.ZipInfo(filename, date_time=upload_date.timetuple()) data.compress_type = zipfile.ZIP_DEFLATED zf.writestr(data, file.read()) memory_file.seek(0) fn_suffix = _filetype_suffices[filetype] return send_file(memory_file, attachment_filename='run{}_{}.zip'.format(run_id, fn_suffix), as_attachment=True)
python
def get_files_zip(run_id: int, filetype: _FileType): """Send all artifacts or sources of a run as ZIP.""" data = current_app.config["data"] dao_runs = data.get_run_dao() dao_files = data.get_files_dao() run = dao_runs.get(run_id) if filetype == _FileType.ARTIFACT: target_files = run['artifacts'] elif filetype == _FileType.SOURCE: target_files = run['experiment']['sources'] else: raise Exception("Unknown file type: %s" % filetype) memory_file = io.BytesIO() with zipfile.ZipFile(memory_file, 'w') as zf: for f in target_files: # source and artifact files use a different data structure file_id = f['file_id'] if 'file_id' in f else f[1] file, filename, upload_date = dao_files.get(file_id) data = zipfile.ZipInfo(filename, date_time=upload_date.timetuple()) data.compress_type = zipfile.ZIP_DEFLATED zf.writestr(data, file.read()) memory_file.seek(0) fn_suffix = _filetype_suffices[filetype] return send_file(memory_file, attachment_filename='run{}_{}.zip'.format(run_id, fn_suffix), as_attachment=True)
[ "def", "get_files_zip", "(", "run_id", ":", "int", ",", "filetype", ":", "_FileType", ")", ":", "data", "=", "current_app", ".", "config", "[", "\"data\"", "]", "dao_runs", "=", "data", ".", "get_run_dao", "(", ")", "dao_files", "=", "data", ".", "get_files_dao", "(", ")", "run", "=", "dao_runs", ".", "get", "(", "run_id", ")", "if", "filetype", "==", "_FileType", ".", "ARTIFACT", ":", "target_files", "=", "run", "[", "'artifacts'", "]", "elif", "filetype", "==", "_FileType", ".", "SOURCE", ":", "target_files", "=", "run", "[", "'experiment'", "]", "[", "'sources'", "]", "else", ":", "raise", "Exception", "(", "\"Unknown file type: %s\"", "%", "filetype", ")", "memory_file", "=", "io", ".", "BytesIO", "(", ")", "with", "zipfile", ".", "ZipFile", "(", "memory_file", ",", "'w'", ")", "as", "zf", ":", "for", "f", "in", "target_files", ":", "# source and artifact files use a different data structure", "file_id", "=", "f", "[", "'file_id'", "]", "if", "'file_id'", "in", "f", "else", "f", "[", "1", "]", "file", ",", "filename", ",", "upload_date", "=", "dao_files", ".", "get", "(", "file_id", ")", "data", "=", "zipfile", ".", "ZipInfo", "(", "filename", ",", "date_time", "=", "upload_date", ".", "timetuple", "(", ")", ")", "data", ".", "compress_type", "=", "zipfile", ".", "ZIP_DEFLATED", "zf", ".", "writestr", "(", "data", ",", "file", ".", "read", "(", ")", ")", "memory_file", ".", "seek", "(", "0", ")", "fn_suffix", "=", "_filetype_suffices", "[", "filetype", "]", "return", "send_file", "(", "memory_file", ",", "attachment_filename", "=", "'run{}_{}.zip'", ".", "format", "(", "run_id", ",", "fn_suffix", ")", ",", "as_attachment", "=", "True", ")" ]
Send all artifacts or sources of a run as ZIP.
[ "Send", "all", "artifacts", "or", "sources", "of", "a", "run", "as", "ZIP", "." ]
47e1c99e3be3c1b099d3772bc077f5666020eb0b
https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/webapi/files.py#L67-L93
-1
251,688
chovanecm/sacredboard
sacredboard/app/data/pymongo/filesdao.py
MongoFilesDAO.get
def get(self, file_id: Union[str, bson.ObjectId]) -> [typing.BinaryIO, str, datetime.datetime]: """ Return the file identified by a file_id string. The return value is a file-like object which also has the following attributes: filename: str upload_date: datetime """ if isinstance(file_id, str): file_id = bson.ObjectId(file_id) file = self._fs.get(file_id) return file, file.filename, file.upload_date
python
def get(self, file_id: Union[str, bson.ObjectId]) -> [typing.BinaryIO, str, datetime.datetime]: """ Return the file identified by a file_id string. The return value is a file-like object which also has the following attributes: filename: str upload_date: datetime """ if isinstance(file_id, str): file_id = bson.ObjectId(file_id) file = self._fs.get(file_id) return file, file.filename, file.upload_date
[ "def", "get", "(", "self", ",", "file_id", ":", "Union", "[", "str", ",", "bson", ".", "ObjectId", "]", ")", "->", "[", "typing", ".", "BinaryIO", ",", "str", ",", "datetime", ".", "datetime", "]", ":", "if", "isinstance", "(", "file_id", ",", "str", ")", ":", "file_id", "=", "bson", ".", "ObjectId", "(", "file_id", ")", "file", "=", "self", ".", "_fs", ".", "get", "(", "file_id", ")", "return", "file", ",", "file", ".", "filename", ",", "file", ".", "upload_date" ]
Return the file identified by a file_id string. The return value is a file-like object which also has the following attributes: filename: str upload_date: datetime
[ "Return", "the", "file", "identified", "by", "a", "file_id", "string", "." ]
47e1c99e3be3c1b099d3772bc077f5666020eb0b
https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/data/pymongo/filesdao.py#L27-L38
-1
251,689
chovanecm/sacredboard
sacredboard/app/data/pymongo/genericdao.py
GenericDAO.find_record
def find_record(self, collection_name, query): """ Return the first record mathing the given Mongo query. :param collection_name: Name of the collection to search in. :param query: MongoDB Query, e.g. {_id: 123} :return: A single MongoDB record or None if not found. :raise DataSourceError """ cursor = self._get_collection(collection_name).find(query) for record in cursor: # Return the first record found. return record # Return None if nothing found. return None
python
def find_record(self, collection_name, query): """ Return the first record mathing the given Mongo query. :param collection_name: Name of the collection to search in. :param query: MongoDB Query, e.g. {_id: 123} :return: A single MongoDB record or None if not found. :raise DataSourceError """ cursor = self._get_collection(collection_name).find(query) for record in cursor: # Return the first record found. return record # Return None if nothing found. return None
[ "def", "find_record", "(", "self", ",", "collection_name", ",", "query", ")", ":", "cursor", "=", "self", ".", "_get_collection", "(", "collection_name", ")", ".", "find", "(", "query", ")", "for", "record", "in", "cursor", ":", "# Return the first record found.", "return", "record", "# Return None if nothing found.", "return", "None" ]
Return the first record mathing the given Mongo query. :param collection_name: Name of the collection to search in. :param query: MongoDB Query, e.g. {_id: 123} :return: A single MongoDB record or None if not found. :raise DataSourceError
[ "Return", "the", "first", "record", "mathing", "the", "given", "Mongo", "query", "." ]
47e1c99e3be3c1b099d3772bc077f5666020eb0b
https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/data/pymongo/genericdao.py#L32-L47
-1
251,690
chovanecm/sacredboard
sacredboard/app/data/pymongo/genericdao.py
GenericDAO.find_records
def find_records(self, collection_name, query={}, sort_by=None, sort_direction=None, start=0, limit=None): """ Return a cursor of records from the given MongoDB collection. :param collection_name: Name of the MongoDB collection to query. :param query: Standard MongoDB query. By default no restriction. :param sort_by: Name of a single field to sort by. :param sort_direction: The direction to sort, "asc" or "desc". :param start: Skip first n results. :param limit: The maximum number of results to return. :return: Cursor -- An iterable with results. :raise DataSourceError """ cursor = self._get_collection(collection_name).find(query) if sort_by is not None: cursor = self._apply_sort(cursor, sort_by, sort_direction) cursor = cursor.skip(start) if limit is not None: cursor = cursor.limit(limit) return MongoDbCursor(cursor)
python
def find_records(self, collection_name, query={}, sort_by=None, sort_direction=None, start=0, limit=None): """ Return a cursor of records from the given MongoDB collection. :param collection_name: Name of the MongoDB collection to query. :param query: Standard MongoDB query. By default no restriction. :param sort_by: Name of a single field to sort by. :param sort_direction: The direction to sort, "asc" or "desc". :param start: Skip first n results. :param limit: The maximum number of results to return. :return: Cursor -- An iterable with results. :raise DataSourceError """ cursor = self._get_collection(collection_name).find(query) if sort_by is not None: cursor = self._apply_sort(cursor, sort_by, sort_direction) cursor = cursor.skip(start) if limit is not None: cursor = cursor.limit(limit) return MongoDbCursor(cursor)
[ "def", "find_records", "(", "self", ",", "collection_name", ",", "query", "=", "{", "}", ",", "sort_by", "=", "None", ",", "sort_direction", "=", "None", ",", "start", "=", "0", ",", "limit", "=", "None", ")", ":", "cursor", "=", "self", ".", "_get_collection", "(", "collection_name", ")", ".", "find", "(", "query", ")", "if", "sort_by", "is", "not", "None", ":", "cursor", "=", "self", ".", "_apply_sort", "(", "cursor", ",", "sort_by", ",", "sort_direction", ")", "cursor", "=", "cursor", ".", "skip", "(", "start", ")", "if", "limit", "is", "not", "None", ":", "cursor", "=", "cursor", ".", "limit", "(", "limit", ")", "return", "MongoDbCursor", "(", "cursor", ")" ]
Return a cursor of records from the given MongoDB collection. :param collection_name: Name of the MongoDB collection to query. :param query: Standard MongoDB query. By default no restriction. :param sort_by: Name of a single field to sort by. :param sort_direction: The direction to sort, "asc" or "desc". :param start: Skip first n results. :param limit: The maximum number of results to return. :return: Cursor -- An iterable with results. :raise DataSourceError
[ "Return", "a", "cursor", "of", "records", "from", "the", "given", "MongoDB", "collection", "." ]
47e1c99e3be3c1b099d3772bc077f5666020eb0b
https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/data/pymongo/genericdao.py#L49-L70
-1
251,691
chovanecm/sacredboard
sacredboard/app/data/pymongo/genericdao.py
GenericDAO._get_database
def _get_database(self, database_name): """ Get PyMongo client pointing to the current database. :return: MongoDB client of the current database. :raise DataSourceError """ try: return self._client[database_name] except InvalidName as ex: raise DataSourceError("Cannot connect to database %s!" % self._database) from ex
python
def _get_database(self, database_name): """ Get PyMongo client pointing to the current database. :return: MongoDB client of the current database. :raise DataSourceError """ try: return self._client[database_name] except InvalidName as ex: raise DataSourceError("Cannot connect to database %s!" % self._database) from ex
[ "def", "_get_database", "(", "self", ",", "database_name", ")", ":", "try", ":", "return", "self", ".", "_client", "[", "database_name", "]", "except", "InvalidName", "as", "ex", ":", "raise", "DataSourceError", "(", "\"Cannot connect to database %s!\"", "%", "self", ".", "_database", ")", "from", "ex" ]
Get PyMongo client pointing to the current database. :return: MongoDB client of the current database. :raise DataSourceError
[ "Get", "PyMongo", "client", "pointing", "to", "the", "current", "database", "." ]
47e1c99e3be3c1b099d3772bc077f5666020eb0b
https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/data/pymongo/genericdao.py#L76-L87
-1
251,692
chovanecm/sacredboard
sacredboard/app/data/pymongo/genericdao.py
GenericDAO._get_collection
def _get_collection(self, collection_name): """ Get PyMongo client pointing to the current DB and the given collection. :return: MongoDB client of the current database and given collection. :raise DataSourceError """ try: return self._database[collection_name] except InvalidName as ex: raise DataSourceError("Cannot access MongoDB collection %s!" % collection_name) from ex except Exception as ex: raise DataSourceError("Unexpected error when accessing MongoDB" "collection %s!" % collection_name) from ex
python
def _get_collection(self, collection_name): """ Get PyMongo client pointing to the current DB and the given collection. :return: MongoDB client of the current database and given collection. :raise DataSourceError """ try: return self._database[collection_name] except InvalidName as ex: raise DataSourceError("Cannot access MongoDB collection %s!" % collection_name) from ex except Exception as ex: raise DataSourceError("Unexpected error when accessing MongoDB" "collection %s!" % collection_name) from ex
[ "def", "_get_collection", "(", "self", ",", "collection_name", ")", ":", "try", ":", "return", "self", ".", "_database", "[", "collection_name", "]", "except", "InvalidName", "as", "ex", ":", "raise", "DataSourceError", "(", "\"Cannot access MongoDB collection %s!\"", "%", "collection_name", ")", "from", "ex", "except", "Exception", "as", "ex", ":", "raise", "DataSourceError", "(", "\"Unexpected error when accessing MongoDB\"", "\"collection %s!\"", "%", "collection_name", ")", "from", "ex" ]
Get PyMongo client pointing to the current DB and the given collection. :return: MongoDB client of the current database and given collection. :raise DataSourceError
[ "Get", "PyMongo", "client", "pointing", "to", "the", "current", "DB", "and", "the", "given", "collection", "." ]
47e1c99e3be3c1b099d3772bc077f5666020eb0b
https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/data/pymongo/genericdao.py#L89-L104
-1
251,693
chovanecm/sacredboard
sacredboard/app/data/pymongo/rundao.py
MongoRunDAO.get
def get(self, run_id): """ Get a single run from the database. :param run_id: The ID of the run. :return: The whole object from the database. :raise NotFoundError when not found """ id = self._parse_id(run_id) run = self.generic_dao.find_record(self.collection_name, {"_id": id}) if run is None: raise NotFoundError("Run %s not found." % run_id) return run
python
def get(self, run_id): """ Get a single run from the database. :param run_id: The ID of the run. :return: The whole object from the database. :raise NotFoundError when not found """ id = self._parse_id(run_id) run = self.generic_dao.find_record(self.collection_name, {"_id": id}) if run is None: raise NotFoundError("Run %s not found." % run_id) return run
[ "def", "get", "(", "self", ",", "run_id", ")", ":", "id", "=", "self", ".", "_parse_id", "(", "run_id", ")", "run", "=", "self", ".", "generic_dao", ".", "find_record", "(", "self", ".", "collection_name", ",", "{", "\"_id\"", ":", "id", "}", ")", "if", "run", "is", "None", ":", "raise", "NotFoundError", "(", "\"Run %s not found.\"", "%", "run_id", ")", "return", "run" ]
Get a single run from the database. :param run_id: The ID of the run. :return: The whole object from the database. :raise NotFoundError when not found
[ "Get", "a", "single", "run", "from", "the", "database", "." ]
47e1c99e3be3c1b099d3772bc077f5666020eb0b
https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/data/pymongo/rundao.py#L72-L86
-1
251,694
chovanecm/sacredboard
sacredboard/app/data/pymongo/rundao.py
MongoRunDAO._apply_sort
def _apply_sort(cursor, sort_by, sort_direction): """ Apply sort to a cursor. :param cursor: The cursor to apply sort on. :param sort_by: The field name to sort by. :param sort_direction: The direction to sort, "asc" or "desc". :return: """ if sort_direction is not None and sort_direction.lower() == "desc": sort = pymongo.DESCENDING else: sort = pymongo.ASCENDING return cursor.sort(sort_by, sort)
python
def _apply_sort(cursor, sort_by, sort_direction): """ Apply sort to a cursor. :param cursor: The cursor to apply sort on. :param sort_by: The field name to sort by. :param sort_direction: The direction to sort, "asc" or "desc". :return: """ if sort_direction is not None and sort_direction.lower() == "desc": sort = pymongo.DESCENDING else: sort = pymongo.ASCENDING return cursor.sort(sort_by, sort)
[ "def", "_apply_sort", "(", "cursor", ",", "sort_by", ",", "sort_direction", ")", ":", "if", "sort_direction", "is", "not", "None", "and", "sort_direction", ".", "lower", "(", ")", "==", "\"desc\"", ":", "sort", "=", "pymongo", ".", "DESCENDING", "else", ":", "sort", "=", "pymongo", ".", "ASCENDING", "return", "cursor", ".", "sort", "(", "sort_by", ",", "sort", ")" ]
Apply sort to a cursor. :param cursor: The cursor to apply sort on. :param sort_by: The field name to sort by. :param sort_direction: The direction to sort, "asc" or "desc". :return:
[ "Apply", "sort", "to", "a", "cursor", "." ]
47e1c99e3be3c1b099d3772bc077f5666020eb0b
https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/data/pymongo/rundao.py#L97-L111
-1
251,695
chovanecm/sacredboard
sacredboard/app/data/pymongo/rundao.py
MongoRunDAO._to_mongo_query
def _to_mongo_query(query): """ Convert the query received by the Sacred Web API to a MongoDB query. Takes a query in format {"type": "and", "filters": [ {"field": "host.hostname", "operator": "==", "value": "ntbacer"}, {"type": "or", "filters": [ {"field": "result", "operator": "==", "value": 2403.52}, {"field": "host.python_version", "operator": "==", "value":"3.5.2"} ]}]} and returns an appropriate MongoDB Query. :param query: A query in the Sacred Web API format. :return: Mongo Query. """ mongo_query = [] for clause in query["filters"]: if clause.get("type") is None: mongo_clause = MongoRunDAO. \ _simple_clause_to_query(clause) else: # It's a subclause mongo_clause = MongoRunDAO._to_mongo_query(clause) mongo_query.append(mongo_clause) if len(mongo_query) == 0: return {} if query["type"] == "and": return {"$and": mongo_query} elif query["type"] == "or": return {"$or": mongo_query} else: raise ValueError("Unexpected query type %s" % query.get("type"))
python
def _to_mongo_query(query): """ Convert the query received by the Sacred Web API to a MongoDB query. Takes a query in format {"type": "and", "filters": [ {"field": "host.hostname", "operator": "==", "value": "ntbacer"}, {"type": "or", "filters": [ {"field": "result", "operator": "==", "value": 2403.52}, {"field": "host.python_version", "operator": "==", "value":"3.5.2"} ]}]} and returns an appropriate MongoDB Query. :param query: A query in the Sacred Web API format. :return: Mongo Query. """ mongo_query = [] for clause in query["filters"]: if clause.get("type") is None: mongo_clause = MongoRunDAO. \ _simple_clause_to_query(clause) else: # It's a subclause mongo_clause = MongoRunDAO._to_mongo_query(clause) mongo_query.append(mongo_clause) if len(mongo_query) == 0: return {} if query["type"] == "and": return {"$and": mongo_query} elif query["type"] == "or": return {"$or": mongo_query} else: raise ValueError("Unexpected query type %s" % query.get("type"))
[ "def", "_to_mongo_query", "(", "query", ")", ":", "mongo_query", "=", "[", "]", "for", "clause", "in", "query", "[", "\"filters\"", "]", ":", "if", "clause", ".", "get", "(", "\"type\"", ")", "is", "None", ":", "mongo_clause", "=", "MongoRunDAO", ".", "_simple_clause_to_query", "(", "clause", ")", "else", ":", "# It's a subclause", "mongo_clause", "=", "MongoRunDAO", ".", "_to_mongo_query", "(", "clause", ")", "mongo_query", ".", "append", "(", "mongo_clause", ")", "if", "len", "(", "mongo_query", ")", "==", "0", ":", "return", "{", "}", "if", "query", "[", "\"type\"", "]", "==", "\"and\"", ":", "return", "{", "\"$and\"", ":", "mongo_query", "}", "elif", "query", "[", "\"type\"", "]", "==", "\"or\"", ":", "return", "{", "\"$or\"", ":", "mongo_query", "}", "else", ":", "raise", "ValueError", "(", "\"Unexpected query type %s\"", "%", "query", ".", "get", "(", "\"type\"", ")", ")" ]
Convert the query received by the Sacred Web API to a MongoDB query. Takes a query in format {"type": "and", "filters": [ {"field": "host.hostname", "operator": "==", "value": "ntbacer"}, {"type": "or", "filters": [ {"field": "result", "operator": "==", "value": 2403.52}, {"field": "host.python_version", "operator": "==", "value":"3.5.2"} ]}]} and returns an appropriate MongoDB Query. :param query: A query in the Sacred Web API format. :return: Mongo Query.
[ "Convert", "the", "query", "received", "by", "the", "Sacred", "Web", "API", "to", "a", "MongoDB", "query", "." ]
47e1c99e3be3c1b099d3772bc077f5666020eb0b
https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/data/pymongo/rundao.py#L114-L146
-1
251,696
chovanecm/sacredboard
sacredboard/app/data/pymongo/rundao.py
MongoRunDAO._simple_clause_to_query
def _simple_clause_to_query(clause): """ Convert a clause from the Sacred Web API format to the MongoDB format. :param clause: A clause to be converted. It must have "field", "operator" and "value" fields. :return: A MongoDB clause. """ # It's a regular clause mongo_clause = {} value = clause["value"] if clause["field"] == "status" and clause["value"] in ["DEAD", "RUNNING"]: return MongoRunDAO. \ _status_filter_to_query(clause) if clause["operator"] == "==": mongo_clause[clause["field"]] = value elif clause["operator"] == ">": mongo_clause[clause["field"]] = {"$gt": value} elif clause["operator"] == ">=": mongo_clause[clause["field"]] = {"$gte": value} elif clause["operator"] == "<": mongo_clause[clause["field"]] = {"$lt": value} elif clause["operator"] == "<=": mongo_clause[clause["field"]] = {"$lte": value} elif clause["operator"] == "!=": mongo_clause[clause["field"]] = {"$ne": value} elif clause["operator"] == "regex": mongo_clause[clause["field"]] = {"$regex": value} return mongo_clause
python
def _simple_clause_to_query(clause): """ Convert a clause from the Sacred Web API format to the MongoDB format. :param clause: A clause to be converted. It must have "field", "operator" and "value" fields. :return: A MongoDB clause. """ # It's a regular clause mongo_clause = {} value = clause["value"] if clause["field"] == "status" and clause["value"] in ["DEAD", "RUNNING"]: return MongoRunDAO. \ _status_filter_to_query(clause) if clause["operator"] == "==": mongo_clause[clause["field"]] = value elif clause["operator"] == ">": mongo_clause[clause["field"]] = {"$gt": value} elif clause["operator"] == ">=": mongo_clause[clause["field"]] = {"$gte": value} elif clause["operator"] == "<": mongo_clause[clause["field"]] = {"$lt": value} elif clause["operator"] == "<=": mongo_clause[clause["field"]] = {"$lte": value} elif clause["operator"] == "!=": mongo_clause[clause["field"]] = {"$ne": value} elif clause["operator"] == "regex": mongo_clause[clause["field"]] = {"$regex": value} return mongo_clause
[ "def", "_simple_clause_to_query", "(", "clause", ")", ":", "# It's a regular clause", "mongo_clause", "=", "{", "}", "value", "=", "clause", "[", "\"value\"", "]", "if", "clause", "[", "\"field\"", "]", "==", "\"status\"", "and", "clause", "[", "\"value\"", "]", "in", "[", "\"DEAD\"", ",", "\"RUNNING\"", "]", ":", "return", "MongoRunDAO", ".", "_status_filter_to_query", "(", "clause", ")", "if", "clause", "[", "\"operator\"", "]", "==", "\"==\"", ":", "mongo_clause", "[", "clause", "[", "\"field\"", "]", "]", "=", "value", "elif", "clause", "[", "\"operator\"", "]", "==", "\">\"", ":", "mongo_clause", "[", "clause", "[", "\"field\"", "]", "]", "=", "{", "\"$gt\"", ":", "value", "}", "elif", "clause", "[", "\"operator\"", "]", "==", "\">=\"", ":", "mongo_clause", "[", "clause", "[", "\"field\"", "]", "]", "=", "{", "\"$gte\"", ":", "value", "}", "elif", "clause", "[", "\"operator\"", "]", "==", "\"<\"", ":", "mongo_clause", "[", "clause", "[", "\"field\"", "]", "]", "=", "{", "\"$lt\"", ":", "value", "}", "elif", "clause", "[", "\"operator\"", "]", "==", "\"<=\"", ":", "mongo_clause", "[", "clause", "[", "\"field\"", "]", "]", "=", "{", "\"$lte\"", ":", "value", "}", "elif", "clause", "[", "\"operator\"", "]", "==", "\"!=\"", ":", "mongo_clause", "[", "clause", "[", "\"field\"", "]", "]", "=", "{", "\"$ne\"", ":", "value", "}", "elif", "clause", "[", "\"operator\"", "]", "==", "\"regex\"", ":", "mongo_clause", "[", "clause", "[", "\"field\"", "]", "]", "=", "{", "\"$regex\"", ":", "value", "}", "return", "mongo_clause" ]
Convert a clause from the Sacred Web API format to the MongoDB format. :param clause: A clause to be converted. It must have "field", "operator" and "value" fields. :return: A MongoDB clause.
[ "Convert", "a", "clause", "from", "the", "Sacred", "Web", "API", "format", "to", "the", "MongoDB", "format", "." ]
47e1c99e3be3c1b099d3772bc077f5666020eb0b
https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/data/pymongo/rundao.py#L149-L178
-1
251,697
chovanecm/sacredboard
sacredboard/app/data/pymongo/rundao.py
MongoRunDAO._status_filter_to_query
def _status_filter_to_query(clause): """ Convert a clause querying for an experiment state RUNNING or DEAD. Queries that check for experiment state RUNNING and DEAD need to be replaced by the logic that decides these two states as both of them are stored in the Mongo Database as "RUNNING". We use querying by last heartbeat time. :param clause: A clause whose field is "status" and "value" is one of RUNNING, DEAD. :return: A MongoDB clause. """ if clause["value"] == "RUNNING": mongo_clause = MongoRunDAO.RUNNING_NOT_DEAD_CLAUSE elif clause["value"] == "DEAD": mongo_clause = MongoRunDAO.RUNNING_DEAD_RUN_CLAUSE if clause["operator"] == "!=": mongo_clause = {"$not": mongo_clause} return mongo_clause
python
def _status_filter_to_query(clause): """ Convert a clause querying for an experiment state RUNNING or DEAD. Queries that check for experiment state RUNNING and DEAD need to be replaced by the logic that decides these two states as both of them are stored in the Mongo Database as "RUNNING". We use querying by last heartbeat time. :param clause: A clause whose field is "status" and "value" is one of RUNNING, DEAD. :return: A MongoDB clause. """ if clause["value"] == "RUNNING": mongo_clause = MongoRunDAO.RUNNING_NOT_DEAD_CLAUSE elif clause["value"] == "DEAD": mongo_clause = MongoRunDAO.RUNNING_DEAD_RUN_CLAUSE if clause["operator"] == "!=": mongo_clause = {"$not": mongo_clause} return mongo_clause
[ "def", "_status_filter_to_query", "(", "clause", ")", ":", "if", "clause", "[", "\"value\"", "]", "==", "\"RUNNING\"", ":", "mongo_clause", "=", "MongoRunDAO", ".", "RUNNING_NOT_DEAD_CLAUSE", "elif", "clause", "[", "\"value\"", "]", "==", "\"DEAD\"", ":", "mongo_clause", "=", "MongoRunDAO", ".", "RUNNING_DEAD_RUN_CLAUSE", "if", "clause", "[", "\"operator\"", "]", "==", "\"!=\"", ":", "mongo_clause", "=", "{", "\"$not\"", ":", "mongo_clause", "}", "return", "mongo_clause" ]
Convert a clause querying for an experiment state RUNNING or DEAD. Queries that check for experiment state RUNNING and DEAD need to be replaced by the logic that decides these two states as both of them are stored in the Mongo Database as "RUNNING". We use querying by last heartbeat time. :param clause: A clause whose field is "status" and "value" is one of RUNNING, DEAD. :return: A MongoDB clause.
[ "Convert", "a", "clause", "querying", "for", "an", "experiment", "state", "RUNNING", "or", "DEAD", "." ]
47e1c99e3be3c1b099d3772bc077f5666020eb0b
https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/data/pymongo/rundao.py#L181-L200
-1
251,698
chovanecm/sacredboard
sacredboard/app/data/pymongo/rundao.py
MongoRunDAO.delete
def delete(self, run_id): """ Delete run with the given id from the backend. :param run_id: Id of the run to delete. :raise NotImplementedError If not supported by the backend. :raise DataSourceError General data source error. :raise NotFoundError The run was not found. (Some backends may succeed even if the run does not exist. """ return self.generic_dao.delete_record(self.collection_name, self._parse_id(run_id))
python
def delete(self, run_id): """ Delete run with the given id from the backend. :param run_id: Id of the run to delete. :raise NotImplementedError If not supported by the backend. :raise DataSourceError General data source error. :raise NotFoundError The run was not found. (Some backends may succeed even if the run does not exist. """ return self.generic_dao.delete_record(self.collection_name, self._parse_id(run_id))
[ "def", "delete", "(", "self", ",", "run_id", ")", ":", "return", "self", ".", "generic_dao", ".", "delete_record", "(", "self", ".", "collection_name", ",", "self", ".", "_parse_id", "(", "run_id", ")", ")" ]
Delete run with the given id from the backend. :param run_id: Id of the run to delete. :raise NotImplementedError If not supported by the backend. :raise DataSourceError General data source error. :raise NotFoundError The run was not found. (Some backends may succeed even if the run does not exist.
[ "Delete", "run", "with", "the", "given", "id", "from", "the", "backend", "." ]
47e1c99e3be3c1b099d3772bc077f5666020eb0b
https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/data/pymongo/rundao.py#L202-L213
-1
251,699
chovanecm/sacredboard
sacredboard/bootstrap.py
add_mongo_config
def add_mongo_config(app, simple_connection_string, mongo_uri, collection_name): """ Configure the application to use MongoDB. :param app: Flask application :param simple_connection_string: Expects host:port:database_name or database_name Mutally_exclusive with mongo_uri :param mongo_uri: Expects mongodb://... as defined in https://docs.mongodb.com/manual/reference/connection-string/ Mutually exclusive with simple_connection_string (must be None) :param collection_name: The collection containing Sacred's runs :return: """ if mongo_uri != (None, None): add_mongo_config_with_uri(app, mongo_uri[0], mongo_uri[1], collection_name) if simple_connection_string is not None: print("Ignoring the -m option. Overridden by " "a more specific option (-mu).", file=sys.stderr) else: # Use the default value 'sacred' when not specified if simple_connection_string is None: simple_connection_string = "sacred" add_mongo_config_simple(app, simple_connection_string, collection_name)
python
def add_mongo_config(app, simple_connection_string, mongo_uri, collection_name): """ Configure the application to use MongoDB. :param app: Flask application :param simple_connection_string: Expects host:port:database_name or database_name Mutally_exclusive with mongo_uri :param mongo_uri: Expects mongodb://... as defined in https://docs.mongodb.com/manual/reference/connection-string/ Mutually exclusive with simple_connection_string (must be None) :param collection_name: The collection containing Sacred's runs :return: """ if mongo_uri != (None, None): add_mongo_config_with_uri(app, mongo_uri[0], mongo_uri[1], collection_name) if simple_connection_string is not None: print("Ignoring the -m option. Overridden by " "a more specific option (-mu).", file=sys.stderr) else: # Use the default value 'sacred' when not specified if simple_connection_string is None: simple_connection_string = "sacred" add_mongo_config_simple(app, simple_connection_string, collection_name)
[ "def", "add_mongo_config", "(", "app", ",", "simple_connection_string", ",", "mongo_uri", ",", "collection_name", ")", ":", "if", "mongo_uri", "!=", "(", "None", ",", "None", ")", ":", "add_mongo_config_with_uri", "(", "app", ",", "mongo_uri", "[", "0", "]", ",", "mongo_uri", "[", "1", "]", ",", "collection_name", ")", "if", "simple_connection_string", "is", "not", "None", ":", "print", "(", "\"Ignoring the -m option. Overridden by \"", "\"a more specific option (-mu).\"", ",", "file", "=", "sys", ".", "stderr", ")", "else", ":", "# Use the default value 'sacred' when not specified", "if", "simple_connection_string", "is", "None", ":", "simple_connection_string", "=", "\"sacred\"", "add_mongo_config_simple", "(", "app", ",", "simple_connection_string", ",", "collection_name", ")" ]
Configure the application to use MongoDB. :param app: Flask application :param simple_connection_string: Expects host:port:database_name or database_name Mutally_exclusive with mongo_uri :param mongo_uri: Expects mongodb://... as defined in https://docs.mongodb.com/manual/reference/connection-string/ Mutually exclusive with simple_connection_string (must be None) :param collection_name: The collection containing Sacred's runs :return:
[ "Configure", "the", "application", "to", "use", "MongoDB", "." ]
47e1c99e3be3c1b099d3772bc077f5666020eb0b
https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/bootstrap.py#L133-L158
-1