repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
39
1.84M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
adafruit/Adafruit_CircuitPython_framebuf
adafruit_framebuf.py
MVLSBFormat.get_pixel
def get_pixel(framebuf, x, y): """Get the color of a given pixel""" index = (y >> 3) * framebuf.stride + x offset = y & 0x07 return (framebuf.buf[index] >> offset) & 0x01
python
def get_pixel(framebuf, x, y): index = (y >> 3) * framebuf.stride + x offset = y & 0x07 return (framebuf.buf[index] >> offset) & 0x01
[ "def", "get_pixel", "(", "framebuf", ",", "x", ",", "y", ")", ":", "index", "=", "(", "y", ">>", "3", ")", "*", "framebuf", ".", "stride", "+", "x", "offset", "=", "y", "&", "0x07", "return", "(", "framebuf", ".", "buf", "[", "index", "]", ">>", "offset", ")", "&", "0x01" ]
Get the color of a given pixel
[ "Get", "the", "color", "of", "a", "given", "pixel" ]
train
https://github.com/adafruit/Adafruit_CircuitPython_framebuf/blob/b9f62c4b71efa963150f9c5a0284b61c7add9d02/adafruit_framebuf.py#L103-L107
adafruit/Adafruit_CircuitPython_framebuf
adafruit_framebuf.py
MVLSBFormat.fill_rect
def fill_rect(framebuf, x, y, width, height, color): """Draw a rectangle at the given location, size and color. The ``fill_rect`` method draws both the outline and interior.""" # pylint: disable=too-many-arguments while height > 0: index = (y >> 3) * framebuf.stride + x offset = y & 0x07 for w_w in range(width): framebuf.buf[index + w_w] = (framebuf.buf[index + w_w] & ~(0x01 << offset)) |\ ((color != 0) << offset) y += 1 height -= 1
python
def fill_rect(framebuf, x, y, width, height, color): while height > 0: index = (y >> 3) * framebuf.stride + x offset = y & 0x07 for w_w in range(width): framebuf.buf[index + w_w] = (framebuf.buf[index + w_w] & ~(0x01 << offset)) |\ ((color != 0) << offset) y += 1 height -= 1
[ "def", "fill_rect", "(", "framebuf", ",", "x", ",", "y", ",", "width", ",", "height", ",", "color", ")", ":", "# pylint: disable=too-many-arguments", "while", "height", ">", "0", ":", "index", "=", "(", "y", ">>", "3", ")", "*", "framebuf", ".", "stride", "+", "x", "offset", "=", "y", "&", "0x07", "for", "w_w", "in", "range", "(", "width", ")", ":", "framebuf", ".", "buf", "[", "index", "+", "w_w", "]", "=", "(", "framebuf", ".", "buf", "[", "index", "+", "w_w", "]", "&", "~", "(", "0x01", "<<", "offset", ")", ")", "|", "(", "(", "color", "!=", "0", ")", "<<", "offset", ")", "y", "+=", "1", "height", "-=", "1" ]
Draw a rectangle at the given location, size and color. The ``fill_rect`` method draws both the outline and interior.
[ "Draw", "a", "rectangle", "at", "the", "given", "location", "size", "and", "color", ".", "The", "fill_rect", "method", "draws", "both", "the", "outline", "and", "interior", "." ]
train
https://github.com/adafruit/Adafruit_CircuitPython_framebuf/blob/b9f62c4b71efa963150f9c5a0284b61c7add9d02/adafruit_framebuf.py#L120-L131
adafruit/Adafruit_CircuitPython_framebuf
adafruit_framebuf.py
FrameBuffer.fill_rect
def fill_rect(self, x, y, width, height, color): """Draw a rectangle at the given location, size and color. The ``fill_rect`` method draws both the outline and interior.""" # pylint: disable=too-many-arguments, too-many-boolean-expressions self.rect(x, y, width, height, color, fill=True)
python
def fill_rect(self, x, y, width, height, color): self.rect(x, y, width, height, color, fill=True)
[ "def", "fill_rect", "(", "self", ",", "x", ",", "y", ",", "width", ",", "height", ",", "color", ")", ":", "# pylint: disable=too-many-arguments, too-many-boolean-expressions", "self", ".", "rect", "(", "x", ",", "y", ",", "width", ",", "height", ",", "color", ",", "fill", "=", "True", ")" ]
Draw a rectangle at the given location, size and color. The ``fill_rect`` method draws both the outline and interior.
[ "Draw", "a", "rectangle", "at", "the", "given", "location", "size", "and", "color", ".", "The", "fill_rect", "method", "draws", "both", "the", "outline", "and", "interior", "." ]
train
https://github.com/adafruit/Adafruit_CircuitPython_framebuf/blob/b9f62c4b71efa963150f9c5a0284b61c7add9d02/adafruit_framebuf.py#L183-L187
adafruit/Adafruit_CircuitPython_framebuf
adafruit_framebuf.py
FrameBuffer.pixel
def pixel(self, x, y, color=None): """If ``color`` is not given, get the color value of the specified pixel. If ``color`` is given, set the specified pixel to the given color.""" if self.rotation == 1: x, y = y, x x = self.width - x - 1 if self.rotation == 2: x = self.width - x - 1 y = self.height - y - 1 if self.rotation == 3: x, y = y, x y = self.height - y - 1 if x < 0 or x >= self.width or y < 0 or y >= self.height: return None if color is None: return self.format.get_pixel(self, x, y) self.format.set_pixel(self, x, y, color) return None
python
def pixel(self, x, y, color=None): if self.rotation == 1: x, y = y, x x = self.width - x - 1 if self.rotation == 2: x = self.width - x - 1 y = self.height - y - 1 if self.rotation == 3: x, y = y, x y = self.height - y - 1 if x < 0 or x >= self.width or y < 0 or y >= self.height: return None if color is None: return self.format.get_pixel(self, x, y) self.format.set_pixel(self, x, y, color) return None
[ "def", "pixel", "(", "self", ",", "x", ",", "y", ",", "color", "=", "None", ")", ":", "if", "self", ".", "rotation", "==", "1", ":", "x", ",", "y", "=", "y", ",", "x", "x", "=", "self", ".", "width", "-", "x", "-", "1", "if", "self", ".", "rotation", "==", "2", ":", "x", "=", "self", ".", "width", "-", "x", "-", "1", "y", "=", "self", ".", "height", "-", "y", "-", "1", "if", "self", ".", "rotation", "==", "3", ":", "x", ",", "y", "=", "y", ",", "x", "y", "=", "self", ".", "height", "-", "y", "-", "1", "if", "x", "<", "0", "or", "x", ">=", "self", ".", "width", "or", "y", "<", "0", "or", "y", ">=", "self", ".", "height", ":", "return", "None", "if", "color", "is", "None", ":", "return", "self", ".", "format", ".", "get_pixel", "(", "self", ",", "x", ",", "y", ")", "self", ".", "format", ".", "set_pixel", "(", "self", ",", "x", ",", "y", ",", "color", ")", "return", "None" ]
If ``color`` is not given, get the color value of the specified pixel. If ``color`` is given, set the specified pixel to the given color.
[ "If", "color", "is", "not", "given", "get", "the", "color", "value", "of", "the", "specified", "pixel", ".", "If", "color", "is", "given", "set", "the", "specified", "pixel", "to", "the", "given", "color", "." ]
train
https://github.com/adafruit/Adafruit_CircuitPython_framebuf/blob/b9f62c4b71efa963150f9c5a0284b61c7add9d02/adafruit_framebuf.py#L189-L207
adafruit/Adafruit_CircuitPython_framebuf
adafruit_framebuf.py
FrameBuffer.hline
def hline(self, x, y, width, color): """Draw a horizontal line up to a given length.""" self.rect(x, y, width, 1, color, fill=True)
python
def hline(self, x, y, width, color): self.rect(x, y, width, 1, color, fill=True)
[ "def", "hline", "(", "self", ",", "x", ",", "y", ",", "width", ",", "color", ")", ":", "self", ".", "rect", "(", "x", ",", "y", ",", "width", ",", "1", ",", "color", ",", "fill", "=", "True", ")" ]
Draw a horizontal line up to a given length.
[ "Draw", "a", "horizontal", "line", "up", "to", "a", "given", "length", "." ]
train
https://github.com/adafruit/Adafruit_CircuitPython_framebuf/blob/b9f62c4b71efa963150f9c5a0284b61c7add9d02/adafruit_framebuf.py#L209-L211
adafruit/Adafruit_CircuitPython_framebuf
adafruit_framebuf.py
FrameBuffer.vline
def vline(self, x, y, height, color): """Draw a vertical line up to a given length.""" self.rect(x, y, 1, height, color, fill=True)
python
def vline(self, x, y, height, color): self.rect(x, y, 1, height, color, fill=True)
[ "def", "vline", "(", "self", ",", "x", ",", "y", ",", "height", ",", "color", ")", ":", "self", ".", "rect", "(", "x", ",", "y", ",", "1", ",", "height", ",", "color", ",", "fill", "=", "True", ")" ]
Draw a vertical line up to a given length.
[ "Draw", "a", "vertical", "line", "up", "to", "a", "given", "length", "." ]
train
https://github.com/adafruit/Adafruit_CircuitPython_framebuf/blob/b9f62c4b71efa963150f9c5a0284b61c7add9d02/adafruit_framebuf.py#L213-L215
adafruit/Adafruit_CircuitPython_framebuf
adafruit_framebuf.py
FrameBuffer.rect
def rect(self, x, y, width, height, color, *, fill=False): """Draw a rectangle at the given location, size and color. The ```rect``` method draws only a 1 pixel outline.""" # pylint: disable=too-many-arguments if self.rotation == 1: x, y = y, x width, height = height, width x = self.width - x - width if self.rotation == 2: x = self.width - x - width y = self.height - y - height if self.rotation == 3: x, y = y, x width, height = height, width y = self.height - y - height # pylint: disable=too-many-boolean-expressions if width < 1 or height < 1 or (x + width) <= 0 or (y + height) <= 0 or \ y >= self.height or x >= self.width: return x_end = min(self.width-1, x + width-1) y_end = min(self.height-1, y + height-1) x = max(x, 0) y = max(y, 0) if fill: self.format.fill_rect(self, x, y, x_end-x+1, y_end-y+1, color) else: self.format.fill_rect(self, x, y, x_end-x+1, 1, color) self.format.fill_rect(self, x, y, 1, y_end-y+1, color) self.format.fill_rect(self, x, y_end, x_end-x+1, 1, color) self.format.fill_rect(self, x_end, y, 1, y_end-y+1, color)
python
def rect(self, x, y, width, height, color, *, fill=False): if self.rotation == 1: x, y = y, x width, height = height, width x = self.width - x - width if self.rotation == 2: x = self.width - x - width y = self.height - y - height if self.rotation == 3: x, y = y, x width, height = height, width y = self.height - y - height if width < 1 or height < 1 or (x + width) <= 0 or (y + height) <= 0 or \ y >= self.height or x >= self.width: return x_end = min(self.width-1, x + width-1) y_end = min(self.height-1, y + height-1) x = max(x, 0) y = max(y, 0) if fill: self.format.fill_rect(self, x, y, x_end-x+1, y_end-y+1, color) else: self.format.fill_rect(self, x, y, x_end-x+1, 1, color) self.format.fill_rect(self, x, y, 1, y_end-y+1, color) self.format.fill_rect(self, x, y_end, x_end-x+1, 1, color) self.format.fill_rect(self, x_end, y, 1, y_end-y+1, color)
[ "def", "rect", "(", "self", ",", "x", ",", "y", ",", "width", ",", "height", ",", "color", ",", "*", ",", "fill", "=", "False", ")", ":", "# pylint: disable=too-many-arguments", "if", "self", ".", "rotation", "==", "1", ":", "x", ",", "y", "=", "y", ",", "x", "width", ",", "height", "=", "height", ",", "width", "x", "=", "self", ".", "width", "-", "x", "-", "width", "if", "self", ".", "rotation", "==", "2", ":", "x", "=", "self", ".", "width", "-", "x", "-", "width", "y", "=", "self", ".", "height", "-", "y", "-", "height", "if", "self", ".", "rotation", "==", "3", ":", "x", ",", "y", "=", "y", ",", "x", "width", ",", "height", "=", "height", ",", "width", "y", "=", "self", ".", "height", "-", "y", "-", "height", "# pylint: disable=too-many-boolean-expressions", "if", "width", "<", "1", "or", "height", "<", "1", "or", "(", "x", "+", "width", ")", "<=", "0", "or", "(", "y", "+", "height", ")", "<=", "0", "or", "y", ">=", "self", ".", "height", "or", "x", ">=", "self", ".", "width", ":", "return", "x_end", "=", "min", "(", "self", ".", "width", "-", "1", ",", "x", "+", "width", "-", "1", ")", "y_end", "=", "min", "(", "self", ".", "height", "-", "1", ",", "y", "+", "height", "-", "1", ")", "x", "=", "max", "(", "x", ",", "0", ")", "y", "=", "max", "(", "y", ",", "0", ")", "if", "fill", ":", "self", ".", "format", ".", "fill_rect", "(", "self", ",", "x", ",", "y", ",", "x_end", "-", "x", "+", "1", ",", "y_end", "-", "y", "+", "1", ",", "color", ")", "else", ":", "self", ".", "format", ".", "fill_rect", "(", "self", ",", "x", ",", "y", ",", "x_end", "-", "x", "+", "1", ",", "1", ",", "color", ")", "self", ".", "format", ".", "fill_rect", "(", "self", ",", "x", ",", "y", ",", "1", ",", "y_end", "-", "y", "+", "1", ",", "color", ")", "self", ".", "format", ".", "fill_rect", "(", "self", ",", "x", ",", "y_end", ",", "x_end", "-", "x", "+", "1", ",", "1", ",", "color", ")", "self", ".", "format", ".", "fill_rect", "(", "self", ",", "x_end", ",", "y", ",", "1", ",", "y_end", "-", "y", "+", "1", ",", "color", ")" ]
Draw a rectangle at the given location, size and color. The ```rect``` method draws only a 1 pixel outline.
[ "Draw", "a", "rectangle", "at", "the", "given", "location", "size", "and", "color", ".", "The", "rect", "method", "draws", "only", "a", "1", "pixel", "outline", "." ]
train
https://github.com/adafruit/Adafruit_CircuitPython_framebuf/blob/b9f62c4b71efa963150f9c5a0284b61c7add9d02/adafruit_framebuf.py#L217-L247
adafruit/Adafruit_CircuitPython_framebuf
adafruit_framebuf.py
FrameBuffer.line
def line(self, x_0, y_0, x_1, y_1, color): # pylint: disable=too-many-arguments """Bresenham's line algorithm""" d_x = abs(x_1 - x_0) d_y = abs(y_1 - y_0) x, y = x_0, y_0 s_x = -1 if x_0 > x_1 else 1 s_y = -1 if y_0 > y_1 else 1 if d_x > d_y: err = d_x / 2.0 while x != x_1: self.pixel(x, y, color) err -= d_y if err < 0: y += s_y err += d_x x += s_x else: err = d_y / 2.0 while y != y_1: self.pixel(x, y, color) err -= d_x if err < 0: x += s_x err += d_y y += s_y self.pixel(x, y, color)
python
def line(self, x_0, y_0, x_1, y_1, color): d_x = abs(x_1 - x_0) d_y = abs(y_1 - y_0) x, y = x_0, y_0 s_x = -1 if x_0 > x_1 else 1 s_y = -1 if y_0 > y_1 else 1 if d_x > d_y: err = d_x / 2.0 while x != x_1: self.pixel(x, y, color) err -= d_y if err < 0: y += s_y err += d_x x += s_x else: err = d_y / 2.0 while y != y_1: self.pixel(x, y, color) err -= d_x if err < 0: x += s_x err += d_y y += s_y self.pixel(x, y, color)
[ "def", "line", "(", "self", ",", "x_0", ",", "y_0", ",", "x_1", ",", "y_1", ",", "color", ")", ":", "# pylint: disable=too-many-arguments", "d_x", "=", "abs", "(", "x_1", "-", "x_0", ")", "d_y", "=", "abs", "(", "y_1", "-", "y_0", ")", "x", ",", "y", "=", "x_0", ",", "y_0", "s_x", "=", "-", "1", "if", "x_0", ">", "x_1", "else", "1", "s_y", "=", "-", "1", "if", "y_0", ">", "y_1", "else", "1", "if", "d_x", ">", "d_y", ":", "err", "=", "d_x", "/", "2.0", "while", "x", "!=", "x_1", ":", "self", ".", "pixel", "(", "x", ",", "y", ",", "color", ")", "err", "-=", "d_y", "if", "err", "<", "0", ":", "y", "+=", "s_y", "err", "+=", "d_x", "x", "+=", "s_x", "else", ":", "err", "=", "d_y", "/", "2.0", "while", "y", "!=", "y_1", ":", "self", ".", "pixel", "(", "x", ",", "y", ",", "color", ")", "err", "-=", "d_x", "if", "err", "<", "0", ":", "x", "+=", "s_x", "err", "+=", "d_y", "y", "+=", "s_y", "self", ".", "pixel", "(", "x", ",", "y", ",", "color", ")" ]
Bresenham's line algorithm
[ "Bresenham", "s", "line", "algorithm" ]
train
https://github.com/adafruit/Adafruit_CircuitPython_framebuf/blob/b9f62c4b71efa963150f9c5a0284b61c7add9d02/adafruit_framebuf.py#L249-L275
adafruit/Adafruit_CircuitPython_framebuf
adafruit_framebuf.py
FrameBuffer.scroll
def scroll(self, delta_x, delta_y): """shifts framebuf in x and y direction""" if delta_x < 0: shift_x = 0 xend = self.width + delta_x dt_x = 1 else: shift_x = self.width - 1 xend = delta_x - 1 dt_x = -1 if delta_y < 0: y = 0 yend = self.height + delta_y dt_y = 1 else: y = self.height - 1 yend = delta_y - 1 dt_y = -1 while y != yend: x = shift_x while x != xend: self.format.set_pixel( self, x, y, self.format.get_pixel(self, x - delta_x, y - delta_y)) x += dt_x y += dt_y
python
def scroll(self, delta_x, delta_y): if delta_x < 0: shift_x = 0 xend = self.width + delta_x dt_x = 1 else: shift_x = self.width - 1 xend = delta_x - 1 dt_x = -1 if delta_y < 0: y = 0 yend = self.height + delta_y dt_y = 1 else: y = self.height - 1 yend = delta_y - 1 dt_y = -1 while y != yend: x = shift_x while x != xend: self.format.set_pixel( self, x, y, self.format.get_pixel(self, x - delta_x, y - delta_y)) x += dt_x y += dt_y
[ "def", "scroll", "(", "self", ",", "delta_x", ",", "delta_y", ")", ":", "if", "delta_x", "<", "0", ":", "shift_x", "=", "0", "xend", "=", "self", ".", "width", "+", "delta_x", "dt_x", "=", "1", "else", ":", "shift_x", "=", "self", ".", "width", "-", "1", "xend", "=", "delta_x", "-", "1", "dt_x", "=", "-", "1", "if", "delta_y", "<", "0", ":", "y", "=", "0", "yend", "=", "self", ".", "height", "+", "delta_y", "dt_y", "=", "1", "else", ":", "y", "=", "self", ".", "height", "-", "1", "yend", "=", "delta_y", "-", "1", "dt_y", "=", "-", "1", "while", "y", "!=", "yend", ":", "x", "=", "shift_x", "while", "x", "!=", "xend", ":", "self", ".", "format", ".", "set_pixel", "(", "self", ",", "x", ",", "y", ",", "self", ".", "format", ".", "get_pixel", "(", "self", ",", "x", "-", "delta_x", ",", "y", "-", "delta_y", ")", ")", "x", "+=", "dt_x", "y", "+=", "dt_y" ]
shifts framebuf in x and y direction
[ "shifts", "framebuf", "in", "x", "and", "y", "direction" ]
train
https://github.com/adafruit/Adafruit_CircuitPython_framebuf/blob/b9f62c4b71efa963150f9c5a0284b61c7add9d02/adafruit_framebuf.py#L281-L305
adafruit/Adafruit_CircuitPython_framebuf
adafruit_framebuf.py
FrameBuffer.text
def text(self, string, x, y, color, *, font_name="font5x8.bin"): """text is not yet implemented""" if not self._font or self._font.font_name != font_name: # load the font! self._font = BitmapFont() w = self._font.font_width for i, char in enumerate(string): self._font.draw_char(char, x + (i * (w + 1)), y, self, color)
python
def text(self, string, x, y, color, *, font_name="font5x8.bin"): if not self._font or self._font.font_name != font_name: self._font = BitmapFont() w = self._font.font_width for i, char in enumerate(string): self._font.draw_char(char, x + (i * (w + 1)), y, self, color)
[ "def", "text", "(", "self", ",", "string", ",", "x", ",", "y", ",", "color", ",", "*", ",", "font_name", "=", "\"font5x8.bin\"", ")", ":", "if", "not", "self", ".", "_font", "or", "self", ".", "_font", ".", "font_name", "!=", "font_name", ":", "# load the font!", "self", ".", "_font", "=", "BitmapFont", "(", ")", "w", "=", "self", ".", "_font", ".", "font_width", "for", "i", ",", "char", "in", "enumerate", "(", "string", ")", ":", "self", ".", "_font", ".", "draw_char", "(", "char", ",", "x", "+", "(", "i", "*", "(", "w", "+", "1", ")", ")", ",", "y", ",", "self", ",", "color", ")" ]
text is not yet implemented
[ "text", "is", "not", "yet", "implemented" ]
train
https://github.com/adafruit/Adafruit_CircuitPython_framebuf/blob/b9f62c4b71efa963150f9c5a0284b61c7add9d02/adafruit_framebuf.py#L307-L317
adafruit/Adafruit_CircuitPython_framebuf
adafruit_framebuf.py
FrameBuffer.image
def image(self, img): """Set buffer to value of Python Imaging Library image. The image should be in 1 bit mode and a size equal to the display size.""" if img.mode != '1': raise ValueError('Image must be in mode 1.') imwidth, imheight = img.size if imwidth != self.width or imheight != self.height: raise ValueError('Image must be same dimensions as display ({0}x{1}).' \ .format(self.width, self.height)) # Grab all the pixels from the image, faster than getpixel. pixels = img.load() # Clear buffer for i in range(len(self.buf)): self.buf[i] = 0 # Iterate through the pixels for x in range(self.width): # yes this double loop is slow, for y in range(self.height): # but these displays are small! if pixels[(x, y)]: self.pixel(x, y, 1)
python
def image(self, img): if img.mode != '1': raise ValueError('Image must be in mode 1.') imwidth, imheight = img.size if imwidth != self.width or imheight != self.height: raise ValueError('Image must be same dimensions as display ({0}x{1}).' \ .format(self.width, self.height)) pixels = img.load() for i in range(len(self.buf)): self.buf[i] = 0 for x in range(self.width): for y in range(self.height): if pixels[(x, y)]: self.pixel(x, y, 1)
[ "def", "image", "(", "self", ",", "img", ")", ":", "if", "img", ".", "mode", "!=", "'1'", ":", "raise", "ValueError", "(", "'Image must be in mode 1.'", ")", "imwidth", ",", "imheight", "=", "img", ".", "size", "if", "imwidth", "!=", "self", ".", "width", "or", "imheight", "!=", "self", ".", "height", ":", "raise", "ValueError", "(", "'Image must be same dimensions as display ({0}x{1}).'", ".", "format", "(", "self", ".", "width", ",", "self", ".", "height", ")", ")", "# Grab all the pixels from the image, faster than getpixel.", "pixels", "=", "img", ".", "load", "(", ")", "# Clear buffer", "for", "i", "in", "range", "(", "len", "(", "self", ".", "buf", ")", ")", ":", "self", ".", "buf", "[", "i", "]", "=", "0", "# Iterate through the pixels", "for", "x", "in", "range", "(", "self", ".", "width", ")", ":", "# yes this double loop is slow,", "for", "y", "in", "range", "(", "self", ".", "height", ")", ":", "# but these displays are small!", "if", "pixels", "[", "(", "x", ",", "y", ")", "]", ":", "self", ".", "pixel", "(", "x", ",", "y", ",", "1", ")" ]
Set buffer to value of Python Imaging Library image. The image should be in 1 bit mode and a size equal to the display size.
[ "Set", "buffer", "to", "value", "of", "Python", "Imaging", "Library", "image", ".", "The", "image", "should", "be", "in", "1", "bit", "mode", "and", "a", "size", "equal", "to", "the", "display", "size", "." ]
train
https://github.com/adafruit/Adafruit_CircuitPython_framebuf/blob/b9f62c4b71efa963150f9c5a0284b61c7add9d02/adafruit_framebuf.py#L319-L337
adafruit/Adafruit_CircuitPython_framebuf
adafruit_framebuf.py
BitmapFont.draw_char
def draw_char(self, char, x, y, framebuffer, color): # pylint: disable=too-many-arguments """Draw one character at position (x,y) to a framebuffer in a given color""" # Don't draw the character if it will be clipped off the visible area. #if x < -self.font_width or x >= framebuffer.width or \ # y < -self.font_height or y >= framebuffer.height: # return # Go through each column of the character. for char_x in range(self.font_width): # Grab the byte for the current column of font data. self._font.seek(2 + (ord(char) * self.font_width) + char_x) try: line = struct.unpack('B', self._font.read(1))[0] except RuntimeError: continue # maybe character isnt there? go to next # Go through each row in the column byte. for char_y in range(self.font_height): # Draw a pixel for each bit that's flipped on. if (line >> char_y) & 0x1: framebuffer.pixel(x + char_x, y + char_y, color)
python
def draw_char(self, char, x, y, framebuffer, color): for char_x in range(self.font_width): self._font.seek(2 + (ord(char) * self.font_width) + char_x) try: line = struct.unpack('B', self._font.read(1))[0] except RuntimeError: continue for char_y in range(self.font_height): if (line >> char_y) & 0x1: framebuffer.pixel(x + char_x, y + char_y, color)
[ "def", "draw_char", "(", "self", ",", "char", ",", "x", ",", "y", ",", "framebuffer", ",", "color", ")", ":", "# pylint: disable=too-many-arguments", "# Don't draw the character if it will be clipped off the visible area.", "#if x < -self.font_width or x >= framebuffer.width or \\", "# y < -self.font_height or y >= framebuffer.height:", "# return", "# Go through each column of the character.", "for", "char_x", "in", "range", "(", "self", ".", "font_width", ")", ":", "# Grab the byte for the current column of font data.", "self", ".", "_font", ".", "seek", "(", "2", "+", "(", "ord", "(", "char", ")", "*", "self", ".", "font_width", ")", "+", "char_x", ")", "try", ":", "line", "=", "struct", ".", "unpack", "(", "'B'", ",", "self", ".", "_font", ".", "read", "(", "1", ")", ")", "[", "0", "]", "except", "RuntimeError", ":", "continue", "# maybe character isnt there? go to next", "# Go through each row in the column byte.", "for", "char_y", "in", "range", "(", "self", ".", "font_height", ")", ":", "# Draw a pixel for each bit that's flipped on.", "if", "(", "line", ">>", "char_y", ")", "&", "0x1", ":", "framebuffer", ".", "pixel", "(", "x", "+", "char_x", ",", "y", "+", "char_y", ",", "color", ")" ]
Draw one character at position (x,y) to a framebuffer in a given color
[ "Draw", "one", "character", "at", "position", "(", "x", "y", ")", "to", "a", "framebuffer", "in", "a", "given", "color" ]
train
https://github.com/adafruit/Adafruit_CircuitPython_framebuf/blob/b9f62c4b71efa963150f9c5a0284b61c7add9d02/adafruit_framebuf.py#L381-L400
loanzen/falcon-auth
falcon_auth/backends.py
AuthBackend.parse_auth_token_from_request
def parse_auth_token_from_request(self, auth_header): """ Parses and returns Auth token from the request header. Raises `falcon.HTTPUnauthoried exception` with proper error message """ if not auth_header: raise falcon.HTTPUnauthorized( description='Missing Authorization Header') parts = auth_header.split() if parts[0].lower() != self.auth_header_prefix.lower(): raise falcon.HTTPUnauthorized( description='Invalid Authorization Header: ' 'Must start with {0}'.format(self.auth_header_prefix)) elif len(parts) == 1: raise falcon.HTTPUnauthorized( description='Invalid Authorization Header: Token Missing') elif len(parts) > 2: raise falcon.HTTPUnauthorized( description='Invalid Authorization Header: Contains extra content') return parts[1]
python
def parse_auth_token_from_request(self, auth_header): if not auth_header: raise falcon.HTTPUnauthorized( description='Missing Authorization Header') parts = auth_header.split() if parts[0].lower() != self.auth_header_prefix.lower(): raise falcon.HTTPUnauthorized( description='Invalid Authorization Header: ' 'Must start with {0}'.format(self.auth_header_prefix)) elif len(parts) == 1: raise falcon.HTTPUnauthorized( description='Invalid Authorization Header: Token Missing') elif len(parts) > 2: raise falcon.HTTPUnauthorized( description='Invalid Authorization Header: Contains extra content') return parts[1]
[ "def", "parse_auth_token_from_request", "(", "self", ",", "auth_header", ")", ":", "if", "not", "auth_header", ":", "raise", "falcon", ".", "HTTPUnauthorized", "(", "description", "=", "'Missing Authorization Header'", ")", "parts", "=", "auth_header", ".", "split", "(", ")", "if", "parts", "[", "0", "]", ".", "lower", "(", ")", "!=", "self", ".", "auth_header_prefix", ".", "lower", "(", ")", ":", "raise", "falcon", ".", "HTTPUnauthorized", "(", "description", "=", "'Invalid Authorization Header: '", "'Must start with {0}'", ".", "format", "(", "self", ".", "auth_header_prefix", ")", ")", "elif", "len", "(", "parts", ")", "==", "1", ":", "raise", "falcon", ".", "HTTPUnauthorized", "(", "description", "=", "'Invalid Authorization Header: Token Missing'", ")", "elif", "len", "(", "parts", ")", ">", "2", ":", "raise", "falcon", ".", "HTTPUnauthorized", "(", "description", "=", "'Invalid Authorization Header: Contains extra content'", ")", "return", "parts", "[", "1", "]" ]
Parses and returns Auth token from the request header. Raises `falcon.HTTPUnauthoried exception` with proper error message
[ "Parses", "and", "returns", "Auth", "token", "from", "the", "request", "header", ".", "Raises", "falcon", ".", "HTTPUnauthoried", "exception", "with", "proper", "error", "message" ]
train
https://github.com/loanzen/falcon-auth/blob/b9063163fff8044a8579a6047a85f28f3b214fdf/falcon_auth/backends.py#L52-L75
loanzen/falcon-auth
falcon_auth/backends.py
AuthBackend.get_auth_header
def get_auth_header(self, user_payload): """ Returns the value for authorization header Args: user_payload(dict, required): A `dict` containing required information to create authentication token """ auth_token = self.get_auth_token(user_payload) return '{auth_header_prefix} {auth_token}'.format( auth_header_prefix=self.auth_header_prefix, auth_token=auth_token )
python
def get_auth_header(self, user_payload): auth_token = self.get_auth_token(user_payload) return '{auth_header_prefix} {auth_token}'.format( auth_header_prefix=self.auth_header_prefix, auth_token=auth_token )
[ "def", "get_auth_header", "(", "self", ",", "user_payload", ")", ":", "auth_token", "=", "self", ".", "get_auth_token", "(", "user_payload", ")", "return", "'{auth_header_prefix} {auth_token}'", ".", "format", "(", "auth_header_prefix", "=", "self", ".", "auth_header_prefix", ",", "auth_token", "=", "auth_token", ")" ]
Returns the value for authorization header Args: user_payload(dict, required): A `dict` containing required information to create authentication token
[ "Returns", "the", "value", "for", "authorization", "header", "Args", ":", "user_payload", "(", "dict", "required", ")", ":", "A", "dict", "containing", "required", "information", "to", "create", "authentication", "token" ]
train
https://github.com/loanzen/falcon-auth/blob/b9063163fff8044a8579a6047a85f28f3b214fdf/falcon_auth/backends.py#L95-L105
loanzen/falcon-auth
falcon_auth/backends.py
JWTAuthBackend.authenticate
def authenticate(self, req, resp, resource): """ Extract auth token from request `authorization` header, decode jwt token, verify configured claims and return either a ``user`` object if successful else raise an `falcon.HTTPUnauthoried exception` """ payload = self._decode_jwt_token(req) user = self.user_loader(payload) if not user: raise falcon.HTTPUnauthorized( description='Invalid JWT Credentials') return user
python
def authenticate(self, req, resp, resource): payload = self._decode_jwt_token(req) user = self.user_loader(payload) if not user: raise falcon.HTTPUnauthorized( description='Invalid JWT Credentials') return user
[ "def", "authenticate", "(", "self", ",", "req", ",", "resp", ",", "resource", ")", ":", "payload", "=", "self", ".", "_decode_jwt_token", "(", "req", ")", "user", "=", "self", ".", "user_loader", "(", "payload", ")", "if", "not", "user", ":", "raise", "falcon", ".", "HTTPUnauthorized", "(", "description", "=", "'Invalid JWT Credentials'", ")", "return", "user" ]
Extract auth token from request `authorization` header, decode jwt token, verify configured claims and return either a ``user`` object if successful else raise an `falcon.HTTPUnauthoried exception`
[ "Extract", "auth", "token", "from", "request", "authorization", "header", "decode", "jwt", "token", "verify", "configured", "claims", "and", "return", "either", "a", "user", "object", "if", "successful", "else", "raise", "an", "falcon", ".", "HTTPUnauthoried", "exception" ]
train
https://github.com/loanzen/falcon-auth/blob/b9063163fff8044a8579a6047a85f28f3b214fdf/falcon_auth/backends.py#L213-L225
loanzen/falcon-auth
falcon_auth/backends.py
JWTAuthBackend.get_auth_token
def get_auth_token(self, user_payload): """ Create a JWT authentication token from ``user_payload`` Args: user_payload(dict, required): A `dict` containing required information to create authentication token """ now = datetime.utcnow() payload = { 'user': user_payload } if 'iat' in self.verify_claims: payload['iat'] = now if 'nbf' in self.verify_claims: payload['nbf'] = now + self.leeway if 'exp' in self.verify_claims: payload['exp'] = now + self.expiration_delta if self.audience is not None: payload['aud'] = self.audience if self.issuer is not None: payload['iss'] = self.issuer return jwt.encode( payload, self.secret_key, algorithm=self.algorithm, json_encoder=ExtendedJSONEncoder).decode('utf-8')
python
def get_auth_token(self, user_payload): now = datetime.utcnow() payload = { 'user': user_payload } if 'iat' in self.verify_claims: payload['iat'] = now if 'nbf' in self.verify_claims: payload['nbf'] = now + self.leeway if 'exp' in self.verify_claims: payload['exp'] = now + self.expiration_delta if self.audience is not None: payload['aud'] = self.audience if self.issuer is not None: payload['iss'] = self.issuer return jwt.encode( payload, self.secret_key, algorithm=self.algorithm, json_encoder=ExtendedJSONEncoder).decode('utf-8')
[ "def", "get_auth_token", "(", "self", ",", "user_payload", ")", ":", "now", "=", "datetime", ".", "utcnow", "(", ")", "payload", "=", "{", "'user'", ":", "user_payload", "}", "if", "'iat'", "in", "self", ".", "verify_claims", ":", "payload", "[", "'iat'", "]", "=", "now", "if", "'nbf'", "in", "self", ".", "verify_claims", ":", "payload", "[", "'nbf'", "]", "=", "now", "+", "self", ".", "leeway", "if", "'exp'", "in", "self", ".", "verify_claims", ":", "payload", "[", "'exp'", "]", "=", "now", "+", "self", ".", "expiration_delta", "if", "self", ".", "audience", "is", "not", "None", ":", "payload", "[", "'aud'", "]", "=", "self", ".", "audience", "if", "self", ".", "issuer", "is", "not", "None", ":", "payload", "[", "'iss'", "]", "=", "self", ".", "issuer", "return", "jwt", ".", "encode", "(", "payload", ",", "self", ".", "secret_key", ",", "algorithm", "=", "self", ".", "algorithm", ",", "json_encoder", "=", "ExtendedJSONEncoder", ")", ".", "decode", "(", "'utf-8'", ")" ]
Create a JWT authentication token from ``user_payload`` Args: user_payload(dict, required): A `dict` containing required information to create authentication token
[ "Create", "a", "JWT", "authentication", "token", "from", "user_payload" ]
train
https://github.com/loanzen/falcon-auth/blob/b9063163fff8044a8579a6047a85f28f3b214fdf/falcon_auth/backends.py#L227-L258
loanzen/falcon-auth
falcon_auth/backends.py
BasicAuthBackend.authenticate
def authenticate(self, req, resp, resource): """ Extract basic auth token from request `authorization` header, deocode the token, verifies the username/password and return either a ``user`` object if successful else raise an `falcon.HTTPUnauthoried exception` """ username, password = self._extract_credentials(req) user = self.user_loader(username, password) if not user: raise falcon.HTTPUnauthorized( description='Invalid Username/Password') return user
python
def authenticate(self, req, resp, resource): username, password = self._extract_credentials(req) user = self.user_loader(username, password) if not user: raise falcon.HTTPUnauthorized( description='Invalid Username/Password') return user
[ "def", "authenticate", "(", "self", ",", "req", ",", "resp", ",", "resource", ")", ":", "username", ",", "password", "=", "self", ".", "_extract_credentials", "(", "req", ")", "user", "=", "self", ".", "user_loader", "(", "username", ",", "password", ")", "if", "not", "user", ":", "raise", "falcon", ".", "HTTPUnauthorized", "(", "description", "=", "'Invalid Username/Password'", ")", "return", "user" ]
Extract basic auth token from request `authorization` header, deocode the token, verifies the username/password and return either a ``user`` object if successful else raise an `falcon.HTTPUnauthoried exception`
[ "Extract", "basic", "auth", "token", "from", "request", "authorization", "header", "deocode", "the", "token", "verifies", "the", "username", "/", "password", "and", "return", "either", "a", "user", "object", "if", "successful", "else", "raise", "an", "falcon", ".", "HTTPUnauthoried", "exception" ]
train
https://github.com/loanzen/falcon-auth/blob/b9063163fff8044a8579a6047a85f28f3b214fdf/falcon_auth/backends.py#L307-L319
loanzen/falcon-auth
falcon_auth/backends.py
BasicAuthBackend.get_auth_token
def get_auth_token(self, user_payload): """ Extracts username, password from the `user_payload` and encode the credentials `username:password` in `base64` form """ username = user_payload.get('username') or None password = user_payload.get('password') or None if not username or not password: raise ValueError('`user_payload` must contain both username and password') token = '{username}:{password}'.format( username=username, password=password).encode('utf-8') token_b64 = base64.b64encode(token).decode('utf-8', 'ignore') return '{auth_header_prefix} {token_b64}'.format( auth_header_prefix=self.auth_header_prefix, token_b64=token_b64)
python
def get_auth_token(self, user_payload): username = user_payload.get('username') or None password = user_payload.get('password') or None if not username or not password: raise ValueError('`user_payload` must contain both username and password') token = '{username}:{password}'.format( username=username, password=password).encode('utf-8') token_b64 = base64.b64encode(token).decode('utf-8', 'ignore') return '{auth_header_prefix} {token_b64}'.format( auth_header_prefix=self.auth_header_prefix, token_b64=token_b64)
[ "def", "get_auth_token", "(", "self", ",", "user_payload", ")", ":", "username", "=", "user_payload", ".", "get", "(", "'username'", ")", "or", "None", "password", "=", "user_payload", ".", "get", "(", "'password'", ")", "or", "None", "if", "not", "username", "or", "not", "password", ":", "raise", "ValueError", "(", "'`user_payload` must contain both username and password'", ")", "token", "=", "'{username}:{password}'", ".", "format", "(", "username", "=", "username", ",", "password", "=", "password", ")", ".", "encode", "(", "'utf-8'", ")", "token_b64", "=", "base64", ".", "b64encode", "(", "token", ")", ".", "decode", "(", "'utf-8'", ",", "'ignore'", ")", "return", "'{auth_header_prefix} {token_b64}'", ".", "format", "(", "auth_header_prefix", "=", "self", ".", "auth_header_prefix", ",", "token_b64", "=", "token_b64", ")" ]
Extracts username, password from the `user_payload` and encode the credentials `username:password` in `base64` form
[ "Extracts", "username", "password", "from", "the", "user_payload", "and", "encode", "the", "credentials", "username", ":", "password", "in", "base64", "form" ]
train
https://github.com/loanzen/falcon-auth/blob/b9063163fff8044a8579a6047a85f28f3b214fdf/falcon_auth/backends.py#L321-L338
loanzen/falcon-auth
falcon_auth/backends.py
TokenAuthBackend.get_auth_token
def get_auth_token(self, user_payload): """ Extracts token from the `user_payload` """ token = user_payload.get('token') or None if not token: raise ValueError('`user_payload` must provide api token') return '{auth_header_prefix} {token}'.format( auth_header_prefix=self.auth_header_prefix, token=token)
python
def get_auth_token(self, user_payload): token = user_payload.get('token') or None if not token: raise ValueError('`user_payload` must provide api token') return '{auth_header_prefix} {token}'.format( auth_header_prefix=self.auth_header_prefix, token=token)
[ "def", "get_auth_token", "(", "self", ",", "user_payload", ")", ":", "token", "=", "user_payload", ".", "get", "(", "'token'", ")", "or", "None", "if", "not", "token", ":", "raise", "ValueError", "(", "'`user_payload` must provide api token'", ")", "return", "'{auth_header_prefix} {token}'", ".", "format", "(", "auth_header_prefix", "=", "self", ".", "auth_header_prefix", ",", "token", "=", "token", ")" ]
Extracts token from the `user_payload`
[ "Extracts", "token", "from", "the", "user_payload" ]
train
https://github.com/loanzen/falcon-auth/blob/b9063163fff8044a8579a6047a85f28f3b214fdf/falcon_auth/backends.py#L379-L388
loanzen/falcon-auth
falcon_auth/backends.py
HawkAuthBackend.parse_auth_token_from_request
def parse_auth_token_from_request(self, auth_header): """ Parses and returns the Hawk Authorization header if it is present and well-formed. Raises `falcon.HTTPUnauthoried exception` with proper error message """ if not auth_header: raise falcon.HTTPUnauthorized( description='Missing Authorization Header') try: auth_header_prefix, _ = auth_header.split(' ', 1) except ValueError: raise falcon.HTTPUnauthorized( description='Invalid Authorization Header: Missing Scheme or Parameters') if auth_header_prefix.lower() != self.auth_header_prefix.lower(): raise falcon.HTTPUnauthorized( description='Invalid Authorization Header: ' 'Must start with {0}'.format(self.auth_header_prefix)) return auth_header
python
def parse_auth_token_from_request(self, auth_header): if not auth_header: raise falcon.HTTPUnauthorized( description='Missing Authorization Header') try: auth_header_prefix, _ = auth_header.split(' ', 1) except ValueError: raise falcon.HTTPUnauthorized( description='Invalid Authorization Header: Missing Scheme or Parameters') if auth_header_prefix.lower() != self.auth_header_prefix.lower(): raise falcon.HTTPUnauthorized( description='Invalid Authorization Header: ' 'Must start with {0}'.format(self.auth_header_prefix)) return auth_header
[ "def", "parse_auth_token_from_request", "(", "self", ",", "auth_header", ")", ":", "if", "not", "auth_header", ":", "raise", "falcon", ".", "HTTPUnauthorized", "(", "description", "=", "'Missing Authorization Header'", ")", "try", ":", "auth_header_prefix", ",", "_", "=", "auth_header", ".", "split", "(", "' '", ",", "1", ")", "except", "ValueError", ":", "raise", "falcon", ".", "HTTPUnauthorized", "(", "description", "=", "'Invalid Authorization Header: Missing Scheme or Parameters'", ")", "if", "auth_header_prefix", ".", "lower", "(", ")", "!=", "self", ".", "auth_header_prefix", ".", "lower", "(", ")", ":", "raise", "falcon", ".", "HTTPUnauthorized", "(", "description", "=", "'Invalid Authorization Header: '", "'Must start with {0}'", ".", "format", "(", "self", ".", "auth_header_prefix", ")", ")", "return", "auth_header" ]
Parses and returns the Hawk Authorization header if it is present and well-formed. Raises `falcon.HTTPUnauthoried exception` with proper error message
[ "Parses", "and", "returns", "the", "Hawk", "Authorization", "header", "if", "it", "is", "present", "and", "well", "-", "formed", ".", "Raises", "falcon", ".", "HTTPUnauthoried", "exception", "with", "proper", "error", "message" ]
train
https://github.com/loanzen/falcon-auth/blob/b9063163fff8044a8579a6047a85f28f3b214fdf/falcon_auth/backends.py#L442-L462
gmarull/qtmodern
qtmodern/styles.py
_apply_base_theme
def _apply_base_theme(app): """ Apply base theme to the application. Args: app (QApplication): QApplication instance. """ if QT_VERSION < (5,): app.setStyle('plastique') else: app.setStyle('Fusion') with open(_STYLESHEET) as stylesheet: app.setStyleSheet(stylesheet.read())
python
def _apply_base_theme(app): if QT_VERSION < (5,): app.setStyle('plastique') else: app.setStyle('Fusion') with open(_STYLESHEET) as stylesheet: app.setStyleSheet(stylesheet.read())
[ "def", "_apply_base_theme", "(", "app", ")", ":", "if", "QT_VERSION", "<", "(", "5", ",", ")", ":", "app", ".", "setStyle", "(", "'plastique'", ")", "else", ":", "app", ".", "setStyle", "(", "'Fusion'", ")", "with", "open", "(", "_STYLESHEET", ")", "as", "stylesheet", ":", "app", ".", "setStyleSheet", "(", "stylesheet", ".", "read", "(", ")", ")" ]
Apply base theme to the application. Args: app (QApplication): QApplication instance.
[ "Apply", "base", "theme", "to", "the", "application", "." ]
train
https://github.com/gmarull/qtmodern/blob/b58b24c5bcfa0b81c7b1af5a7dfdc0fae660ce0f/qtmodern/styles.py#L11-L24
gmarull/qtmodern
qtmodern/styles.py
dark
def dark(app): """ Apply Dark Theme to the Qt application instance. Args: app (QApplication): QApplication instance. """ _apply_base_theme(app) darkPalette = QPalette() # base darkPalette.setColor(QPalette.WindowText, QColor(180, 180, 180)) darkPalette.setColor(QPalette.Button, QColor(53, 53, 53)) darkPalette.setColor(QPalette.Light, QColor(180, 180, 180)) darkPalette.setColor(QPalette.Midlight, QColor(90, 90, 90)) darkPalette.setColor(QPalette.Dark, QColor(35, 35, 35)) darkPalette.setColor(QPalette.Text, QColor(180, 180, 180)) darkPalette.setColor(QPalette.BrightText, QColor(180, 180, 180)) darkPalette.setColor(QPalette.ButtonText, QColor(180, 180, 180)) darkPalette.setColor(QPalette.Base, QColor(42, 42, 42)) darkPalette.setColor(QPalette.Window, QColor(53, 53, 53)) darkPalette.setColor(QPalette.Shadow, QColor(20, 20, 20)) darkPalette.setColor(QPalette.Highlight, QColor(42, 130, 218)) darkPalette.setColor(QPalette.HighlightedText, QColor(180, 180, 180)) darkPalette.setColor(QPalette.Link, QColor(56, 252, 196)) darkPalette.setColor(QPalette.AlternateBase, QColor(66, 66, 66)) darkPalette.setColor(QPalette.ToolTipBase, QColor(53, 53, 53)) darkPalette.setColor(QPalette.ToolTipText, QColor(180, 180, 180)) # disabled darkPalette.setColor(QPalette.Disabled, QPalette.WindowText, QColor(127, 127, 127)) darkPalette.setColor(QPalette.Disabled, QPalette.Text, QColor(127, 127, 127)) darkPalette.setColor(QPalette.Disabled, QPalette.ButtonText, QColor(127, 127, 127)) darkPalette.setColor(QPalette.Disabled, QPalette.Highlight, QColor(80, 80, 80)) darkPalette.setColor(QPalette.Disabled, QPalette.HighlightedText, QColor(127, 127, 127)) app.setPalette(darkPalette)
python
def dark(app): _apply_base_theme(app) darkPalette = QPalette() darkPalette.setColor(QPalette.WindowText, QColor(180, 180, 180)) darkPalette.setColor(QPalette.Button, QColor(53, 53, 53)) darkPalette.setColor(QPalette.Light, QColor(180, 180, 180)) darkPalette.setColor(QPalette.Midlight, QColor(90, 90, 90)) darkPalette.setColor(QPalette.Dark, QColor(35, 35, 35)) darkPalette.setColor(QPalette.Text, QColor(180, 180, 180)) darkPalette.setColor(QPalette.BrightText, QColor(180, 180, 180)) darkPalette.setColor(QPalette.ButtonText, QColor(180, 180, 180)) darkPalette.setColor(QPalette.Base, QColor(42, 42, 42)) darkPalette.setColor(QPalette.Window, QColor(53, 53, 53)) darkPalette.setColor(QPalette.Shadow, QColor(20, 20, 20)) darkPalette.setColor(QPalette.Highlight, QColor(42, 130, 218)) darkPalette.setColor(QPalette.HighlightedText, QColor(180, 180, 180)) darkPalette.setColor(QPalette.Link, QColor(56, 252, 196)) darkPalette.setColor(QPalette.AlternateBase, QColor(66, 66, 66)) darkPalette.setColor(QPalette.ToolTipBase, QColor(53, 53, 53)) darkPalette.setColor(QPalette.ToolTipText, QColor(180, 180, 180)) darkPalette.setColor(QPalette.Disabled, QPalette.WindowText, QColor(127, 127, 127)) darkPalette.setColor(QPalette.Disabled, QPalette.Text, QColor(127, 127, 127)) darkPalette.setColor(QPalette.Disabled, QPalette.ButtonText, QColor(127, 127, 127)) darkPalette.setColor(QPalette.Disabled, QPalette.Highlight, QColor(80, 80, 80)) darkPalette.setColor(QPalette.Disabled, QPalette.HighlightedText, QColor(127, 127, 127)) app.setPalette(darkPalette)
[ "def", "dark", "(", "app", ")", ":", "_apply_base_theme", "(", "app", ")", "darkPalette", "=", "QPalette", "(", ")", "# base", "darkPalette", ".", "setColor", "(", "QPalette", ".", "WindowText", ",", "QColor", "(", "180", ",", "180", ",", "180", ")", ")", "darkPalette", ".", "setColor", "(", "QPalette", ".", "Button", ",", "QColor", "(", "53", ",", "53", ",", "53", ")", ")", "darkPalette", ".", "setColor", "(", "QPalette", ".", "Light", ",", "QColor", "(", "180", ",", "180", ",", "180", ")", ")", "darkPalette", ".", "setColor", "(", "QPalette", ".", "Midlight", ",", "QColor", "(", "90", ",", "90", ",", "90", ")", ")", "darkPalette", ".", "setColor", "(", "QPalette", ".", "Dark", ",", "QColor", "(", "35", ",", "35", ",", "35", ")", ")", "darkPalette", ".", "setColor", "(", "QPalette", ".", "Text", ",", "QColor", "(", "180", ",", "180", ",", "180", ")", ")", "darkPalette", ".", "setColor", "(", "QPalette", ".", "BrightText", ",", "QColor", "(", "180", ",", "180", ",", "180", ")", ")", "darkPalette", ".", "setColor", "(", "QPalette", ".", "ButtonText", ",", "QColor", "(", "180", ",", "180", ",", "180", ")", ")", "darkPalette", ".", "setColor", "(", "QPalette", ".", "Base", ",", "QColor", "(", "42", ",", "42", ",", "42", ")", ")", "darkPalette", ".", "setColor", "(", "QPalette", ".", "Window", ",", "QColor", "(", "53", ",", "53", ",", "53", ")", ")", "darkPalette", ".", "setColor", "(", "QPalette", ".", "Shadow", ",", "QColor", "(", "20", ",", "20", ",", "20", ")", ")", "darkPalette", ".", "setColor", "(", "QPalette", ".", "Highlight", ",", "QColor", "(", "42", ",", "130", ",", "218", ")", ")", "darkPalette", ".", "setColor", "(", "QPalette", ".", "HighlightedText", ",", "QColor", "(", "180", ",", "180", ",", "180", ")", ")", "darkPalette", ".", "setColor", "(", "QPalette", ".", "Link", ",", "QColor", "(", "56", ",", "252", ",", "196", ")", ")", "darkPalette", ".", "setColor", "(", "QPalette", ".", "AlternateBase", ",", "QColor", "(", "66", ",", "66", ",", "66", ")", ")", "darkPalette", ".", "setColor", "(", "QPalette", ".", "ToolTipBase", ",", "QColor", "(", "53", ",", "53", ",", "53", ")", ")", "darkPalette", ".", "setColor", "(", "QPalette", ".", "ToolTipText", ",", "QColor", "(", "180", ",", "180", ",", "180", ")", ")", "# disabled", "darkPalette", ".", "setColor", "(", "QPalette", ".", "Disabled", ",", "QPalette", ".", "WindowText", ",", "QColor", "(", "127", ",", "127", ",", "127", ")", ")", "darkPalette", ".", "setColor", "(", "QPalette", ".", "Disabled", ",", "QPalette", ".", "Text", ",", "QColor", "(", "127", ",", "127", ",", "127", ")", ")", "darkPalette", ".", "setColor", "(", "QPalette", ".", "Disabled", ",", "QPalette", ".", "ButtonText", ",", "QColor", "(", "127", ",", "127", ",", "127", ")", ")", "darkPalette", ".", "setColor", "(", "QPalette", ".", "Disabled", ",", "QPalette", ".", "Highlight", ",", "QColor", "(", "80", ",", "80", ",", "80", ")", ")", "darkPalette", ".", "setColor", "(", "QPalette", ".", "Disabled", ",", "QPalette", ".", "HighlightedText", ",", "QColor", "(", "127", ",", "127", ",", "127", ")", ")", "app", ".", "setPalette", "(", "darkPalette", ")" ]
Apply Dark Theme to the Qt application instance. Args: app (QApplication): QApplication instance.
[ "Apply", "Dark", "Theme", "to", "the", "Qt", "application", "instance", "." ]
train
https://github.com/gmarull/qtmodern/blob/b58b24c5bcfa0b81c7b1af5a7dfdc0fae660ce0f/qtmodern/styles.py#L27-L69
matthias-k/cyipopt
setup.py
pkgconfig
def pkgconfig(*packages, **kw): """Based on http://code.activestate.com/recipes/502261-python-distutils-pkg-config/#c2""" flag_map = {'-I': 'include_dirs', '-L': 'library_dirs', '-l': 'libraries'} output = sp.Popen(["pkg-config", "--libs", "--cflags"] + list(packages), stdout=sp.PIPE).communicate()[0] if six.PY3: output = output.decode('utf8') for token in output.split(): if token[:2] in flag_map: kw.setdefault(flag_map.get(token[:2]), []).append(token[2:]) else: kw.setdefault('extra_compile_args', []).append(token) kw['include_dirs'] += [np.get_include()] return kw
python
def pkgconfig(*packages, **kw): flag_map = {'-I': 'include_dirs', '-L': 'library_dirs', '-l': 'libraries'} output = sp.Popen(["pkg-config", "--libs", "--cflags"] + list(packages), stdout=sp.PIPE).communicate()[0] if six.PY3: output = output.decode('utf8') for token in output.split(): if token[:2] in flag_map: kw.setdefault(flag_map.get(token[:2]), []).append(token[2:]) else: kw.setdefault('extra_compile_args', []).append(token) kw['include_dirs'] += [np.get_include()] return kw
[ "def", "pkgconfig", "(", "*", "packages", ",", "*", "*", "kw", ")", ":", "flag_map", "=", "{", "'-I'", ":", "'include_dirs'", ",", "'-L'", ":", "'library_dirs'", ",", "'-l'", ":", "'libraries'", "}", "output", "=", "sp", ".", "Popen", "(", "[", "\"pkg-config\"", ",", "\"--libs\"", ",", "\"--cflags\"", "]", "+", "list", "(", "packages", ")", ",", "stdout", "=", "sp", ".", "PIPE", ")", ".", "communicate", "(", ")", "[", "0", "]", "if", "six", ".", "PY3", ":", "output", "=", "output", ".", "decode", "(", "'utf8'", ")", "for", "token", "in", "output", ".", "split", "(", ")", ":", "if", "token", "[", ":", "2", "]", "in", "flag_map", ":", "kw", ".", "setdefault", "(", "flag_map", ".", "get", "(", "token", "[", ":", "2", "]", ")", ",", "[", "]", ")", ".", "append", "(", "token", "[", "2", ":", "]", ")", "else", ":", "kw", ".", "setdefault", "(", "'extra_compile_args'", ",", "[", "]", ")", ".", "append", "(", "token", ")", "kw", "[", "'include_dirs'", "]", "+=", "[", "np", ".", "get_include", "(", ")", "]", "return", "kw" ]
Based on http://code.activestate.com/recipes/502261-python-distutils-pkg-config/#c2
[ "Based", "on", "http", ":", "//", "code", ".", "activestate", ".", "com", "/", "recipes", "/", "502261", "-", "python", "-", "distutils", "-", "pkg", "-", "config", "/", "#c2" ]
train
https://github.com/matthias-k/cyipopt/blob/ed03f54de2e0b8c8ba4c0aa18ab9ab6c8846bc19/setup.py#L48-L64
matthias-k/cyipopt
doc/source/sphinxext/inheritance_diagram.py
inheritance_diagram_directive
def inheritance_diagram_directive(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): """ Run when the inheritance_diagram directive is first encountered. """ node = inheritance_diagram() class_names = arguments # Create a graph starting with the list of classes graph = InheritanceGraph(class_names) # Create xref nodes for each target of the graph's image map and # add them to the doc tree so that Sphinx can resolve the # references to real URLs later. These nodes will eventually be # removed from the doctree after we're done with them. for name in graph.get_all_class_names(): refnodes, x = xfileref_role( 'class', ':class:`%s`' % name, name, 0, state) node.extend(refnodes) # Store the graph object so we can use it to generate the # dot file later node['graph'] = graph # Store the original content for use as a hash node['parts'] = options.get('parts', 0) node['content'] = " ".join(class_names) return [node]
python
def inheritance_diagram_directive(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): node = inheritance_diagram() class_names = arguments graph = InheritanceGraph(class_names) for name in graph.get_all_class_names(): refnodes, x = xfileref_role( 'class', ':class:`%s`' % name, name, 0, state) node.extend(refnodes) node['graph'] = graph node['parts'] = options.get('parts', 0) node['content'] = " ".join(class_names) return [node]
[ "def", "inheritance_diagram_directive", "(", "name", ",", "arguments", ",", "options", ",", "content", ",", "lineno", ",", "content_offset", ",", "block_text", ",", "state", ",", "state_machine", ")", ":", "node", "=", "inheritance_diagram", "(", ")", "class_names", "=", "arguments", "# Create a graph starting with the list of classes", "graph", "=", "InheritanceGraph", "(", "class_names", ")", "# Create xref nodes for each target of the graph's image map and", "# add them to the doc tree so that Sphinx can resolve the", "# references to real URLs later. These nodes will eventually be", "# removed from the doctree after we're done with them.", "for", "name", "in", "graph", ".", "get_all_class_names", "(", ")", ":", "refnodes", ",", "x", "=", "xfileref_role", "(", "'class'", ",", "':class:`%s`'", "%", "name", ",", "name", ",", "0", ",", "state", ")", "node", ".", "extend", "(", "refnodes", ")", "# Store the graph object so we can use it to generate the", "# dot file later", "node", "[", "'graph'", "]", "=", "graph", "# Store the original content for use as a hash", "node", "[", "'parts'", "]", "=", "options", ".", "get", "(", "'parts'", ",", "0", ")", "node", "[", "'content'", "]", "=", "\" \"", ".", "join", "(", "class_names", ")", "return", "[", "node", "]" ]
Run when the inheritance_diagram directive is first encountered.
[ "Run", "when", "the", "inheritance_diagram", "directive", "is", "first", "encountered", "." ]
train
https://github.com/matthias-k/cyipopt/blob/ed03f54de2e0b8c8ba4c0aa18ab9ab6c8846bc19/doc/source/sphinxext/inheritance_diagram.py#L293-L320
matthias-k/cyipopt
doc/source/sphinxext/inheritance_diagram.py
html_output_graph
def html_output_graph(self, node): """ Output the graph for HTML. This will insert a PNG with clickable image map. """ graph = node['graph'] parts = node['parts'] graph_hash = get_graph_hash(node) name = "inheritance%s" % graph_hash path = '_images' dest_path = os.path.join(setup.app.builder.outdir, path) if not os.path.exists(dest_path): os.makedirs(dest_path) png_path = os.path.join(dest_path, name + ".png") path = setup.app.builder.imgpath # Create a mapping from fully-qualified class names to URLs. urls = {} for child in node: if child.get('refuri') is not None: urls[child['reftitle']] = child.get('refuri') elif child.get('refid') is not None: urls[child['reftitle']] = '#' + child.get('refid') # These arguments to dot will save a PNG file to disk and write # an HTML image map to stdout. image_map = graph.run_dot(['-Tpng', '-o%s' % png_path, '-Tcmapx'], name, parts, urls) return ('<img src="%s/%s.png" usemap="#%s" class="inheritance"/>%s' % (path, name, name, image_map))
python
def html_output_graph(self, node): graph = node['graph'] parts = node['parts'] graph_hash = get_graph_hash(node) name = "inheritance%s" % graph_hash path = '_images' dest_path = os.path.join(setup.app.builder.outdir, path) if not os.path.exists(dest_path): os.makedirs(dest_path) png_path = os.path.join(dest_path, name + ".png") path = setup.app.builder.imgpath urls = {} for child in node: if child.get('refuri') is not None: urls[child['reftitle']] = child.get('refuri') elif child.get('refid') is not None: urls[child['reftitle']] = ' image_map = graph.run_dot(['-Tpng', '-o%s' % png_path, '-Tcmapx'], name, parts, urls) return ('<img src="%s/%s.png" usemap=" (path, name, name, image_map))
[ "def", "html_output_graph", "(", "self", ",", "node", ")", ":", "graph", "=", "node", "[", "'graph'", "]", "parts", "=", "node", "[", "'parts'", "]", "graph_hash", "=", "get_graph_hash", "(", "node", ")", "name", "=", "\"inheritance%s\"", "%", "graph_hash", "path", "=", "'_images'", "dest_path", "=", "os", ".", "path", ".", "join", "(", "setup", ".", "app", ".", "builder", ".", "outdir", ",", "path", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "dest_path", ")", ":", "os", ".", "makedirs", "(", "dest_path", ")", "png_path", "=", "os", ".", "path", ".", "join", "(", "dest_path", ",", "name", "+", "\".png\"", ")", "path", "=", "setup", ".", "app", ".", "builder", ".", "imgpath", "# Create a mapping from fully-qualified class names to URLs.", "urls", "=", "{", "}", "for", "child", "in", "node", ":", "if", "child", ".", "get", "(", "'refuri'", ")", "is", "not", "None", ":", "urls", "[", "child", "[", "'reftitle'", "]", "]", "=", "child", ".", "get", "(", "'refuri'", ")", "elif", "child", ".", "get", "(", "'refid'", ")", "is", "not", "None", ":", "urls", "[", "child", "[", "'reftitle'", "]", "]", "=", "'#'", "+", "child", ".", "get", "(", "'refid'", ")", "# These arguments to dot will save a PNG file to disk and write", "# an HTML image map to stdout.", "image_map", "=", "graph", ".", "run_dot", "(", "[", "'-Tpng'", ",", "'-o%s'", "%", "png_path", ",", "'-Tcmapx'", "]", ",", "name", ",", "parts", ",", "urls", ")", "return", "(", "'<img src=\"%s/%s.png\" usemap=\"#%s\" class=\"inheritance\"/>%s'", "%", "(", "path", ",", "name", ",", "name", ",", "image_map", ")", ")" ]
Output the graph for HTML. This will insert a PNG with clickable image map.
[ "Output", "the", "graph", "for", "HTML", ".", "This", "will", "insert", "a", "PNG", "with", "clickable", "image", "map", "." ]
train
https://github.com/matthias-k/cyipopt/blob/ed03f54de2e0b8c8ba4c0aa18ab9ab6c8846bc19/doc/source/sphinxext/inheritance_diagram.py#L325-L355
matthias-k/cyipopt
doc/source/sphinxext/inheritance_diagram.py
latex_output_graph
def latex_output_graph(self, node): """ Output the graph for LaTeX. This will insert a PDF. """ graph = node['graph'] parts = node['parts'] graph_hash = get_graph_hash(node) name = "inheritance%s" % graph_hash dest_path = os.path.abspath(os.path.join(setup.app.builder.outdir, '_images')) if not os.path.exists(dest_path): os.makedirs(dest_path) pdf_path = os.path.abspath(os.path.join(dest_path, name + ".pdf")) graph.run_dot(['-Tpdf', '-o%s' % pdf_path], name, parts, graph_options={'size': '"6.0,6.0"'}) return '\n\\includegraphics{%s}\n\n' % pdf_path
python
def latex_output_graph(self, node): graph = node['graph'] parts = node['parts'] graph_hash = get_graph_hash(node) name = "inheritance%s" % graph_hash dest_path = os.path.abspath(os.path.join(setup.app.builder.outdir, '_images')) if not os.path.exists(dest_path): os.makedirs(dest_path) pdf_path = os.path.abspath(os.path.join(dest_path, name + ".pdf")) graph.run_dot(['-Tpdf', '-o%s' % pdf_path], name, parts, graph_options={'size': '"6.0,6.0"'}) return '\n\\includegraphics{%s}\n\n' % pdf_path
[ "def", "latex_output_graph", "(", "self", ",", "node", ")", ":", "graph", "=", "node", "[", "'graph'", "]", "parts", "=", "node", "[", "'parts'", "]", "graph_hash", "=", "get_graph_hash", "(", "node", ")", "name", "=", "\"inheritance%s\"", "%", "graph_hash", "dest_path", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "setup", ".", "app", ".", "builder", ".", "outdir", ",", "'_images'", ")", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "dest_path", ")", ":", "os", ".", "makedirs", "(", "dest_path", ")", "pdf_path", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "dest_path", ",", "name", "+", "\".pdf\"", ")", ")", "graph", ".", "run_dot", "(", "[", "'-Tpdf'", ",", "'-o%s'", "%", "pdf_path", "]", ",", "name", ",", "parts", ",", "graph_options", "=", "{", "'size'", ":", "'\"6.0,6.0\"'", "}", ")", "return", "'\\n\\\\includegraphics{%s}\\n\\n'", "%", "pdf_path" ]
Output the graph for LaTeX. This will insert a PDF.
[ "Output", "the", "graph", "for", "LaTeX", ".", "This", "will", "insert", "a", "PDF", "." ]
train
https://github.com/matthias-k/cyipopt/blob/ed03f54de2e0b8c8ba4c0aa18ab9ab6c8846bc19/doc/source/sphinxext/inheritance_diagram.py#L357-L373
matthias-k/cyipopt
doc/source/sphinxext/inheritance_diagram.py
visit_inheritance_diagram
def visit_inheritance_diagram(inner_func): """ This is just a wrapper around html/latex_output_graph to make it easier to handle errors and insert warnings. """ def visitor(self, node): try: content = inner_func(self, node) except DotException, e: # Insert the exception as a warning in the document warning = self.document.reporter.warning(str(e), line=node.line) warning.parent = node node.children = [warning] else: source = self.document.attributes['source'] self.body.append(content) node.children = [] return visitor
python
def visit_inheritance_diagram(inner_func): def visitor(self, node): try: content = inner_func(self, node) except DotException, e: warning = self.document.reporter.warning(str(e), line=node.line) warning.parent = node node.children = [warning] else: source = self.document.attributes['source'] self.body.append(content) node.children = [] return visitor
[ "def", "visit_inheritance_diagram", "(", "inner_func", ")", ":", "def", "visitor", "(", "self", ",", "node", ")", ":", "try", ":", "content", "=", "inner_func", "(", "self", ",", "node", ")", "except", "DotException", ",", "e", ":", "# Insert the exception as a warning in the document", "warning", "=", "self", ".", "document", ".", "reporter", ".", "warning", "(", "str", "(", "e", ")", ",", "line", "=", "node", ".", "line", ")", "warning", ".", "parent", "=", "node", "node", ".", "children", "=", "[", "warning", "]", "else", ":", "source", "=", "self", ".", "document", ".", "attributes", "[", "'source'", "]", "self", ".", "body", ".", "append", "(", "content", ")", "node", ".", "children", "=", "[", "]", "return", "visitor" ]
This is just a wrapper around html/latex_output_graph to make it easier to handle errors and insert warnings.
[ "This", "is", "just", "a", "wrapper", "around", "html", "/", "latex_output_graph", "to", "make", "it", "easier", "to", "handle", "errors", "and", "insert", "warnings", "." ]
train
https://github.com/matthias-k/cyipopt/blob/ed03f54de2e0b8c8ba4c0aa18ab9ab6c8846bc19/doc/source/sphinxext/inheritance_diagram.py#L375-L392
matthias-k/cyipopt
doc/source/sphinxext/inheritance_diagram.py
InheritanceGraph._import_class_or_module
def _import_class_or_module(self, name): """ Import a class using its fully-qualified *name*. """ try: path, base = self.py_sig_re.match(name).groups() except: raise ValueError( "Invalid class or module '%s' specified for inheritance diagram" % name) fullname = (path or '') + base path = (path and path.rstrip('.')) if not path: path = base try: module = __import__(path, None, None, []) # We must do an import of the fully qualified name. Otherwise if a # subpackage 'a.b' is requested where 'import a' does NOT provide # 'a.b' automatically, then 'a.b' will not be found below. This # second call will force the equivalent of 'import a.b' to happen # after the top-level import above. my_import(fullname) except ImportError: raise ValueError( "Could not import class or module '%s' specified for inheritance diagram" % name) try: todoc = module for comp in fullname.split('.')[1:]: todoc = getattr(todoc, comp) except AttributeError: raise ValueError( "Could not find class or module '%s' specified for inheritance diagram" % name) # If a class, just return it if inspect.isclass(todoc): return [todoc] elif inspect.ismodule(todoc): classes = [] for cls in todoc.__dict__.values(): if inspect.isclass(cls) and cls.__module__ == todoc.__name__: classes.append(cls) return classes raise ValueError( "'%s' does not resolve to a class or module" % name)
python
def _import_class_or_module(self, name): try: path, base = self.py_sig_re.match(name).groups() except: raise ValueError( "Invalid class or module '%s' specified for inheritance diagram" % name) fullname = (path or '') + base path = (path and path.rstrip('.')) if not path: path = base try: module = __import__(path, None, None, []) my_import(fullname) except ImportError: raise ValueError( "Could not import class or module '%s' specified for inheritance diagram" % name) try: todoc = module for comp in fullname.split('.')[1:]: todoc = getattr(todoc, comp) except AttributeError: raise ValueError( "Could not find class or module '%s' specified for inheritance diagram" % name) if inspect.isclass(todoc): return [todoc] elif inspect.ismodule(todoc): classes = [] for cls in todoc.__dict__.values(): if inspect.isclass(cls) and cls.__module__ == todoc.__name__: classes.append(cls) return classes raise ValueError( "'%s' does not resolve to a class or module" % name)
[ "def", "_import_class_or_module", "(", "self", ",", "name", ")", ":", "try", ":", "path", ",", "base", "=", "self", ".", "py_sig_re", ".", "match", "(", "name", ")", ".", "groups", "(", ")", "except", ":", "raise", "ValueError", "(", "\"Invalid class or module '%s' specified for inheritance diagram\"", "%", "name", ")", "fullname", "=", "(", "path", "or", "''", ")", "+", "base", "path", "=", "(", "path", "and", "path", ".", "rstrip", "(", "'.'", ")", ")", "if", "not", "path", ":", "path", "=", "base", "try", ":", "module", "=", "__import__", "(", "path", ",", "None", ",", "None", ",", "[", "]", ")", "# We must do an import of the fully qualified name. Otherwise if a", "# subpackage 'a.b' is requested where 'import a' does NOT provide", "# 'a.b' automatically, then 'a.b' will not be found below. This", "# second call will force the equivalent of 'import a.b' to happen", "# after the top-level import above.", "my_import", "(", "fullname", ")", "except", "ImportError", ":", "raise", "ValueError", "(", "\"Could not import class or module '%s' specified for inheritance diagram\"", "%", "name", ")", "try", ":", "todoc", "=", "module", "for", "comp", "in", "fullname", ".", "split", "(", "'.'", ")", "[", "1", ":", "]", ":", "todoc", "=", "getattr", "(", "todoc", ",", "comp", ")", "except", "AttributeError", ":", "raise", "ValueError", "(", "\"Could not find class or module '%s' specified for inheritance diagram\"", "%", "name", ")", "# If a class, just return it", "if", "inspect", ".", "isclass", "(", "todoc", ")", ":", "return", "[", "todoc", "]", "elif", "inspect", ".", "ismodule", "(", "todoc", ")", ":", "classes", "=", "[", "]", "for", "cls", "in", "todoc", ".", "__dict__", ".", "values", "(", ")", ":", "if", "inspect", ".", "isclass", "(", "cls", ")", "and", "cls", ".", "__module__", "==", "todoc", ".", "__name__", ":", "classes", ".", "append", "(", "cls", ")", "return", "classes", "raise", "ValueError", "(", "\"'%s' does not resolve to a class or module\"", "%", "name", ")" ]
Import a class using its fully-qualified *name*.
[ "Import", "a", "class", "using", "its", "fully", "-", "qualified", "*", "name", "*", "." ]
train
https://github.com/matthias-k/cyipopt/blob/ed03f54de2e0b8c8ba4c0aa18ab9ab6c8846bc19/doc/source/sphinxext/inheritance_diagram.py#L83-L127
matthias-k/cyipopt
doc/source/sphinxext/inheritance_diagram.py
InheritanceGraph._import_classes
def _import_classes(self, class_names): """ Import a list of classes. """ classes = [] for name in class_names: classes.extend(self._import_class_or_module(name)) return classes
python
def _import_classes(self, class_names): classes = [] for name in class_names: classes.extend(self._import_class_or_module(name)) return classes
[ "def", "_import_classes", "(", "self", ",", "class_names", ")", ":", "classes", "=", "[", "]", "for", "name", "in", "class_names", ":", "classes", ".", "extend", "(", "self", ".", "_import_class_or_module", "(", "name", ")", ")", "return", "classes" ]
Import a list of classes.
[ "Import", "a", "list", "of", "classes", "." ]
train
https://github.com/matthias-k/cyipopt/blob/ed03f54de2e0b8c8ba4c0aa18ab9ab6c8846bc19/doc/source/sphinxext/inheritance_diagram.py#L129-L136
matthias-k/cyipopt
doc/source/sphinxext/inheritance_diagram.py
InheritanceGraph._all_classes
def _all_classes(self, classes): """ Return a list of all classes that are ancestors of *classes*. """ all_classes = {} def recurse(cls): all_classes[cls] = None for c in cls.__bases__: if c not in all_classes: recurse(c) for cls in classes: recurse(cls) return all_classes.keys()
python
def _all_classes(self, classes): all_classes = {} def recurse(cls): all_classes[cls] = None for c in cls.__bases__: if c not in all_classes: recurse(c) for cls in classes: recurse(cls) return all_classes.keys()
[ "def", "_all_classes", "(", "self", ",", "classes", ")", ":", "all_classes", "=", "{", "}", "def", "recurse", "(", "cls", ")", ":", "all_classes", "[", "cls", "]", "=", "None", "for", "c", "in", "cls", ".", "__bases__", ":", "if", "c", "not", "in", "all_classes", ":", "recurse", "(", "c", ")", "for", "cls", "in", "classes", ":", "recurse", "(", "cls", ")", "return", "all_classes", ".", "keys", "(", ")" ]
Return a list of all classes that are ancestors of *classes*.
[ "Return", "a", "list", "of", "all", "classes", "that", "are", "ancestors", "of", "*", "classes", "*", "." ]
train
https://github.com/matthias-k/cyipopt/blob/ed03f54de2e0b8c8ba4c0aa18ab9ab6c8846bc19/doc/source/sphinxext/inheritance_diagram.py#L138-L153
matthias-k/cyipopt
doc/source/sphinxext/inheritance_diagram.py
InheritanceGraph.generate_dot
def generate_dot(self, fd, name, parts=0, urls={}, graph_options={}, node_options={}, edge_options={}): """ Generate a graphviz dot graph from the classes that were passed in to __init__. *fd* is a Python file-like object to write to. *name* is the name of the graph *urls* is a dictionary mapping class names to http urls *graph_options*, *node_options*, *edge_options* are dictionaries containing key/value pairs to pass on as graphviz properties. """ g_options = self.default_graph_options.copy() g_options.update(graph_options) n_options = self.default_node_options.copy() n_options.update(node_options) e_options = self.default_edge_options.copy() e_options.update(edge_options) fd.write('digraph %s {\n' % name) fd.write(self._format_graph_options(g_options)) for cls in self.all_classes: if not self.show_builtins and cls in __builtins__.values(): continue name = self.class_name(cls, parts) # Write the node this_node_options = n_options.copy() url = urls.get(self.class_name(cls)) if url is not None: this_node_options['URL'] = '"%s"' % url fd.write(' "%s" [%s];\n' % (name, self._format_node_options(this_node_options))) # Write the edges for base in cls.__bases__: if not self.show_builtins and base in __builtins__.values(): continue base_name = self.class_name(base, parts) fd.write(' "%s" -> "%s" [%s];\n' % (base_name, name, self._format_node_options(e_options))) fd.write('}\n')
python
def generate_dot(self, fd, name, parts=0, urls={}, graph_options={}, node_options={}, edge_options={}): g_options = self.default_graph_options.copy() g_options.update(graph_options) n_options = self.default_node_options.copy() n_options.update(node_options) e_options = self.default_edge_options.copy() e_options.update(edge_options) fd.write('digraph %s {\n' % name) fd.write(self._format_graph_options(g_options)) for cls in self.all_classes: if not self.show_builtins and cls in __builtins__.values(): continue name = self.class_name(cls, parts) this_node_options = n_options.copy() url = urls.get(self.class_name(cls)) if url is not None: this_node_options['URL'] = '"%s"' % url fd.write(' "%s" [%s];\n' % (name, self._format_node_options(this_node_options))) for base in cls.__bases__: if not self.show_builtins and base in __builtins__.values(): continue base_name = self.class_name(base, parts) fd.write(' "%s" -> "%s" [%s];\n' % (base_name, name, self._format_node_options(e_options))) fd.write('}\n')
[ "def", "generate_dot", "(", "self", ",", "fd", ",", "name", ",", "parts", "=", "0", ",", "urls", "=", "{", "}", ",", "graph_options", "=", "{", "}", ",", "node_options", "=", "{", "}", ",", "edge_options", "=", "{", "}", ")", ":", "g_options", "=", "self", ".", "default_graph_options", ".", "copy", "(", ")", "g_options", ".", "update", "(", "graph_options", ")", "n_options", "=", "self", ".", "default_node_options", ".", "copy", "(", ")", "n_options", ".", "update", "(", "node_options", ")", "e_options", "=", "self", ".", "default_edge_options", ".", "copy", "(", ")", "e_options", ".", "update", "(", "edge_options", ")", "fd", ".", "write", "(", "'digraph %s {\\n'", "%", "name", ")", "fd", ".", "write", "(", "self", ".", "_format_graph_options", "(", "g_options", ")", ")", "for", "cls", "in", "self", ".", "all_classes", ":", "if", "not", "self", ".", "show_builtins", "and", "cls", "in", "__builtins__", ".", "values", "(", ")", ":", "continue", "name", "=", "self", ".", "class_name", "(", "cls", ",", "parts", ")", "# Write the node", "this_node_options", "=", "n_options", ".", "copy", "(", ")", "url", "=", "urls", ".", "get", "(", "self", ".", "class_name", "(", "cls", ")", ")", "if", "url", "is", "not", "None", ":", "this_node_options", "[", "'URL'", "]", "=", "'\"%s\"'", "%", "url", "fd", ".", "write", "(", "' \"%s\" [%s];\\n'", "%", "(", "name", ",", "self", ".", "_format_node_options", "(", "this_node_options", ")", ")", ")", "# Write the edges", "for", "base", "in", "cls", ".", "__bases__", ":", "if", "not", "self", ".", "show_builtins", "and", "base", "in", "__builtins__", ".", "values", "(", ")", ":", "continue", "base_name", "=", "self", ".", "class_name", "(", "base", ",", "parts", ")", "fd", ".", "write", "(", "' \"%s\" -> \"%s\" [%s];\\n'", "%", "(", "base_name", ",", "name", ",", "self", ".", "_format_node_options", "(", "e_options", ")", ")", ")", "fd", ".", "write", "(", "'}\\n'", ")" ]
Generate a graphviz dot graph from the classes that were passed in to __init__. *fd* is a Python file-like object to write to. *name* is the name of the graph *urls* is a dictionary mapping class names to http urls *graph_options*, *node_options*, *edge_options* are dictionaries containing key/value pairs to pass on as graphviz properties.
[ "Generate", "a", "graphviz", "dot", "graph", "from", "the", "classes", "that", "were", "passed", "in", "to", "__init__", "." ]
train
https://github.com/matthias-k/cyipopt/blob/ed03f54de2e0b8c8ba4c0aa18ab9ab6c8846bc19/doc/source/sphinxext/inheritance_diagram.py#L199-L249
matthias-k/cyipopt
doc/source/sphinxext/inheritance_diagram.py
InheritanceGraph.run_dot
def run_dot(self, args, name, parts=0, urls={}, graph_options={}, node_options={}, edge_options={}): """ Run graphviz 'dot' over this graph, returning whatever 'dot' writes to stdout. *args* will be passed along as commandline arguments. *name* is the name of the graph *urls* is a dictionary mapping class names to http urls Raises DotException for any of the many os and installation-related errors that may occur. """ try: dot = subprocess.Popen(['dot'] + list(args), stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True) except OSError: raise DotException("Could not execute 'dot'. Are you sure you have 'graphviz' installed?") except ValueError: raise DotException("'dot' called with invalid arguments") except: raise DotException("Unexpected error calling 'dot'") self.generate_dot(dot.stdin, name, parts, urls, graph_options, node_options, edge_options) dot.stdin.close() result = dot.stdout.read() returncode = dot.wait() if returncode != 0: raise DotException("'dot' returned the errorcode %d" % returncode) return result
python
def run_dot(self, args, name, parts=0, urls={}, graph_options={}, node_options={}, edge_options={}): try: dot = subprocess.Popen(['dot'] + list(args), stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True) except OSError: raise DotException("Could not execute 'dot'. Are you sure you have 'graphviz' installed?") except ValueError: raise DotException("'dot' called with invalid arguments") except: raise DotException("Unexpected error calling 'dot'") self.generate_dot(dot.stdin, name, parts, urls, graph_options, node_options, edge_options) dot.stdin.close() result = dot.stdout.read() returncode = dot.wait() if returncode != 0: raise DotException("'dot' returned the errorcode %d" % returncode) return result
[ "def", "run_dot", "(", "self", ",", "args", ",", "name", ",", "parts", "=", "0", ",", "urls", "=", "{", "}", ",", "graph_options", "=", "{", "}", ",", "node_options", "=", "{", "}", ",", "edge_options", "=", "{", "}", ")", ":", "try", ":", "dot", "=", "subprocess", ".", "Popen", "(", "[", "'dot'", "]", "+", "list", "(", "args", ")", ",", "stdin", "=", "subprocess", ".", "PIPE", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "close_fds", "=", "True", ")", "except", "OSError", ":", "raise", "DotException", "(", "\"Could not execute 'dot'. Are you sure you have 'graphviz' installed?\"", ")", "except", "ValueError", ":", "raise", "DotException", "(", "\"'dot' called with invalid arguments\"", ")", "except", ":", "raise", "DotException", "(", "\"Unexpected error calling 'dot'\"", ")", "self", ".", "generate_dot", "(", "dot", ".", "stdin", ",", "name", ",", "parts", ",", "urls", ",", "graph_options", ",", "node_options", ",", "edge_options", ")", "dot", ".", "stdin", ".", "close", "(", ")", "result", "=", "dot", ".", "stdout", ".", "read", "(", ")", "returncode", "=", "dot", ".", "wait", "(", ")", "if", "returncode", "!=", "0", ":", "raise", "DotException", "(", "\"'dot' returned the errorcode %d\"", "%", "returncode", ")", "return", "result" ]
Run graphviz 'dot' over this graph, returning whatever 'dot' writes to stdout. *args* will be passed along as commandline arguments. *name* is the name of the graph *urls* is a dictionary mapping class names to http urls Raises DotException for any of the many os and installation-related errors that may occur.
[ "Run", "graphviz", "dot", "over", "this", "graph", "returning", "whatever", "dot", "writes", "to", "stdout", "." ]
train
https://github.com/matthias-k/cyipopt/blob/ed03f54de2e0b8c8ba4c0aa18ab9ab6c8846bc19/doc/source/sphinxext/inheritance_diagram.py#L251-L284
matthias-k/cyipopt
ipopt/ipopt_wrapper.py
minimize_ipopt
def minimize_ipopt(fun, x0, args=(), kwargs=None, method=None, jac=None, hess=None, hessp=None, bounds=None, constraints=(), tol=None, callback=None, options=None): """ Minimize a function using ipopt. The call signature is exactly like for `scipy.optimize.mimize`. In options, all options are directly passed to ipopt. Check [http://www.coin-or.org/Ipopt/documentation/node39.html] for details. The options `disp` and `maxiter` are automatically mapped to their ipopt-equivalents `print_level` and `max_iter`. """ if not SCIPY_INSTALLED: raise ImportError('Install SciPy to use the `minimize_ipopt` function.') _x0 = np.atleast_1d(x0) problem = IpoptProblemWrapper(fun, args=args, kwargs=kwargs, jac=jac, hess=hess, hessp=hessp, constraints=constraints) lb, ub = get_bounds(bounds) cl, cu = get_constraint_bounds(constraints, x0) if options is None: options = {} nlp = cyipopt.problem(n = len(_x0), m = len(cl), problem_obj=problem, lb=lb, ub=ub, cl=cl, cu=cu) # python3 compatibility convert_to_bytes(options) # Rename some default scipy options replace_option(options, b'disp', b'print_level') replace_option(options, b'maxiter', b'max_iter') if b'print_level' not in options: options[b'print_level'] = 0 if b'tol' not in options: options[b'tol'] = tol or 1e-8 if b'mu_strategy' not in options: options[b'mu_strategy'] = b'adaptive' if b'hessian_approximation' not in options: if hess is None and hessp is None: options[b'hessian_approximation'] = b'limited-memory' for option, value in options.items(): try: nlp.addOption(option, value) except TypeError as e: raise TypeError('Invalid option for IPOPT: {0}: {1} (Original message: "{2}")'.format(option, value, e)) x, info = nlp.solve(_x0) if np.asarray(x0).shape == (): x = x[0] return OptimizeResult(x=x, success=info['status'] == 0, status=info['status'], message=info['status_msg'], fun=info['obj_val'], info=info, nfev=problem.nfev, njev=problem.njev, nit=problem.nit)
python
def minimize_ipopt(fun, x0, args=(), kwargs=None, method=None, jac=None, hess=None, hessp=None, bounds=None, constraints=(), tol=None, callback=None, options=None): if not SCIPY_INSTALLED: raise ImportError('Install SciPy to use the `minimize_ipopt` function.') _x0 = np.atleast_1d(x0) problem = IpoptProblemWrapper(fun, args=args, kwargs=kwargs, jac=jac, hess=hess, hessp=hessp, constraints=constraints) lb, ub = get_bounds(bounds) cl, cu = get_constraint_bounds(constraints, x0) if options is None: options = {} nlp = cyipopt.problem(n = len(_x0), m = len(cl), problem_obj=problem, lb=lb, ub=ub, cl=cl, cu=cu) convert_to_bytes(options) replace_option(options, b'disp', b'print_level') replace_option(options, b'maxiter', b'max_iter') if b'print_level' not in options: options[b'print_level'] = 0 if b'tol' not in options: options[b'tol'] = tol or 1e-8 if b'mu_strategy' not in options: options[b'mu_strategy'] = b'adaptive' if b'hessian_approximation' not in options: if hess is None and hessp is None: options[b'hessian_approximation'] = b'limited-memory' for option, value in options.items(): try: nlp.addOption(option, value) except TypeError as e: raise TypeError('Invalid option for IPOPT: {0}: {1} (Original message: "{2}")'.format(option, value, e)) x, info = nlp.solve(_x0) if np.asarray(x0).shape == (): x = x[0] return OptimizeResult(x=x, success=info['status'] == 0, status=info['status'], message=info['status_msg'], fun=info['obj_val'], info=info, nfev=problem.nfev, njev=problem.njev, nit=problem.nit)
[ "def", "minimize_ipopt", "(", "fun", ",", "x0", ",", "args", "=", "(", ")", ",", "kwargs", "=", "None", ",", "method", "=", "None", ",", "jac", "=", "None", ",", "hess", "=", "None", ",", "hessp", "=", "None", ",", "bounds", "=", "None", ",", "constraints", "=", "(", ")", ",", "tol", "=", "None", ",", "callback", "=", "None", ",", "options", "=", "None", ")", ":", "if", "not", "SCIPY_INSTALLED", ":", "raise", "ImportError", "(", "'Install SciPy to use the `minimize_ipopt` function.'", ")", "_x0", "=", "np", ".", "atleast_1d", "(", "x0", ")", "problem", "=", "IpoptProblemWrapper", "(", "fun", ",", "args", "=", "args", ",", "kwargs", "=", "kwargs", ",", "jac", "=", "jac", ",", "hess", "=", "hess", ",", "hessp", "=", "hessp", ",", "constraints", "=", "constraints", ")", "lb", ",", "ub", "=", "get_bounds", "(", "bounds", ")", "cl", ",", "cu", "=", "get_constraint_bounds", "(", "constraints", ",", "x0", ")", "if", "options", "is", "None", ":", "options", "=", "{", "}", "nlp", "=", "cyipopt", ".", "problem", "(", "n", "=", "len", "(", "_x0", ")", ",", "m", "=", "len", "(", "cl", ")", ",", "problem_obj", "=", "problem", ",", "lb", "=", "lb", ",", "ub", "=", "ub", ",", "cl", "=", "cl", ",", "cu", "=", "cu", ")", "# python3 compatibility", "convert_to_bytes", "(", "options", ")", "# Rename some default scipy options", "replace_option", "(", "options", ",", "b'disp'", ",", "b'print_level'", ")", "replace_option", "(", "options", ",", "b'maxiter'", ",", "b'max_iter'", ")", "if", "b'print_level'", "not", "in", "options", ":", "options", "[", "b'print_level'", "]", "=", "0", "if", "b'tol'", "not", "in", "options", ":", "options", "[", "b'tol'", "]", "=", "tol", "or", "1e-8", "if", "b'mu_strategy'", "not", "in", "options", ":", "options", "[", "b'mu_strategy'", "]", "=", "b'adaptive'", "if", "b'hessian_approximation'", "not", "in", "options", ":", "if", "hess", "is", "None", "and", "hessp", "is", "None", ":", "options", "[", "b'hessian_approximation'", "]", "=", "b'limited-memory'", "for", "option", ",", "value", "in", "options", ".", "items", "(", ")", ":", "try", ":", "nlp", ".", "addOption", "(", "option", ",", "value", ")", "except", "TypeError", "as", "e", ":", "raise", "TypeError", "(", "'Invalid option for IPOPT: {0}: {1} (Original message: \"{2}\")'", ".", "format", "(", "option", ",", "value", ",", "e", ")", ")", "x", ",", "info", "=", "nlp", ".", "solve", "(", "_x0", ")", "if", "np", ".", "asarray", "(", "x0", ")", ".", "shape", "==", "(", ")", ":", "x", "=", "x", "[", "0", "]", "return", "OptimizeResult", "(", "x", "=", "x", ",", "success", "=", "info", "[", "'status'", "]", "==", "0", ",", "status", "=", "info", "[", "'status'", "]", ",", "message", "=", "info", "[", "'status_msg'", "]", ",", "fun", "=", "info", "[", "'obj_val'", "]", ",", "info", "=", "info", ",", "nfev", "=", "problem", ".", "nfev", ",", "njev", "=", "problem", ".", "njev", ",", "nit", "=", "problem", ".", "nit", ")" ]
Minimize a function using ipopt. The call signature is exactly like for `scipy.optimize.mimize`. In options, all options are directly passed to ipopt. Check [http://www.coin-or.org/Ipopt/documentation/node39.html] for details. The options `disp` and `maxiter` are automatically mapped to their ipopt-equivalents `print_level` and `max_iter`.
[ "Minimize", "a", "function", "using", "ipopt", ".", "The", "call", "signature", "is", "exactly", "like", "for", "scipy", ".", "optimize", ".", "mimize", ".", "In", "options", "all", "options", "are", "directly", "passed", "to", "ipopt", ".", "Check", "[", "http", ":", "//", "www", ".", "coin", "-", "or", ".", "org", "/", "Ipopt", "/", "documentation", "/", "node39", ".", "html", "]", "for", "details", ".", "The", "options", "disp", "and", "maxiter", "are", "automatically", "mapped", "to", "their", "ipopt", "-", "equivalents", "print_level", "and", "max_iter", "." ]
train
https://github.com/matthias-k/cyipopt/blob/ed03f54de2e0b8c8ba4c0aa18ab9ab6c8846bc19/ipopt/ipopt_wrapper.py#L175-L238
schapman1974/tinymongo
setup.py
parse_md_to_rst
def parse_md_to_rst(file): """Read Markdown file and convert to ReStructured Text.""" try: from m2r import parse_from_file return parse_from_file(file).replace( "artwork/", "http://198.27.119.65/" ) except ImportError: # m2r may not be installed in user environment return read(file)
python
def parse_md_to_rst(file): try: from m2r import parse_from_file return parse_from_file(file).replace( "artwork/", "http://198.27.119.65/" ) except ImportError: return read(file)
[ "def", "parse_md_to_rst", "(", "file", ")", ":", "try", ":", "from", "m2r", "import", "parse_from_file", "return", "parse_from_file", "(", "file", ")", ".", "replace", "(", "\"artwork/\"", ",", "\"http://198.27.119.65/\"", ")", "except", "ImportError", ":", "# m2r may not be installed in user environment", "return", "read", "(", "file", ")" ]
Read Markdown file and convert to ReStructured Text.
[ "Read", "Markdown", "file", "and", "convert", "to", "ReStructured", "Text", "." ]
train
https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/setup.py#L14-L23
schapman1974/tinymongo
tinymongo/results.py
DeleteResult.deleted_count
def deleted_count(self): """The number of documents deleted.""" if isinstance(self.raw_result, list): return len(self.raw_result) else: return self.raw_result
python
def deleted_count(self): if isinstance(self.raw_result, list): return len(self.raw_result) else: return self.raw_result
[ "def", "deleted_count", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "raw_result", ",", "list", ")", ":", "return", "len", "(", "self", ".", "raw_result", ")", "else", ":", "return", "self", ".", "raw_result" ]
The number of documents deleted.
[ "The", "number", "of", "documents", "deleted", "." ]
train
https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/tinymongo/results.py#L107-L112
schapman1974/tinymongo
tinymongo/tinymongo.py
generate_id
def generate_id(): """Generate new UUID""" # TODO: Use six.string_type to Py3 compat try: return unicode(uuid1()).replace(u"-", u"") except NameError: return str(uuid1()).replace(u"-", u"")
python
def generate_id(): try: return unicode(uuid1()).replace(u"-", u"") except NameError: return str(uuid1()).replace(u"-", u"")
[ "def", "generate_id", "(", ")", ":", "# TODO: Use six.string_type to Py3 compat", "try", ":", "return", "unicode", "(", "uuid1", "(", ")", ")", ".", "replace", "(", "u\"-\"", ",", "u\"\"", ")", "except", "NameError", ":", "return", "str", "(", "uuid1", "(", ")", ")", ".", "replace", "(", "u\"-\"", ",", "u\"\"", ")" ]
Generate new UUID
[ "Generate", "new", "UUID" ]
train
https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/tinymongo/tinymongo.py#L806-L812
schapman1974/tinymongo
tinymongo/tinymongo.py
TinyMongoCollection.build_table
def build_table(self): """ Builds a new tinydb table at the parent database :return: """ self.table = self.parent.tinydb.table(self.tablename)
python
def build_table(self): self.table = self.parent.tinydb.table(self.tablename)
[ "def", "build_table", "(", "self", ")", ":", "self", ".", "table", "=", "self", ".", "parent", ".", "tinydb", ".", "table", "(", "self", ".", "tablename", ")" ]
Builds a new tinydb table at the parent database :return:
[ "Builds", "a", "new", "tinydb", "table", "at", "the", "parent", "database", ":", "return", ":" ]
train
https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/tinymongo/tinymongo.py#L143-L148
schapman1974/tinymongo
tinymongo/tinymongo.py
TinyMongoCollection.drop
def drop(self, **kwargs): """ Removes a collection from the database. **kwargs only because of the optional "writeConcern" field, but does nothing in the TinyDB database. :return: Returns True when successfully drops a collection. Returns False when collection to drop does not exist. """ if self.table: self.parent.tinydb.purge_table(self.tablename) return True else: return False
python
def drop(self, **kwargs): if self.table: self.parent.tinydb.purge_table(self.tablename) return True else: return False
[ "def", "drop", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "table", ":", "self", ".", "parent", ".", "tinydb", ".", "purge_table", "(", "self", ".", "tablename", ")", "return", "True", "else", ":", "return", "False" ]
Removes a collection from the database. **kwargs only because of the optional "writeConcern" field, but does nothing in the TinyDB database. :return: Returns True when successfully drops a collection. Returns False when collection to drop does not exist.
[ "Removes", "a", "collection", "from", "the", "database", ".", "**", "kwargs", "only", "because", "of", "the", "optional", "writeConcern", "field", "but", "does", "nothing", "in", "the", "TinyDB", "database", ".", ":", "return", ":", "Returns", "True", "when", "successfully", "drops", "a", "collection", ".", "Returns", "False", "when", "collection", "to", "drop", "does", "not", "exist", "." ]
train
https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/tinymongo/tinymongo.py#L157-L168
schapman1974/tinymongo
tinymongo/tinymongo.py
TinyMongoCollection.insert
def insert(self, docs, *args, **kwargs): """Backwards compatibility with insert""" if isinstance(docs, list): return self.insert_many(docs, *args, **kwargs) else: return self.insert_one(docs, *args, **kwargs)
python
def insert(self, docs, *args, **kwargs): if isinstance(docs, list): return self.insert_many(docs, *args, **kwargs) else: return self.insert_one(docs, *args, **kwargs)
[ "def", "insert", "(", "self", ",", "docs", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "docs", ",", "list", ")", ":", "return", "self", ".", "insert_many", "(", "docs", ",", "*", "args", ",", "*", "*", "kwargs", ")", "else", ":", "return", "self", ".", "insert_one", "(", "docs", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Backwards compatibility with insert
[ "Backwards", "compatibility", "with", "insert" ]
train
https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/tinymongo/tinymongo.py#L170-L175
schapman1974/tinymongo
tinymongo/tinymongo.py
TinyMongoCollection.insert_one
def insert_one(self, doc, *args, **kwargs): """ Inserts one document into the collection If contains '_id' key it is used, else it is generated. :param doc: the document :return: InsertOneResult """ if self.table is None: self.build_table() if not isinstance(doc, dict): raise ValueError(u'"doc" must be a dict') _id = doc[u'_id'] = doc.get('_id') or generate_id() bypass_document_validation = kwargs.get('bypass_document_validation') if bypass_document_validation is True: # insert doc without validation of duplicated `_id` eid = self.table.insert(doc) else: existing = self.find_one({'_id': _id}) if existing is None: eid = self.table.insert(doc) else: raise DuplicateKeyError( u'_id:{0} already exists in collection:{1}'.format( _id, self.tablename ) ) return InsertOneResult(eid=eid, inserted_id=_id)
python
def insert_one(self, doc, *args, **kwargs): if self.table is None: self.build_table() if not isinstance(doc, dict): raise ValueError(u'"doc" must be a dict') _id = doc[u'_id'] = doc.get('_id') or generate_id() bypass_document_validation = kwargs.get('bypass_document_validation') if bypass_document_validation is True: eid = self.table.insert(doc) else: existing = self.find_one({'_id': _id}) if existing is None: eid = self.table.insert(doc) else: raise DuplicateKeyError( u'_id:{0} already exists in collection:{1}'.format( _id, self.tablename ) ) return InsertOneResult(eid=eid, inserted_id=_id)
[ "def", "insert_one", "(", "self", ",", "doc", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "table", "is", "None", ":", "self", ".", "build_table", "(", ")", "if", "not", "isinstance", "(", "doc", ",", "dict", ")", ":", "raise", "ValueError", "(", "u'\"doc\" must be a dict'", ")", "_id", "=", "doc", "[", "u'_id'", "]", "=", "doc", ".", "get", "(", "'_id'", ")", "or", "generate_id", "(", ")", "bypass_document_validation", "=", "kwargs", ".", "get", "(", "'bypass_document_validation'", ")", "if", "bypass_document_validation", "is", "True", ":", "# insert doc without validation of duplicated `_id`", "eid", "=", "self", ".", "table", ".", "insert", "(", "doc", ")", "else", ":", "existing", "=", "self", ".", "find_one", "(", "{", "'_id'", ":", "_id", "}", ")", "if", "existing", "is", "None", ":", "eid", "=", "self", ".", "table", ".", "insert", "(", "doc", ")", "else", ":", "raise", "DuplicateKeyError", "(", "u'_id:{0} already exists in collection:{1}'", ".", "format", "(", "_id", ",", "self", ".", "tablename", ")", ")", "return", "InsertOneResult", "(", "eid", "=", "eid", ",", "inserted_id", "=", "_id", ")" ]
Inserts one document into the collection If contains '_id' key it is used, else it is generated. :param doc: the document :return: InsertOneResult
[ "Inserts", "one", "document", "into", "the", "collection", "If", "contains", "_id", "key", "it", "is", "used", "else", "it", "is", "generated", ".", ":", "param", "doc", ":", "the", "document", ":", "return", ":", "InsertOneResult" ]
train
https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/tinymongo/tinymongo.py#L177-L207
schapman1974/tinymongo
tinymongo/tinymongo.py
TinyMongoCollection.insert_many
def insert_many(self, docs, *args, **kwargs): """ Inserts several documents into the collection :param docs: a list of documents :return: InsertManyResult """ if self.table is None: self.build_table() if not isinstance(docs, list): raise ValueError(u'"insert_many" requires a list input') bypass_document_validation = kwargs.get('bypass_document_validation') if bypass_document_validation is not True: # get all _id in once, to reduce I/O. (without projection) existing = [doc['_id'] for doc in self.find({})] _ids = list() for doc in docs: _id = doc[u'_id'] = doc.get('_id') or generate_id() if bypass_document_validation is not True: if _id in existing: raise DuplicateKeyError( u'_id:{0} already exists in collection:{1}'.format( _id, self.tablename ) ) existing.append(_id) _ids.append(_id) results = self.table.insert_multiple(docs) return InsertManyResult( eids=[eid for eid in results], inserted_ids=[inserted_id for inserted_id in _ids] )
python
def insert_many(self, docs, *args, **kwargs): if self.table is None: self.build_table() if not isinstance(docs, list): raise ValueError(u'"insert_many" requires a list input') bypass_document_validation = kwargs.get('bypass_document_validation') if bypass_document_validation is not True: existing = [doc['_id'] for doc in self.find({})] _ids = list() for doc in docs: _id = doc[u'_id'] = doc.get('_id') or generate_id() if bypass_document_validation is not True: if _id in existing: raise DuplicateKeyError( u'_id:{0} already exists in collection:{1}'.format( _id, self.tablename ) ) existing.append(_id) _ids.append(_id) results = self.table.insert_multiple(docs) return InsertManyResult( eids=[eid for eid in results], inserted_ids=[inserted_id for inserted_id in _ids] )
[ "def", "insert_many", "(", "self", ",", "docs", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "table", "is", "None", ":", "self", ".", "build_table", "(", ")", "if", "not", "isinstance", "(", "docs", ",", "list", ")", ":", "raise", "ValueError", "(", "u'\"insert_many\" requires a list input'", ")", "bypass_document_validation", "=", "kwargs", ".", "get", "(", "'bypass_document_validation'", ")", "if", "bypass_document_validation", "is", "not", "True", ":", "# get all _id in once, to reduce I/O. (without projection)", "existing", "=", "[", "doc", "[", "'_id'", "]", "for", "doc", "in", "self", ".", "find", "(", "{", "}", ")", "]", "_ids", "=", "list", "(", ")", "for", "doc", "in", "docs", ":", "_id", "=", "doc", "[", "u'_id'", "]", "=", "doc", ".", "get", "(", "'_id'", ")", "or", "generate_id", "(", ")", "if", "bypass_document_validation", "is", "not", "True", ":", "if", "_id", "in", "existing", ":", "raise", "DuplicateKeyError", "(", "u'_id:{0} already exists in collection:{1}'", ".", "format", "(", "_id", ",", "self", ".", "tablename", ")", ")", "existing", ".", "append", "(", "_id", ")", "_ids", ".", "append", "(", "_id", ")", "results", "=", "self", ".", "table", ".", "insert_multiple", "(", "docs", ")", "return", "InsertManyResult", "(", "eids", "=", "[", "eid", "for", "eid", "in", "results", "]", ",", "inserted_ids", "=", "[", "inserted_id", "for", "inserted_id", "in", "_ids", "]", ")" ]
Inserts several documents into the collection :param docs: a list of documents :return: InsertManyResult
[ "Inserts", "several", "documents", "into", "the", "collection", ":", "param", "docs", ":", "a", "list", "of", "documents", ":", "return", ":", "InsertManyResult" ]
train
https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/tinymongo/tinymongo.py#L209-L248
schapman1974/tinymongo
tinymongo/tinymongo.py
TinyMongoCollection.parse_query
def parse_query(self, query): """ Creates a tinydb Query() object from the query dict :param query: object containing the dictionary representation of the query :return: composite Query() """ logger.debug(u'query to parse2: {}'.format(query)) # this should find all records if query == {} or query is None: return Query()._id != u'-1' # noqa q = None # find the final result of the generator for c in self.parse_condition(query): if q is None: q = c else: q = q & c logger.debug(u'new query item2: {}'.format(q)) return q
python
def parse_query(self, query): logger.debug(u'query to parse2: {}'.format(query)) if query == {} or query is None: return Query()._id != u'-1' q = None for c in self.parse_condition(query): if q is None: q = c else: q = q & c logger.debug(u'new query item2: {}'.format(q)) return q
[ "def", "parse_query", "(", "self", ",", "query", ")", ":", "logger", ".", "debug", "(", "u'query to parse2: {}'", ".", "format", "(", "query", ")", ")", "# this should find all records", "if", "query", "==", "{", "}", "or", "query", "is", "None", ":", "return", "Query", "(", ")", ".", "_id", "!=", "u'-1'", "# noqa", "q", "=", "None", "# find the final result of the generator", "for", "c", "in", "self", ".", "parse_condition", "(", "query", ")", ":", "if", "q", "is", "None", ":", "q", "=", "c", "else", ":", "q", "=", "q", "&", "c", "logger", ".", "debug", "(", "u'new query item2: {}'", ".", "format", "(", "q", ")", ")", "return", "q" ]
Creates a tinydb Query() object from the query dict :param query: object containing the dictionary representation of the query :return: composite Query()
[ "Creates", "a", "tinydb", "Query", "()", "object", "from", "the", "query", "dict" ]
train
https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/tinymongo/tinymongo.py#L250-L274
schapman1974/tinymongo
tinymongo/tinymongo.py
TinyMongoCollection.parse_condition
def parse_condition(self, query, prev_key=None, last_prev_key=None): """ Creates a recursive generator for parsing some types of Query() conditions :param query: Query object :param prev_key: The key at the next-higher level :return: generator object, the last of which will be the complete Query() object containing all conditions """ # use this to determine gt/lt/eq on prev_query logger.debug(u'query: {} prev_query: {}'.format(query, prev_key)) q = Query() conditions = None # deal with the {'name': value} case by injecting a previous key if not prev_key: temp_query = copy.deepcopy(query) k, v = temp_query.popitem() prev_key = k # deal with the conditions for key, value in query.items(): logger.debug(u'conditions: {} {}'.format(key, value)) if key == u'$gte': conditions = ( Q(q, prev_key) >= value ) if not conditions and prev_key != "$not" \ else (conditions & (Q(q, prev_key) >= value)) if prev_key != "$not" \ else (q[last_prev_key] < value) elif key == u'$gt': conditions = ( Q(q, prev_key) > value ) if not conditions and prev_key != "$not" \ else (conditions & (Q(q, prev_key) > value)) if prev_key != "$not" \ else (q[last_prev_key] <= value) elif key == u'$lte': conditions = ( Q(q, prev_key) <= value ) if not conditions and prev_key != "$not" \ else (conditions & (Q(q, prev_key) <= value)) if prev_key != "$not" \ else (q[last_prev_key] > value) elif key == u'$lt': conditions = ( Q(q, prev_key) < value ) if not conditions and prev_key != "$not" \ else (conditions & (Q(q, prev_key) < value)) if prev_key != "$not" \ else (q[last_prev_key] >= value) elif key == u'$ne': conditions = ( Q(q, prev_key) != value ) if not conditions and prev_key != "$not" \ else (conditions & (Q(q, prev_key) != value))if prev_key != "$not" \ else (q[last_prev_key] == value) elif key == u'$not': if not isinstance(value, dict) and not isinstance(value, list): conditions = ( Q(q, prev_key) != value ) if not conditions and prev_key != "$not" \ else (conditions & (Q(q, prev_key) != value)) \ if prev_key != "$not" else (q[last_prev_key] >= value) else: # let the value's condition be parsed below pass elif key == u'$regex': value = value.replace('\\\\\\', '|||') value = value.replace('\\\\', '|||') regex = value.replace('\\', '') regex = regex.replace('|||', '\\') currCond = (where(prev_key).matches(regex)) conditions = currCond if not conditions else (conditions & currCond) elif key in ['$and', '$or', '$in', '$all']: pass else: # don't want to use the previous key if this is a secondary key # (fixes multiple item query that includes $ codes) if not isinstance(value, dict) and not isinstance(value, list): conditions = ( (Q(q, key) == value) | (Q(q, key).any([value])) ) if not conditions else (conditions & ((Q(q, key) == value) | (Q(q, key).any([value])))) prev_key = key logger.debug(u'c: {}'.format(conditions)) if isinstance(value, dict): # yield from self.parse_condition(value, key) for parse_condition in self.parse_condition(value, key, prev_key): yield parse_condition elif isinstance(value, list): if key == '$and': grouped_conditions = None for spec in value: for parse_condition in self.parse_condition(spec): grouped_conditions = ( parse_condition if not grouped_conditions else grouped_conditions & parse_condition ) yield grouped_conditions elif key == '$or': grouped_conditions = None for spec in value: for parse_condition in self.parse_condition(spec): grouped_conditions = ( parse_condition if not grouped_conditions else grouped_conditions | parse_condition ) yield grouped_conditions elif key == '$in': # use `any` to find with list, before comparing to single string grouped_conditions = Q(q, prev_key).any(value) for val in value: for parse_condition in self.parse_condition({prev_key : val}): grouped_conditions = ( parse_condition if not grouped_conditions else grouped_conditions | parse_condition ) yield grouped_conditions elif key == '$all': yield Q(q, prev_key).all(value) else: yield Q(q, prev_key).any([value]) else: yield conditions
python
def parse_condition(self, query, prev_key=None, last_prev_key=None): logger.debug(u'query: {} prev_query: {}'.format(query, prev_key)) q = Query() conditions = None if not prev_key: temp_query = copy.deepcopy(query) k, v = temp_query.popitem() prev_key = k for key, value in query.items(): logger.debug(u'conditions: {} {}'.format(key, value)) if key == u'$gte': conditions = ( Q(q, prev_key) >= value ) if not conditions and prev_key != "$not" \ else (conditions & (Q(q, prev_key) >= value)) if prev_key != "$not" \ else (q[last_prev_key] < value) elif key == u'$gt': conditions = ( Q(q, prev_key) > value ) if not conditions and prev_key != "$not" \ else (conditions & (Q(q, prev_key) > value)) if prev_key != "$not" \ else (q[last_prev_key] <= value) elif key == u'$lte': conditions = ( Q(q, prev_key) <= value ) if not conditions and prev_key != "$not" \ else (conditions & (Q(q, prev_key) <= value)) if prev_key != "$not" \ else (q[last_prev_key] > value) elif key == u'$lt': conditions = ( Q(q, prev_key) < value ) if not conditions and prev_key != "$not" \ else (conditions & (Q(q, prev_key) < value)) if prev_key != "$not" \ else (q[last_prev_key] >= value) elif key == u'$ne': conditions = ( Q(q, prev_key) != value ) if not conditions and prev_key != "$not" \ else (conditions & (Q(q, prev_key) != value))if prev_key != "$not" \ else (q[last_prev_key] == value) elif key == u'$not': if not isinstance(value, dict) and not isinstance(value, list): conditions = ( Q(q, prev_key) != value ) if not conditions and prev_key != "$not" \ else (conditions & (Q(q, prev_key) != value)) \ if prev_key != "$not" else (q[last_prev_key] >= value) else: pass elif key == u'$regex': value = value.replace('\\\\\\', '|||') value = value.replace('\\\\', '|||') regex = value.replace('\\', '') regex = regex.replace('|||', '\\') currCond = (where(prev_key).matches(regex)) conditions = currCond if not conditions else (conditions & currCond) elif key in ['$and', '$or', '$in', '$all']: pass else: if not isinstance(value, dict) and not isinstance(value, list): conditions = ( (Q(q, key) == value) | (Q(q, key).any([value])) ) if not conditions else (conditions & ((Q(q, key) == value) | (Q(q, key).any([value])))) prev_key = key logger.debug(u'c: {}'.format(conditions)) if isinstance(value, dict): for parse_condition in self.parse_condition(value, key, prev_key): yield parse_condition elif isinstance(value, list): if key == '$and': grouped_conditions = None for spec in value: for parse_condition in self.parse_condition(spec): grouped_conditions = ( parse_condition if not grouped_conditions else grouped_conditions & parse_condition ) yield grouped_conditions elif key == '$or': grouped_conditions = None for spec in value: for parse_condition in self.parse_condition(spec): grouped_conditions = ( parse_condition if not grouped_conditions else grouped_conditions | parse_condition ) yield grouped_conditions elif key == '$in': grouped_conditions = Q(q, prev_key).any(value) for val in value: for parse_condition in self.parse_condition({prev_key : val}): grouped_conditions = ( parse_condition if not grouped_conditions else grouped_conditions | parse_condition ) yield grouped_conditions elif key == '$all': yield Q(q, prev_key).all(value) else: yield Q(q, prev_key).any([value]) else: yield conditions
[ "def", "parse_condition", "(", "self", ",", "query", ",", "prev_key", "=", "None", ",", "last_prev_key", "=", "None", ")", ":", "# use this to determine gt/lt/eq on prev_query", "logger", ".", "debug", "(", "u'query: {} prev_query: {}'", ".", "format", "(", "query", ",", "prev_key", ")", ")", "q", "=", "Query", "(", ")", "conditions", "=", "None", "# deal with the {'name': value} case by injecting a previous key", "if", "not", "prev_key", ":", "temp_query", "=", "copy", ".", "deepcopy", "(", "query", ")", "k", ",", "v", "=", "temp_query", ".", "popitem", "(", ")", "prev_key", "=", "k", "# deal with the conditions", "for", "key", ",", "value", "in", "query", ".", "items", "(", ")", ":", "logger", ".", "debug", "(", "u'conditions: {} {}'", ".", "format", "(", "key", ",", "value", ")", ")", "if", "key", "==", "u'$gte'", ":", "conditions", "=", "(", "Q", "(", "q", ",", "prev_key", ")", ">=", "value", ")", "if", "not", "conditions", "and", "prev_key", "!=", "\"$not\"", "else", "(", "conditions", "&", "(", "Q", "(", "q", ",", "prev_key", ")", ">=", "value", ")", ")", "if", "prev_key", "!=", "\"$not\"", "else", "(", "q", "[", "last_prev_key", "]", "<", "value", ")", "elif", "key", "==", "u'$gt'", ":", "conditions", "=", "(", "Q", "(", "q", ",", "prev_key", ")", ">", "value", ")", "if", "not", "conditions", "and", "prev_key", "!=", "\"$not\"", "else", "(", "conditions", "&", "(", "Q", "(", "q", ",", "prev_key", ")", ">", "value", ")", ")", "if", "prev_key", "!=", "\"$not\"", "else", "(", "q", "[", "last_prev_key", "]", "<=", "value", ")", "elif", "key", "==", "u'$lte'", ":", "conditions", "=", "(", "Q", "(", "q", ",", "prev_key", ")", "<=", "value", ")", "if", "not", "conditions", "and", "prev_key", "!=", "\"$not\"", "else", "(", "conditions", "&", "(", "Q", "(", "q", ",", "prev_key", ")", "<=", "value", ")", ")", "if", "prev_key", "!=", "\"$not\"", "else", "(", "q", "[", "last_prev_key", "]", ">", "value", ")", "elif", "key", "==", "u'$lt'", ":", "conditions", "=", "(", "Q", "(", "q", ",", "prev_key", ")", "<", "value", ")", "if", "not", "conditions", "and", "prev_key", "!=", "\"$not\"", "else", "(", "conditions", "&", "(", "Q", "(", "q", ",", "prev_key", ")", "<", "value", ")", ")", "if", "prev_key", "!=", "\"$not\"", "else", "(", "q", "[", "last_prev_key", "]", ">=", "value", ")", "elif", "key", "==", "u'$ne'", ":", "conditions", "=", "(", "Q", "(", "q", ",", "prev_key", ")", "!=", "value", ")", "if", "not", "conditions", "and", "prev_key", "!=", "\"$not\"", "else", "(", "conditions", "&", "(", "Q", "(", "q", ",", "prev_key", ")", "!=", "value", ")", ")", "if", "prev_key", "!=", "\"$not\"", "else", "(", "q", "[", "last_prev_key", "]", "==", "value", ")", "elif", "key", "==", "u'$not'", ":", "if", "not", "isinstance", "(", "value", ",", "dict", ")", "and", "not", "isinstance", "(", "value", ",", "list", ")", ":", "conditions", "=", "(", "Q", "(", "q", ",", "prev_key", ")", "!=", "value", ")", "if", "not", "conditions", "and", "prev_key", "!=", "\"$not\"", "else", "(", "conditions", "&", "(", "Q", "(", "q", ",", "prev_key", ")", "!=", "value", ")", ")", "if", "prev_key", "!=", "\"$not\"", "else", "(", "q", "[", "last_prev_key", "]", ">=", "value", ")", "else", ":", "# let the value's condition be parsed below", "pass", "elif", "key", "==", "u'$regex'", ":", "value", "=", "value", ".", "replace", "(", "'\\\\\\\\\\\\'", ",", "'|||'", ")", "value", "=", "value", ".", "replace", "(", "'\\\\\\\\'", ",", "'|||'", ")", "regex", "=", "value", ".", "replace", "(", "'\\\\'", ",", "''", ")", "regex", "=", "regex", ".", "replace", "(", "'|||'", ",", "'\\\\'", ")", "currCond", "=", "(", "where", "(", "prev_key", ")", ".", "matches", "(", "regex", ")", ")", "conditions", "=", "currCond", "if", "not", "conditions", "else", "(", "conditions", "&", "currCond", ")", "elif", "key", "in", "[", "'$and'", ",", "'$or'", ",", "'$in'", ",", "'$all'", "]", ":", "pass", "else", ":", "# don't want to use the previous key if this is a secondary key", "# (fixes multiple item query that includes $ codes)", "if", "not", "isinstance", "(", "value", ",", "dict", ")", "and", "not", "isinstance", "(", "value", ",", "list", ")", ":", "conditions", "=", "(", "(", "Q", "(", "q", ",", "key", ")", "==", "value", ")", "|", "(", "Q", "(", "q", ",", "key", ")", ".", "any", "(", "[", "value", "]", ")", ")", ")", "if", "not", "conditions", "else", "(", "conditions", "&", "(", "(", "Q", "(", "q", ",", "key", ")", "==", "value", ")", "|", "(", "Q", "(", "q", ",", "key", ")", ".", "any", "(", "[", "value", "]", ")", ")", ")", ")", "prev_key", "=", "key", "logger", ".", "debug", "(", "u'c: {}'", ".", "format", "(", "conditions", ")", ")", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "# yield from self.parse_condition(value, key)", "for", "parse_condition", "in", "self", ".", "parse_condition", "(", "value", ",", "key", ",", "prev_key", ")", ":", "yield", "parse_condition", "elif", "isinstance", "(", "value", ",", "list", ")", ":", "if", "key", "==", "'$and'", ":", "grouped_conditions", "=", "None", "for", "spec", "in", "value", ":", "for", "parse_condition", "in", "self", ".", "parse_condition", "(", "spec", ")", ":", "grouped_conditions", "=", "(", "parse_condition", "if", "not", "grouped_conditions", "else", "grouped_conditions", "&", "parse_condition", ")", "yield", "grouped_conditions", "elif", "key", "==", "'$or'", ":", "grouped_conditions", "=", "None", "for", "spec", "in", "value", ":", "for", "parse_condition", "in", "self", ".", "parse_condition", "(", "spec", ")", ":", "grouped_conditions", "=", "(", "parse_condition", "if", "not", "grouped_conditions", "else", "grouped_conditions", "|", "parse_condition", ")", "yield", "grouped_conditions", "elif", "key", "==", "'$in'", ":", "# use `any` to find with list, before comparing to single string", "grouped_conditions", "=", "Q", "(", "q", ",", "prev_key", ")", ".", "any", "(", "value", ")", "for", "val", "in", "value", ":", "for", "parse_condition", "in", "self", ".", "parse_condition", "(", "{", "prev_key", ":", "val", "}", ")", ":", "grouped_conditions", "=", "(", "parse_condition", "if", "not", "grouped_conditions", "else", "grouped_conditions", "|", "parse_condition", ")", "yield", "grouped_conditions", "elif", "key", "==", "'$all'", ":", "yield", "Q", "(", "q", ",", "prev_key", ")", ".", "all", "(", "value", ")", "else", ":", "yield", "Q", "(", "q", ",", "prev_key", ")", ".", "any", "(", "[", "value", "]", ")", "else", ":", "yield", "conditions" ]
Creates a recursive generator for parsing some types of Query() conditions :param query: Query object :param prev_key: The key at the next-higher level :return: generator object, the last of which will be the complete Query() object containing all conditions
[ "Creates", "a", "recursive", "generator", "for", "parsing", "some", "types", "of", "Query", "()", "conditions" ]
train
https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/tinymongo/tinymongo.py#L276-L404
schapman1974/tinymongo
tinymongo/tinymongo.py
TinyMongoCollection.update
def update(self, query, doc, *args, **kwargs): """BAckwards compatibility with update""" if isinstance(doc, list): return [ self.update_one(query, item, *args, **kwargs) for item in doc ] else: return self.update_one(query, doc, *args, **kwargs)
python
def update(self, query, doc, *args, **kwargs): if isinstance(doc, list): return [ self.update_one(query, item, *args, **kwargs) for item in doc ] else: return self.update_one(query, doc, *args, **kwargs)
[ "def", "update", "(", "self", ",", "query", ",", "doc", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "doc", ",", "list", ")", ":", "return", "[", "self", ".", "update_one", "(", "query", ",", "item", ",", "*", "args", ",", "*", "*", "kwargs", ")", "for", "item", "in", "doc", "]", "else", ":", "return", "self", ".", "update_one", "(", "query", ",", "doc", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
BAckwards compatibility with update
[ "BAckwards", "compatibility", "with", "update" ]
train
https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/tinymongo/tinymongo.py#L406-L414
schapman1974/tinymongo
tinymongo/tinymongo.py
TinyMongoCollection.update_one
def update_one(self, query, doc): """ Updates one element of the collection :param query: dictionary representing the mongo query :param doc: dictionary representing the item to be updated :return: UpdateResult """ if self.table is None: self.build_table() if u"$set" in doc: doc = doc[u"$set"] allcond = self.parse_query(query) try: result = self.table.update(doc, allcond) except: # TODO: check table.update result # check what pymongo does in that case result = None return UpdateResult(raw_result=result)
python
def update_one(self, query, doc): if self.table is None: self.build_table() if u"$set" in doc: doc = doc[u"$set"] allcond = self.parse_query(query) try: result = self.table.update(doc, allcond) except: result = None return UpdateResult(raw_result=result)
[ "def", "update_one", "(", "self", ",", "query", ",", "doc", ")", ":", "if", "self", ".", "table", "is", "None", ":", "self", ".", "build_table", "(", ")", "if", "u\"$set\"", "in", "doc", ":", "doc", "=", "doc", "[", "u\"$set\"", "]", "allcond", "=", "self", ".", "parse_query", "(", "query", ")", "try", ":", "result", "=", "self", ".", "table", ".", "update", "(", "doc", ",", "allcond", ")", "except", ":", "# TODO: check table.update result", "# check what pymongo does in that case", "result", "=", "None", "return", "UpdateResult", "(", "raw_result", "=", "result", ")" ]
Updates one element of the collection :param query: dictionary representing the mongo query :param doc: dictionary representing the item to be updated :return: UpdateResult
[ "Updates", "one", "element", "of", "the", "collection" ]
train
https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/tinymongo/tinymongo.py#L416-L439
schapman1974/tinymongo
tinymongo/tinymongo.py
TinyMongoCollection.find
def find(self, filter=None, sort=None, skip=None, limit=None, *args, **kwargs): """ Finds all matching results :param query: dictionary representing the mongo query :return: cursor containing the search results """ if self.table is None: self.build_table() if filter is None: result = self.table.all() else: allcond = self.parse_query(filter) try: result = self.table.search(allcond) except (AttributeError, TypeError): result = [] result = TinyMongoCursor( result, sort=sort, skip=skip, limit=limit ) return result
python
def find(self, filter=None, sort=None, skip=None, limit=None, *args, **kwargs): if self.table is None: self.build_table() if filter is None: result = self.table.all() else: allcond = self.parse_query(filter) try: result = self.table.search(allcond) except (AttributeError, TypeError): result = [] result = TinyMongoCursor( result, sort=sort, skip=skip, limit=limit ) return result
[ "def", "find", "(", "self", ",", "filter", "=", "None", ",", "sort", "=", "None", ",", "skip", "=", "None", ",", "limit", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "table", "is", "None", ":", "self", ".", "build_table", "(", ")", "if", "filter", "is", "None", ":", "result", "=", "self", ".", "table", ".", "all", "(", ")", "else", ":", "allcond", "=", "self", ".", "parse_query", "(", "filter", ")", "try", ":", "result", "=", "self", ".", "table", ".", "search", "(", "allcond", ")", "except", "(", "AttributeError", ",", "TypeError", ")", ":", "result", "=", "[", "]", "result", "=", "TinyMongoCursor", "(", "result", ",", "sort", "=", "sort", ",", "skip", "=", "skip", ",", "limit", "=", "limit", ")", "return", "result" ]
Finds all matching results :param query: dictionary representing the mongo query :return: cursor containing the search results
[ "Finds", "all", "matching", "results" ]
train
https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/tinymongo/tinymongo.py#L441-L469
schapman1974/tinymongo
tinymongo/tinymongo.py
TinyMongoCollection.find_one
def find_one(self, filter=None): """ Finds one matching query element :param query: dictionary representing the mongo query :return: the resulting document (if found) """ if self.table is None: self.build_table() allcond = self.parse_query(filter) return self.table.get(allcond)
python
def find_one(self, filter=None): if self.table is None: self.build_table() allcond = self.parse_query(filter) return self.table.get(allcond)
[ "def", "find_one", "(", "self", ",", "filter", "=", "None", ")", ":", "if", "self", ".", "table", "is", "None", ":", "self", ".", "build_table", "(", ")", "allcond", "=", "self", ".", "parse_query", "(", "filter", ")", "return", "self", ".", "table", ".", "get", "(", "allcond", ")" ]
Finds one matching query element :param query: dictionary representing the mongo query :return: the resulting document (if found)
[ "Finds", "one", "matching", "query", "element" ]
train
https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/tinymongo/tinymongo.py#L471-L484
schapman1974/tinymongo
tinymongo/tinymongo.py
TinyMongoCollection.remove
def remove(self, spec_or_id, multi=True, *args, **kwargs): """Backwards compatibility with remove""" if multi: return self.delete_many(spec_or_id) return self.delete_one(spec_or_id)
python
def remove(self, spec_or_id, multi=True, *args, **kwargs): if multi: return self.delete_many(spec_or_id) return self.delete_one(spec_or_id)
[ "def", "remove", "(", "self", ",", "spec_or_id", ",", "multi", "=", "True", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "multi", ":", "return", "self", ".", "delete_many", "(", "spec_or_id", ")", "return", "self", ".", "delete_one", "(", "spec_or_id", ")" ]
Backwards compatibility with remove
[ "Backwards", "compatibility", "with", "remove" ]
train
https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/tinymongo/tinymongo.py#L486-L490
schapman1974/tinymongo
tinymongo/tinymongo.py
TinyMongoCollection.delete_one
def delete_one(self, query): """ Deletes one document from the collection :param query: dictionary representing the mongo query :return: DeleteResult """ item = self.find_one(query) result = self.table.remove(where(u'_id') == item[u'_id']) return DeleteResult(raw_result=result)
python
def delete_one(self, query): item = self.find_one(query) result = self.table.remove(where(u'_id') == item[u'_id']) return DeleteResult(raw_result=result)
[ "def", "delete_one", "(", "self", ",", "query", ")", ":", "item", "=", "self", ".", "find_one", "(", "query", ")", "result", "=", "self", ".", "table", ".", "remove", "(", "where", "(", "u'_id'", ")", "==", "item", "[", "u'_id'", "]", ")", "return", "DeleteResult", "(", "raw_result", "=", "result", ")" ]
Deletes one document from the collection :param query: dictionary representing the mongo query :return: DeleteResult
[ "Deletes", "one", "document", "from", "the", "collection" ]
train
https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/tinymongo/tinymongo.py#L492-L502
schapman1974/tinymongo
tinymongo/tinymongo.py
TinyMongoCollection.delete_many
def delete_many(self, query): """ Removes all items matching the mongo query :param query: dictionary representing the mongo query :return: DeleteResult """ items = self.find(query) result = [ self.table.remove(where(u'_id') == item[u'_id']) for item in items ] if query == {}: # need to reset TinyDB's index for docs order consistency self.table._last_id = 0 return DeleteResult(raw_result=result)
python
def delete_many(self, query): items = self.find(query) result = [ self.table.remove(where(u'_id') == item[u'_id']) for item in items ] if query == {}: self.table._last_id = 0 return DeleteResult(raw_result=result)
[ "def", "delete_many", "(", "self", ",", "query", ")", ":", "items", "=", "self", ".", "find", "(", "query", ")", "result", "=", "[", "self", ".", "table", ".", "remove", "(", "where", "(", "u'_id'", ")", "==", "item", "[", "u'_id'", "]", ")", "for", "item", "in", "items", "]", "if", "query", "==", "{", "}", ":", "# need to reset TinyDB's index for docs order consistency", "self", ".", "table", ".", "_last_id", "=", "0", "return", "DeleteResult", "(", "raw_result", "=", "result", ")" ]
Removes all items matching the mongo query :param query: dictionary representing the mongo query :return: DeleteResult
[ "Removes", "all", "items", "matching", "the", "mongo", "query" ]
train
https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/tinymongo/tinymongo.py#L504-L521
schapman1974/tinymongo
tinymongo/tinymongo.py
TinyMongoCursor.paginate
def paginate(self, skip, limit): """Paginate list of records""" if not self.count() or not limit: return skip = skip or 0 pages = int(ceil(self.count() / float(limit))) limits = {} last = 0 for i in range(pages): current = limit * i limits[last] = current last = current # example with count == 62 # {0: 20, 20: 40, 40: 60, 60: 62} if limit and limit < self.count(): limit = limits.get(skip, self.count()) self.cursordat = self.cursordat[skip: limit]
python
def paginate(self, skip, limit): if not self.count() or not limit: return skip = skip or 0 pages = int(ceil(self.count() / float(limit))) limits = {} last = 0 for i in range(pages): current = limit * i limits[last] = current last = current if limit and limit < self.count(): limit = limits.get(skip, self.count()) self.cursordat = self.cursordat[skip: limit]
[ "def", "paginate", "(", "self", ",", "skip", ",", "limit", ")", ":", "if", "not", "self", ".", "count", "(", ")", "or", "not", "limit", ":", "return", "skip", "=", "skip", "or", "0", "pages", "=", "int", "(", "ceil", "(", "self", ".", "count", "(", ")", "/", "float", "(", "limit", ")", ")", ")", "limits", "=", "{", "}", "last", "=", "0", "for", "i", "in", "range", "(", "pages", ")", ":", "current", "=", "limit", "*", "i", "limits", "[", "last", "]", "=", "current", "last", "=", "current", "# example with count == 62", "# {0: 20, 20: 40, 40: 60, 60: 62}", "if", "limit", "and", "limit", "<", "self", ".", "count", "(", ")", ":", "limit", "=", "limits", ".", "get", "(", "skip", ",", "self", ".", "count", "(", ")", ")", "self", ".", "cursordat", "=", "self", ".", "cursordat", "[", "skip", ":", "limit", "]" ]
Paginate list of records
[ "Paginate", "list", "of", "records" ]
train
https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/tinymongo/tinymongo.py#L548-L564
schapman1974/tinymongo
tinymongo/tinymongo.py
TinyMongoCursor._order
def _order(self, value, is_reverse=None): """Parsing data to a sortable form By giving each data type an ID(int), and assemble with the value into a sortable tuple. """ def _dict_parser(dict_doc): """ dict ordered by: valueType_N -> key_N -> value_N """ result = list() for key in dict_doc: data = self._order(dict_doc[key]) res = (data[0], key, data[1]) result.append(res) return tuple(result) def _list_parser(list_doc): """list will iter members to compare """ result = list() for member in list_doc: result.append(self._order(member)) return result # (TODO) include more data type if value is None or not isinstance(value, (dict, list, basestring, bool, float, int)): # not support/sortable value type value = (0, None) elif isinstance(value, bool): value = (5, value) elif isinstance(value, (int, float)): value = (1, value) elif isinstance(value, basestring): value = (2, value) elif isinstance(value, dict): value = (3, _dict_parser(value)) elif isinstance(value, list): if len(value) == 0: # [] less then None value = [(-1, [])] else: value = _list_parser(value) if is_reverse is not None: # list will firstly compare with other doc by it's smallest # or largest member value = max(value) if is_reverse else min(value) else: # if the smallest or largest member is a list # then compaer with it's sub-member in list index order value = (4, tuple(value)) return value
python
def _order(self, value, is_reverse=None): def _dict_parser(dict_doc): result = list() for key in dict_doc: data = self._order(dict_doc[key]) res = (data[0], key, data[1]) result.append(res) return tuple(result) def _list_parser(list_doc): result = list() for member in list_doc: result.append(self._order(member)) return result if value is None or not isinstance(value, (dict, list, basestring, bool, float, int)): value = (0, None) elif isinstance(value, bool): value = (5, value) elif isinstance(value, (int, float)): value = (1, value) elif isinstance(value, basestring): value = (2, value) elif isinstance(value, dict): value = (3, _dict_parser(value)) elif isinstance(value, list): if len(value) == 0: value = [(-1, [])] else: value = _list_parser(value) if is_reverse is not None: value = max(value) if is_reverse else min(value) else: value = (4, tuple(value)) return value
[ "def", "_order", "(", "self", ",", "value", ",", "is_reverse", "=", "None", ")", ":", "def", "_dict_parser", "(", "dict_doc", ")", ":", "\"\"\" dict ordered by:\n valueType_N -> key_N -> value_N\n \"\"\"", "result", "=", "list", "(", ")", "for", "key", "in", "dict_doc", ":", "data", "=", "self", ".", "_order", "(", "dict_doc", "[", "key", "]", ")", "res", "=", "(", "data", "[", "0", "]", ",", "key", ",", "data", "[", "1", "]", ")", "result", ".", "append", "(", "res", ")", "return", "tuple", "(", "result", ")", "def", "_list_parser", "(", "list_doc", ")", ":", "\"\"\"list will iter members to compare\n \"\"\"", "result", "=", "list", "(", ")", "for", "member", "in", "list_doc", ":", "result", ".", "append", "(", "self", ".", "_order", "(", "member", ")", ")", "return", "result", "# (TODO) include more data type", "if", "value", "is", "None", "or", "not", "isinstance", "(", "value", ",", "(", "dict", ",", "list", ",", "basestring", ",", "bool", ",", "float", ",", "int", ")", ")", ":", "# not support/sortable value type", "value", "=", "(", "0", ",", "None", ")", "elif", "isinstance", "(", "value", ",", "bool", ")", ":", "value", "=", "(", "5", ",", "value", ")", "elif", "isinstance", "(", "value", ",", "(", "int", ",", "float", ")", ")", ":", "value", "=", "(", "1", ",", "value", ")", "elif", "isinstance", "(", "value", ",", "basestring", ")", ":", "value", "=", "(", "2", ",", "value", ")", "elif", "isinstance", "(", "value", ",", "dict", ")", ":", "value", "=", "(", "3", ",", "_dict_parser", "(", "value", ")", ")", "elif", "isinstance", "(", "value", ",", "list", ")", ":", "if", "len", "(", "value", ")", "==", "0", ":", "# [] less then None", "value", "=", "[", "(", "-", "1", ",", "[", "]", ")", "]", "else", ":", "value", "=", "_list_parser", "(", "value", ")", "if", "is_reverse", "is", "not", "None", ":", "# list will firstly compare with other doc by it's smallest", "# or largest member", "value", "=", "max", "(", "value", ")", "if", "is_reverse", "else", "min", "(", "value", ")", "else", ":", "# if the smallest or largest member is a list", "# then compaer with it's sub-member in list index order", "value", "=", "(", "4", ",", "tuple", "(", "value", ")", ")", "return", "value" ]
Parsing data to a sortable form By giving each data type an ID(int), and assemble with the value into a sortable tuple.
[ "Parsing", "data", "to", "a", "sortable", "form", "By", "giving", "each", "data", "type", "an", "ID", "(", "int", ")", "and", "assemble", "with", "the", "value", "into", "a", "sortable", "tuple", "." ]
train
https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/tinymongo/tinymongo.py#L566-L629
schapman1974/tinymongo
tinymongo/tinymongo.py
TinyMongoCursor.sort
def sort(self, key_or_list, direction=None): """ Sorts a cursor object based on the input :param key_or_list: a list/tuple containing the sort specification, i.e. ('user_number': -1), or a basestring :param direction: sorting direction, 1 or -1, needed if key_or_list is a basestring :return: """ # checking input format sort_specifier = list() if isinstance(key_or_list, list): if direction is not None: raise ValueError('direction can not be set separately ' 'if sorting by multiple fields.') for pair in key_or_list: if not (isinstance(pair, list) or isinstance(pair, tuple)): raise TypeError('key pair should be a list or tuple.') if not len(pair) == 2: raise ValueError('Need to be (key, direction) pair') if not isinstance(pair[0], basestring): raise TypeError('first item in each key pair must ' 'be a string') if not isinstance(pair[1], int) or not abs(pair[1]) == 1: raise TypeError('bad sort specification.') sort_specifier = key_or_list elif isinstance(key_or_list, basestring): if direction is not None: if not isinstance(direction, int) or not abs(direction) == 1: raise TypeError('bad sort specification.') else: # default ASCENDING direction = 1 sort_specifier = [(key_or_list, direction)] else: raise ValueError('Wrong input, pass a field name and a direction,' ' or pass a list of (key, direction) pairs.') # sorting _cursordat = self.cursordat total = len(_cursordat) pre_sect_stack = list() for pair in sort_specifier: is_reverse = bool(1-pair[1]) value_stack = list() for index, data in enumerate(_cursordat): # get field value not_found = None for key in pair[0].split('.'): not_found = True if isinstance(data, dict) and key in data: data = copy.deepcopy(data[key]) not_found = False elif isinstance(data, list): if not is_reverse and len(data) == 1: # MongoDB treat [{data}] as {data} # when finding fields if isinstance(data[0], dict) and key in data[0]: data = copy.deepcopy(data[0][key]) not_found = False elif is_reverse: # MongoDB will keep finding field in reverse mode for _d in data: if isinstance(_d, dict) and key in _d: data = copy.deepcopy(_d[key]) not_found = False break if not_found: break # parsing data for sorting if not_found: # treat no match as None data = None value = self._order(data, is_reverse) # read previous section pre_sect = pre_sect_stack[index] if pre_sect_stack else 0 # inverse if in reverse mode # for keeping order as ASCENDING after sort pre_sect = (total - pre_sect) if is_reverse else pre_sect _ind = (total - index) if is_reverse else index value_stack.append((pre_sect, value, _ind)) # sorting cursor data value_stack.sort(reverse=is_reverse) ordereddat = list() sect_stack = list() sect_id = -1 last_dat = None for dat in value_stack: # restore if in reverse mode _ind = (total - dat[-1]) if is_reverse else dat[-1] ordereddat.append(_cursordat[_ind]) # define section # maintain the sorting result in next level sorting if not dat[1] == last_dat: sect_id += 1 sect_stack.append(sect_id) last_dat = dat[1] # save result for next level sorting _cursordat = ordereddat pre_sect_stack = sect_stack # done self.cursordat = _cursordat return self
python
def sort(self, key_or_list, direction=None): sort_specifier = list() if isinstance(key_or_list, list): if direction is not None: raise ValueError('direction can not be set separately ' 'if sorting by multiple fields.') for pair in key_or_list: if not (isinstance(pair, list) or isinstance(pair, tuple)): raise TypeError('key pair should be a list or tuple.') if not len(pair) == 2: raise ValueError('Need to be (key, direction) pair') if not isinstance(pair[0], basestring): raise TypeError('first item in each key pair must ' 'be a string') if not isinstance(pair[1], int) or not abs(pair[1]) == 1: raise TypeError('bad sort specification.') sort_specifier = key_or_list elif isinstance(key_or_list, basestring): if direction is not None: if not isinstance(direction, int) or not abs(direction) == 1: raise TypeError('bad sort specification.') else: direction = 1 sort_specifier = [(key_or_list, direction)] else: raise ValueError('Wrong input, pass a field name and a direction,' ' or pass a list of (key, direction) pairs.') _cursordat = self.cursordat total = len(_cursordat) pre_sect_stack = list() for pair in sort_specifier: is_reverse = bool(1-pair[1]) value_stack = list() for index, data in enumerate(_cursordat): not_found = None for key in pair[0].split('.'): not_found = True if isinstance(data, dict) and key in data: data = copy.deepcopy(data[key]) not_found = False elif isinstance(data, list): if not is_reverse and len(data) == 1: if isinstance(data[0], dict) and key in data[0]: data = copy.deepcopy(data[0][key]) not_found = False elif is_reverse: for _d in data: if isinstance(_d, dict) and key in _d: data = copy.deepcopy(_d[key]) not_found = False break if not_found: break if not_found: data = None value = self._order(data, is_reverse) pre_sect = pre_sect_stack[index] if pre_sect_stack else 0 pre_sect = (total - pre_sect) if is_reverse else pre_sect _ind = (total - index) if is_reverse else index value_stack.append((pre_sect, value, _ind)) value_stack.sort(reverse=is_reverse) ordereddat = list() sect_stack = list() sect_id = -1 last_dat = None for dat in value_stack: _ind = (total - dat[-1]) if is_reverse else dat[-1] ordereddat.append(_cursordat[_ind]) if not dat[1] == last_dat: sect_id += 1 sect_stack.append(sect_id) last_dat = dat[1] _cursordat = ordereddat pre_sect_stack = sect_stack self.cursordat = _cursordat return self
[ "def", "sort", "(", "self", ",", "key_or_list", ",", "direction", "=", "None", ")", ":", "# checking input format", "sort_specifier", "=", "list", "(", ")", "if", "isinstance", "(", "key_or_list", ",", "list", ")", ":", "if", "direction", "is", "not", "None", ":", "raise", "ValueError", "(", "'direction can not be set separately '", "'if sorting by multiple fields.'", ")", "for", "pair", "in", "key_or_list", ":", "if", "not", "(", "isinstance", "(", "pair", ",", "list", ")", "or", "isinstance", "(", "pair", ",", "tuple", ")", ")", ":", "raise", "TypeError", "(", "'key pair should be a list or tuple.'", ")", "if", "not", "len", "(", "pair", ")", "==", "2", ":", "raise", "ValueError", "(", "'Need to be (key, direction) pair'", ")", "if", "not", "isinstance", "(", "pair", "[", "0", "]", ",", "basestring", ")", ":", "raise", "TypeError", "(", "'first item in each key pair must '", "'be a string'", ")", "if", "not", "isinstance", "(", "pair", "[", "1", "]", ",", "int", ")", "or", "not", "abs", "(", "pair", "[", "1", "]", ")", "==", "1", ":", "raise", "TypeError", "(", "'bad sort specification.'", ")", "sort_specifier", "=", "key_or_list", "elif", "isinstance", "(", "key_or_list", ",", "basestring", ")", ":", "if", "direction", "is", "not", "None", ":", "if", "not", "isinstance", "(", "direction", ",", "int", ")", "or", "not", "abs", "(", "direction", ")", "==", "1", ":", "raise", "TypeError", "(", "'bad sort specification.'", ")", "else", ":", "# default ASCENDING", "direction", "=", "1", "sort_specifier", "=", "[", "(", "key_or_list", ",", "direction", ")", "]", "else", ":", "raise", "ValueError", "(", "'Wrong input, pass a field name and a direction,'", "' or pass a list of (key, direction) pairs.'", ")", "# sorting", "_cursordat", "=", "self", ".", "cursordat", "total", "=", "len", "(", "_cursordat", ")", "pre_sect_stack", "=", "list", "(", ")", "for", "pair", "in", "sort_specifier", ":", "is_reverse", "=", "bool", "(", "1", "-", "pair", "[", "1", "]", ")", "value_stack", "=", "list", "(", ")", "for", "index", ",", "data", "in", "enumerate", "(", "_cursordat", ")", ":", "# get field value", "not_found", "=", "None", "for", "key", "in", "pair", "[", "0", "]", ".", "split", "(", "'.'", ")", ":", "not_found", "=", "True", "if", "isinstance", "(", "data", ",", "dict", ")", "and", "key", "in", "data", ":", "data", "=", "copy", ".", "deepcopy", "(", "data", "[", "key", "]", ")", "not_found", "=", "False", "elif", "isinstance", "(", "data", ",", "list", ")", ":", "if", "not", "is_reverse", "and", "len", "(", "data", ")", "==", "1", ":", "# MongoDB treat [{data}] as {data}", "# when finding fields", "if", "isinstance", "(", "data", "[", "0", "]", ",", "dict", ")", "and", "key", "in", "data", "[", "0", "]", ":", "data", "=", "copy", ".", "deepcopy", "(", "data", "[", "0", "]", "[", "key", "]", ")", "not_found", "=", "False", "elif", "is_reverse", ":", "# MongoDB will keep finding field in reverse mode", "for", "_d", "in", "data", ":", "if", "isinstance", "(", "_d", ",", "dict", ")", "and", "key", "in", "_d", ":", "data", "=", "copy", ".", "deepcopy", "(", "_d", "[", "key", "]", ")", "not_found", "=", "False", "break", "if", "not_found", ":", "break", "# parsing data for sorting", "if", "not_found", ":", "# treat no match as None", "data", "=", "None", "value", "=", "self", ".", "_order", "(", "data", ",", "is_reverse", ")", "# read previous section", "pre_sect", "=", "pre_sect_stack", "[", "index", "]", "if", "pre_sect_stack", "else", "0", "# inverse if in reverse mode", "# for keeping order as ASCENDING after sort", "pre_sect", "=", "(", "total", "-", "pre_sect", ")", "if", "is_reverse", "else", "pre_sect", "_ind", "=", "(", "total", "-", "index", ")", "if", "is_reverse", "else", "index", "value_stack", ".", "append", "(", "(", "pre_sect", ",", "value", ",", "_ind", ")", ")", "# sorting cursor data", "value_stack", ".", "sort", "(", "reverse", "=", "is_reverse", ")", "ordereddat", "=", "list", "(", ")", "sect_stack", "=", "list", "(", ")", "sect_id", "=", "-", "1", "last_dat", "=", "None", "for", "dat", "in", "value_stack", ":", "# restore if in reverse mode", "_ind", "=", "(", "total", "-", "dat", "[", "-", "1", "]", ")", "if", "is_reverse", "else", "dat", "[", "-", "1", "]", "ordereddat", ".", "append", "(", "_cursordat", "[", "_ind", "]", ")", "# define section", "# maintain the sorting result in next level sorting", "if", "not", "dat", "[", "1", "]", "==", "last_dat", ":", "sect_id", "+=", "1", "sect_stack", ".", "append", "(", "sect_id", ")", "last_dat", "=", "dat", "[", "1", "]", "# save result for next level sorting", "_cursordat", "=", "ordereddat", "pre_sect_stack", "=", "sect_stack", "# done", "self", ".", "cursordat", "=", "_cursordat", "return", "self" ]
Sorts a cursor object based on the input :param key_or_list: a list/tuple containing the sort specification, i.e. ('user_number': -1), or a basestring :param direction: sorting direction, 1 or -1, needed if key_or_list is a basestring :return:
[ "Sorts", "a", "cursor", "object", "based", "on", "the", "input" ]
train
https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/tinymongo/tinymongo.py#L631-L762
schapman1974/tinymongo
tinymongo/tinymongo.py
TinyMongoCursor.hasNext
def hasNext(self): """ Returns True if the cursor has a next position, False if not :return: """ cursor_pos = self.cursorpos + 1 try: self.cursordat[cursor_pos] return True except IndexError: return False
python
def hasNext(self): cursor_pos = self.cursorpos + 1 try: self.cursordat[cursor_pos] return True except IndexError: return False
[ "def", "hasNext", "(", "self", ")", ":", "cursor_pos", "=", "self", ".", "cursorpos", "+", "1", "try", ":", "self", ".", "cursordat", "[", "cursor_pos", "]", "return", "True", "except", "IndexError", ":", "return", "False" ]
Returns True if the cursor has a next position, False if not :return:
[ "Returns", "True", "if", "the", "cursor", "has", "a", "next", "position", "False", "if", "not", ":", "return", ":" ]
train
https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/tinymongo/tinymongo.py#L764-L775
rm-hull/luma.lcd
luma/lcd/device.py
pcd8544.display
def display(self, image): """ Takes a 1-bit :py:mod:`PIL.Image` and dumps it to the PCD8544 LCD display. """ assert(image.mode == self.mode) assert(image.size == self.size) image = self.preprocess(image) self.command(0x20, 0x80, 0x40) buf = bytearray(self._w * self._h // 8) off = self._offsets mask = self._mask for idx, pix in enumerate(image.getdata()): if pix > 0: buf[off[idx]] |= mask[idx] self.data(list(buf))
python
def display(self, image): assert(image.mode == self.mode) assert(image.size == self.size) image = self.preprocess(image) self.command(0x20, 0x80, 0x40) buf = bytearray(self._w * self._h // 8) off = self._offsets mask = self._mask for idx, pix in enumerate(image.getdata()): if pix > 0: buf[off[idx]] |= mask[idx] self.data(list(buf))
[ "def", "display", "(", "self", ",", "image", ")", ":", "assert", "(", "image", ".", "mode", "==", "self", ".", "mode", ")", "assert", "(", "image", ".", "size", "==", "self", ".", "size", ")", "image", "=", "self", ".", "preprocess", "(", "image", ")", "self", ".", "command", "(", "0x20", ",", "0x80", ",", "0x40", ")", "buf", "=", "bytearray", "(", "self", ".", "_w", "*", "self", ".", "_h", "//", "8", ")", "off", "=", "self", ".", "_offsets", "mask", "=", "self", ".", "_mask", "for", "idx", ",", "pix", "in", "enumerate", "(", "image", ".", "getdata", "(", ")", ")", ":", "if", "pix", ">", "0", ":", "buf", "[", "off", "[", "idx", "]", "]", "|=", "mask", "[", "idx", "]", "self", ".", "data", "(", "list", "(", "buf", ")", ")" ]
Takes a 1-bit :py:mod:`PIL.Image` and dumps it to the PCD8544 LCD display.
[ "Takes", "a", "1", "-", "bit", ":", "py", ":", "mod", ":", "PIL", ".", "Image", "and", "dumps", "it", "to", "the", "PCD8544", "LCD", "display", "." ]
train
https://github.com/rm-hull/luma.lcd/blob/a3ad5d5f9555ffe9d9d5635cb2aa9d0fd98cb131/luma/lcd/device.py#L76-L96
rm-hull/luma.lcd
luma/lcd/device.py
st7567.display
def display(self, image): """ Takes a 1-bit :py:mod:`PIL.Image` and dumps it to the ST7567 LCD display """ assert(image.mode == self.mode) assert(image.size == self.size) image = self.preprocess(image) set_page_address = 0xB0 image_data = image.getdata() pixels_per_page = self.width * 8 buf = bytearray(self.width) for y in range(0, int(self._pages * pixels_per_page), pixels_per_page): self.command(set_page_address, 0x04, 0x10) set_page_address += 1 offsets = [y + self.width * i for i in range(8)] for x in range(self.width): buf[x] = \ (image_data[x + offsets[0]] and 0x01) | \ (image_data[x + offsets[1]] and 0x02) | \ (image_data[x + offsets[2]] and 0x04) | \ (image_data[x + offsets[3]] and 0x08) | \ (image_data[x + offsets[4]] and 0x10) | \ (image_data[x + offsets[5]] and 0x20) | \ (image_data[x + offsets[6]] and 0x40) | \ (image_data[x + offsets[7]] and 0x80) self.data(list(buf))
python
def display(self, image): assert(image.mode == self.mode) assert(image.size == self.size) image = self.preprocess(image) set_page_address = 0xB0 image_data = image.getdata() pixels_per_page = self.width * 8 buf = bytearray(self.width) for y in range(0, int(self._pages * pixels_per_page), pixels_per_page): self.command(set_page_address, 0x04, 0x10) set_page_address += 1 offsets = [y + self.width * i for i in range(8)] for x in range(self.width): buf[x] = \ (image_data[x + offsets[0]] and 0x01) | \ (image_data[x + offsets[1]] and 0x02) | \ (image_data[x + offsets[2]] and 0x04) | \ (image_data[x + offsets[3]] and 0x08) | \ (image_data[x + offsets[4]] and 0x10) | \ (image_data[x + offsets[5]] and 0x20) | \ (image_data[x + offsets[6]] and 0x40) | \ (image_data[x + offsets[7]] and 0x80) self.data(list(buf))
[ "def", "display", "(", "self", ",", "image", ")", ":", "assert", "(", "image", ".", "mode", "==", "self", ".", "mode", ")", "assert", "(", "image", ".", "size", "==", "self", ".", "size", ")", "image", "=", "self", ".", "preprocess", "(", "image", ")", "set_page_address", "=", "0xB0", "image_data", "=", "image", ".", "getdata", "(", ")", "pixels_per_page", "=", "self", ".", "width", "*", "8", "buf", "=", "bytearray", "(", "self", ".", "width", ")", "for", "y", "in", "range", "(", "0", ",", "int", "(", "self", ".", "_pages", "*", "pixels_per_page", ")", ",", "pixels_per_page", ")", ":", "self", ".", "command", "(", "set_page_address", ",", "0x04", ",", "0x10", ")", "set_page_address", "+=", "1", "offsets", "=", "[", "y", "+", "self", ".", "width", "*", "i", "for", "i", "in", "range", "(", "8", ")", "]", "for", "x", "in", "range", "(", "self", ".", "width", ")", ":", "buf", "[", "x", "]", "=", "(", "image_data", "[", "x", "+", "offsets", "[", "0", "]", "]", "and", "0x01", ")", "|", "(", "image_data", "[", "x", "+", "offsets", "[", "1", "]", "]", "and", "0x02", ")", "|", "(", "image_data", "[", "x", "+", "offsets", "[", "2", "]", "]", "and", "0x04", ")", "|", "(", "image_data", "[", "x", "+", "offsets", "[", "3", "]", "]", "and", "0x08", ")", "|", "(", "image_data", "[", "x", "+", "offsets", "[", "4", "]", "]", "and", "0x10", ")", "|", "(", "image_data", "[", "x", "+", "offsets", "[", "5", "]", "]", "and", "0x20", ")", "|", "(", "image_data", "[", "x", "+", "offsets", "[", "6", "]", "]", "and", "0x40", ")", "|", "(", "image_data", "[", "x", "+", "offsets", "[", "7", "]", "]", "and", "0x80", ")", "self", ".", "data", "(", "list", "(", "buf", ")", ")" ]
Takes a 1-bit :py:mod:`PIL.Image` and dumps it to the ST7567 LCD display
[ "Takes", "a", "1", "-", "bit", ":", "py", ":", "mod", ":", "PIL", ".", "Image", "and", "dumps", "it", "to", "the", "ST7567", "LCD", "display" ]
train
https://github.com/rm-hull/luma.lcd/blob/a3ad5d5f9555ffe9d9d5635cb2aa9d0fd98cb131/luma/lcd/device.py#L144-L176
TracyWebTech/django-revproxy
revproxy/utils.py
should_stream
def should_stream(proxy_response): """Function to verify if the proxy_response must be converted into a stream.This will be done by checking the proxy_response content-length and verify if its length is bigger than one stipulated by MIN_STREAMING_LENGTH. :param proxy_response: An Instance of urllib3.response.HTTPResponse :returns: A boolean stating if the proxy_response should be treated as a stream """ content_type = proxy_response.headers.get('Content-Type') if is_html_content_type(content_type): return False try: content_length = int(proxy_response.headers.get('Content-Length', 0)) except ValueError: content_length = 0 if not content_length or content_length > MIN_STREAMING_LENGTH: return True return False
python
def should_stream(proxy_response): content_type = proxy_response.headers.get('Content-Type') if is_html_content_type(content_type): return False try: content_length = int(proxy_response.headers.get('Content-Length', 0)) except ValueError: content_length = 0 if not content_length or content_length > MIN_STREAMING_LENGTH: return True return False
[ "def", "should_stream", "(", "proxy_response", ")", ":", "content_type", "=", "proxy_response", ".", "headers", ".", "get", "(", "'Content-Type'", ")", "if", "is_html_content_type", "(", "content_type", ")", ":", "return", "False", "try", ":", "content_length", "=", "int", "(", "proxy_response", ".", "headers", ".", "get", "(", "'Content-Length'", ",", "0", ")", ")", "except", "ValueError", ":", "content_length", "=", "0", "if", "not", "content_length", "or", "content_length", ">", "MIN_STREAMING_LENGTH", ":", "return", "True", "return", "False" ]
Function to verify if the proxy_response must be converted into a stream.This will be done by checking the proxy_response content-length and verify if its length is bigger than one stipulated by MIN_STREAMING_LENGTH. :param proxy_response: An Instance of urllib3.response.HTTPResponse :returns: A boolean stating if the proxy_response should be treated as a stream
[ "Function", "to", "verify", "if", "the", "proxy_response", "must", "be", "converted", "into", "a", "stream", ".", "This", "will", "be", "done", "by", "checking", "the", "proxy_response", "content", "-", "length", "and", "verify", "if", "its", "length", "is", "bigger", "than", "one", "stipulated", "by", "MIN_STREAMING_LENGTH", "." ]
train
https://github.com/TracyWebTech/django-revproxy/blob/b8d1d9e44eadbafbd16bc03f04d15560089d4472/revproxy/utils.py#L60-L83
TracyWebTech/django-revproxy
revproxy/utils.py
get_charset
def get_charset(content_type): """Function used to retrieve the charset from a content-type.If there is no charset in the content type then the charset defined on DEFAULT_CHARSET will be returned :param content_type: A string containing a Content-Type header :returns: A string containing the charset """ if not content_type: return DEFAULT_CHARSET matched = _get_charset_re.search(content_type) if matched: # Extract the charset and strip its double quotes return matched.group('charset').replace('"', '') return DEFAULT_CHARSET
python
def get_charset(content_type): if not content_type: return DEFAULT_CHARSET matched = _get_charset_re.search(content_type) if matched: return matched.group('charset').replace('"', '') return DEFAULT_CHARSET
[ "def", "get_charset", "(", "content_type", ")", ":", "if", "not", "content_type", ":", "return", "DEFAULT_CHARSET", "matched", "=", "_get_charset_re", ".", "search", "(", "content_type", ")", "if", "matched", ":", "# Extract the charset and strip its double quotes", "return", "matched", ".", "group", "(", "'charset'", ")", ".", "replace", "(", "'\"'", ",", "''", ")", "return", "DEFAULT_CHARSET" ]
Function used to retrieve the charset from a content-type.If there is no charset in the content type then the charset defined on DEFAULT_CHARSET will be returned :param content_type: A string containing a Content-Type header :returns: A string containing the charset
[ "Function", "used", "to", "retrieve", "the", "charset", "from", "a", "content", "-", "type", ".", "If", "there", "is", "no", "charset", "in", "the", "content", "type", "then", "the", "charset", "defined", "on", "DEFAULT_CHARSET", "will", "be", "returned" ]
train
https://github.com/TracyWebTech/django-revproxy/blob/b8d1d9e44eadbafbd16bc03f04d15560089d4472/revproxy/utils.py#L86-L101
TracyWebTech/django-revproxy
revproxy/utils.py
required_header
def required_header(header): """Function that verify if the header parameter is a essential header :param header: A string represented a header :returns: A boolean value that represent if the header is required """ if header in IGNORE_HEADERS: return False if header.startswith('HTTP_') or header == 'CONTENT_TYPE': return True return False
python
def required_header(header): if header in IGNORE_HEADERS: return False if header.startswith('HTTP_') or header == 'CONTENT_TYPE': return True return False
[ "def", "required_header", "(", "header", ")", ":", "if", "header", "in", "IGNORE_HEADERS", ":", "return", "False", "if", "header", ".", "startswith", "(", "'HTTP_'", ")", "or", "header", "==", "'CONTENT_TYPE'", ":", "return", "True", "return", "False" ]
Function that verify if the header parameter is a essential header :param header: A string represented a header :returns: A boolean value that represent if the header is required
[ "Function", "that", "verify", "if", "the", "header", "parameter", "is", "a", "essential", "header" ]
train
https://github.com/TracyWebTech/django-revproxy/blob/b8d1d9e44eadbafbd16bc03f04d15560089d4472/revproxy/utils.py#L104-L116
TracyWebTech/django-revproxy
revproxy/utils.py
normalize_request_headers
def normalize_request_headers(request): r"""Function used to transform header, replacing 'HTTP\_' to '' and replace '_' to '-' :param request: A HttpRequest that will be transformed :returns: A dictionary with the normalized headers """ norm_headers = {} for header, value in request.META.items(): if required_header(header): norm_header = header.replace('HTTP_', '').title().replace('_', '-') norm_headers[norm_header] = value return norm_headers
python
def normalize_request_headers(request): r norm_headers = {} for header, value in request.META.items(): if required_header(header): norm_header = header.replace('HTTP_', '').title().replace('_', '-') norm_headers[norm_header] = value return norm_headers
[ "def", "normalize_request_headers", "(", "request", ")", ":", "norm_headers", "=", "{", "}", "for", "header", ",", "value", "in", "request", ".", "META", ".", "items", "(", ")", ":", "if", "required_header", "(", "header", ")", ":", "norm_header", "=", "header", ".", "replace", "(", "'HTTP_'", ",", "''", ")", ".", "title", "(", ")", ".", "replace", "(", "'_'", ",", "'-'", ")", "norm_headers", "[", "norm_header", "]", "=", "value", "return", "norm_headers" ]
r"""Function used to transform header, replacing 'HTTP\_' to '' and replace '_' to '-' :param request: A HttpRequest that will be transformed :returns: A dictionary with the normalized headers
[ "r", "Function", "used", "to", "transform", "header", "replacing", "HTTP", "\\", "_", "to", "and", "replace", "_", "to", "-" ]
train
https://github.com/TracyWebTech/django-revproxy/blob/b8d1d9e44eadbafbd16bc03f04d15560089d4472/revproxy/utils.py#L130-L143
TracyWebTech/django-revproxy
revproxy/utils.py
encode_items
def encode_items(items): """Function that encode all elements in the list of items passed as a parameter :param items: A list of tuple :returns: A list of tuple with all items encoded in 'utf-8' """ encoded = [] for key, values in items: for value in values: encoded.append((key.encode('utf-8'), value.encode('utf-8'))) return encoded
python
def encode_items(items): encoded = [] for key, values in items: for value in values: encoded.append((key.encode('utf-8'), value.encode('utf-8'))) return encoded
[ "def", "encode_items", "(", "items", ")", ":", "encoded", "=", "[", "]", "for", "key", ",", "values", "in", "items", ":", "for", "value", "in", "values", ":", "encoded", ".", "append", "(", "(", "key", ".", "encode", "(", "'utf-8'", ")", ",", "value", ".", "encode", "(", "'utf-8'", ")", ")", ")", "return", "encoded" ]
Function that encode all elements in the list of items passed as a parameter :param items: A list of tuple :returns: A list of tuple with all items encoded in 'utf-8'
[ "Function", "that", "encode", "all", "elements", "in", "the", "list", "of", "items", "passed", "as", "a", "parameter" ]
train
https://github.com/TracyWebTech/django-revproxy/blob/b8d1d9e44eadbafbd16bc03f04d15560089d4472/revproxy/utils.py#L146-L157
TracyWebTech/django-revproxy
revproxy/utils.py
cookie_from_string
def cookie_from_string(cookie_string, strict_cookies=False): """Parser for HTTP header set-cookie The return from this function will be used as parameters for django's response.set_cookie method. Because set_cookie doesn't have parameter comment, this cookie attribute will be ignored. :param cookie_string: A string representing a valid cookie :param strict_cookies: Whether to only accept RFC-compliant cookies :returns: A dictionary containing the cookie_string attributes """ if strict_cookies: cookies = SimpleCookie(COOKIE_PREFIX + cookie_string) if not cookies.keys(): return None cookie_name, = cookies.keys() cookie_dict = {k: v for k, v in cookies[cookie_name].items() if v and k != 'comment'} cookie_dict['key'] = cookie_name cookie_dict['value'] = cookies[cookie_name].value return cookie_dict else: valid_attrs = ('path', 'domain', 'comment', 'expires', 'max_age', 'httponly', 'secure') cookie_dict = {} cookie_parts = cookie_string.split(';') try: key, value = cookie_parts[0].split('=', 1) cookie_dict['key'], cookie_dict['value'] = key, unquote(value) except ValueError: logger.warning('Invalid cookie: `%s`', cookie_string) return None if cookie_dict['value'].startswith('='): logger.warning('Invalid cookie: `%s`', cookie_string) return None for part in cookie_parts[1:]: if '=' in part: attr, value = part.split('=', 1) value = value.strip() else: attr = part value = '' attr = attr.strip().lower() if not attr: continue if attr in valid_attrs: if attr in ('httponly', 'secure'): cookie_dict[attr] = True elif attr in 'comment': # ignoring comment attr as explained in the # function docstring continue else: cookie_dict[attr] = unquote(value) else: logger.warning('Unknown cookie attribute %s', attr) return cookie_dict
python
def cookie_from_string(cookie_string, strict_cookies=False): if strict_cookies: cookies = SimpleCookie(COOKIE_PREFIX + cookie_string) if not cookies.keys(): return None cookie_name, = cookies.keys() cookie_dict = {k: v for k, v in cookies[cookie_name].items() if v and k != 'comment'} cookie_dict['key'] = cookie_name cookie_dict['value'] = cookies[cookie_name].value return cookie_dict else: valid_attrs = ('path', 'domain', 'comment', 'expires', 'max_age', 'httponly', 'secure') cookie_dict = {} cookie_parts = cookie_string.split(';') try: key, value = cookie_parts[0].split('=', 1) cookie_dict['key'], cookie_dict['value'] = key, unquote(value) except ValueError: logger.warning('Invalid cookie: `%s`', cookie_string) return None if cookie_dict['value'].startswith('='): logger.warning('Invalid cookie: `%s`', cookie_string) return None for part in cookie_parts[1:]: if '=' in part: attr, value = part.split('=', 1) value = value.strip() else: attr = part value = '' attr = attr.strip().lower() if not attr: continue if attr in valid_attrs: if attr in ('httponly', 'secure'): cookie_dict[attr] = True elif attr in 'comment': continue else: cookie_dict[attr] = unquote(value) else: logger.warning('Unknown cookie attribute %s', attr) return cookie_dict
[ "def", "cookie_from_string", "(", "cookie_string", ",", "strict_cookies", "=", "False", ")", ":", "if", "strict_cookies", ":", "cookies", "=", "SimpleCookie", "(", "COOKIE_PREFIX", "+", "cookie_string", ")", "if", "not", "cookies", ".", "keys", "(", ")", ":", "return", "None", "cookie_name", ",", "=", "cookies", ".", "keys", "(", ")", "cookie_dict", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "cookies", "[", "cookie_name", "]", ".", "items", "(", ")", "if", "v", "and", "k", "!=", "'comment'", "}", "cookie_dict", "[", "'key'", "]", "=", "cookie_name", "cookie_dict", "[", "'value'", "]", "=", "cookies", "[", "cookie_name", "]", ".", "value", "return", "cookie_dict", "else", ":", "valid_attrs", "=", "(", "'path'", ",", "'domain'", ",", "'comment'", ",", "'expires'", ",", "'max_age'", ",", "'httponly'", ",", "'secure'", ")", "cookie_dict", "=", "{", "}", "cookie_parts", "=", "cookie_string", ".", "split", "(", "';'", ")", "try", ":", "key", ",", "value", "=", "cookie_parts", "[", "0", "]", ".", "split", "(", "'='", ",", "1", ")", "cookie_dict", "[", "'key'", "]", ",", "cookie_dict", "[", "'value'", "]", "=", "key", ",", "unquote", "(", "value", ")", "except", "ValueError", ":", "logger", ".", "warning", "(", "'Invalid cookie: `%s`'", ",", "cookie_string", ")", "return", "None", "if", "cookie_dict", "[", "'value'", "]", ".", "startswith", "(", "'='", ")", ":", "logger", ".", "warning", "(", "'Invalid cookie: `%s`'", ",", "cookie_string", ")", "return", "None", "for", "part", "in", "cookie_parts", "[", "1", ":", "]", ":", "if", "'='", "in", "part", ":", "attr", ",", "value", "=", "part", ".", "split", "(", "'='", ",", "1", ")", "value", "=", "value", ".", "strip", "(", ")", "else", ":", "attr", "=", "part", "value", "=", "''", "attr", "=", "attr", ".", "strip", "(", ")", ".", "lower", "(", ")", "if", "not", "attr", ":", "continue", "if", "attr", "in", "valid_attrs", ":", "if", "attr", "in", "(", "'httponly'", ",", "'secure'", ")", ":", "cookie_dict", "[", "attr", "]", "=", "True", "elif", "attr", "in", "'comment'", ":", "# ignoring comment attr as explained in the", "# function docstring", "continue", "else", ":", "cookie_dict", "[", "attr", "]", "=", "unquote", "(", "value", ")", "else", ":", "logger", ".", "warning", "(", "'Unknown cookie attribute %s'", ",", "attr", ")", "return", "cookie_dict" ]
Parser for HTTP header set-cookie The return from this function will be used as parameters for django's response.set_cookie method. Because set_cookie doesn't have parameter comment, this cookie attribute will be ignored. :param cookie_string: A string representing a valid cookie :param strict_cookies: Whether to only accept RFC-compliant cookies :returns: A dictionary containing the cookie_string attributes
[ "Parser", "for", "HTTP", "header", "set", "-", "cookie", "The", "return", "from", "this", "function", "will", "be", "used", "as", "parameters", "for", "django", "s", "response", ".", "set_cookie", "method", ".", "Because", "set_cookie", "doesn", "t", "have", "parameter", "comment", "this", "cookie", "attribute", "will", "be", "ignored", "." ]
train
https://github.com/TracyWebTech/django-revproxy/blob/b8d1d9e44eadbafbd16bc03f04d15560089d4472/revproxy/utils.py#L163-L228
TracyWebTech/django-revproxy
revproxy/utils.py
unquote
def unquote(value): """Remove wrapping quotes from a string. :param value: A string that might be wrapped in double quotes, such as a HTTP cookie value. :returns: Beginning and ending quotes removed and escaped quotes (``\"``) unescaped """ if len(value) > 1 and value[0] == '"' and value[-1] == '"': value = value[1:-1].replace(r'\"', '"') return value
python
def unquote(value): if len(value) > 1 and value[0] == '"' and value[-1] == '"': value = value[1:-1].replace(r'\"', '"') return value
[ "def", "unquote", "(", "value", ")", ":", "if", "len", "(", "value", ")", ">", "1", "and", "value", "[", "0", "]", "==", "'\"'", "and", "value", "[", "-", "1", "]", "==", "'\"'", ":", "value", "=", "value", "[", "1", ":", "-", "1", "]", ".", "replace", "(", "r'\\\"'", ",", "'\"'", ")", "return", "value" ]
Remove wrapping quotes from a string. :param value: A string that might be wrapped in double quotes, such as a HTTP cookie value. :returns: Beginning and ending quotes removed and escaped quotes (``\"``) unescaped
[ "Remove", "wrapping", "quotes", "from", "a", "string", "." ]
train
https://github.com/TracyWebTech/django-revproxy/blob/b8d1d9e44eadbafbd16bc03f04d15560089d4472/revproxy/utils.py#L231-L241
TracyWebTech/django-revproxy
revproxy/transformer.py
asbool
def asbool(value): """Function used to convert certain string values into an appropriated boolean value.If value is not a string the built-in python bool function will be used to convert the passed parameter :param value: an object to be converted to a boolean value :returns: A boolean value """ is_string = isinstance(value, string_types) if is_string: value = value.strip().lower() if value in ('true', 'yes', 'on', 'y', 't', '1',): return True elif value in ('false', 'no', 'off', 'n', 'f', '0'): return False else: raise ValueError("String is not true/false: %r" % value) else: return bool(value)
python
def asbool(value): is_string = isinstance(value, string_types) if is_string: value = value.strip().lower() if value in ('true', 'yes', 'on', 'y', 't', '1',): return True elif value in ('false', 'no', 'off', 'n', 'f', '0'): return False else: raise ValueError("String is not true/false: %r" % value) else: return bool(value)
[ "def", "asbool", "(", "value", ")", ":", "is_string", "=", "isinstance", "(", "value", ",", "string_types", ")", "if", "is_string", ":", "value", "=", "value", ".", "strip", "(", ")", ".", "lower", "(", ")", "if", "value", "in", "(", "'true'", ",", "'yes'", ",", "'on'", ",", "'y'", ",", "'t'", ",", "'1'", ",", ")", ":", "return", "True", "elif", "value", "in", "(", "'false'", ",", "'no'", ",", "'off'", ",", "'n'", ",", "'f'", ",", "'0'", ")", ":", "return", "False", "else", ":", "raise", "ValueError", "(", "\"String is not true/false: %r\"", "%", "value", ")", "else", ":", "return", "bool", "(", "value", ")" ]
Function used to convert certain string values into an appropriated boolean value.If value is not a string the built-in python bool function will be used to convert the passed parameter :param value: an object to be converted to a boolean value :returns: A boolean value
[ "Function", "used", "to", "convert", "certain", "string", "values", "into", "an", "appropriated", "boolean", "value", ".", "If", "value", "is", "not", "a", "string", "the", "built", "-", "in", "python", "bool", "function", "will", "be", "used", "to", "convert", "the", "passed", "parameter" ]
train
https://github.com/TracyWebTech/django-revproxy/blob/b8d1d9e44eadbafbd16bc03f04d15560089d4472/revproxy/transformer.py#L30-L50
TracyWebTech/django-revproxy
revproxy/transformer.py
DiazoTransformer.should_transform
def should_transform(self): """Determine if we should transform the response :returns: A boolean value """ if not HAS_DIAZO: self.log.info("HAS_DIAZO: false") return False if asbool(self.request.META.get(DIAZO_OFF_REQUEST_HEADER)): self.log.info("DIAZO_OFF_REQUEST_HEADER in request.META: off") return False if asbool(self.response.get(DIAZO_OFF_RESPONSE_HEADER)): self.log.info("DIAZO_OFF_RESPONSE_HEADER in response.get: off") return False if self.request.is_ajax(): self.log.info("Request is AJAX") return False if self.response.streaming: self.log.info("Response has streaming") return False content_type = self.response.get('Content-Type') if not is_html_content_type(content_type): self.log.info("Content-type: false") return False content_encoding = self.response.get('Content-Encoding') if content_encoding in ('zip', 'compress'): self.log.info("Content encode is %s", content_encoding) return False status_code = str(self.response.status_code) if status_code.startswith('3') or \ status_code == '204' or \ status_code == '401': self.log.info("Status code: %s", status_code) return False if len(self.response.content) == 0: self.log.info("Response Content is EMPTY") return False self.log.info("Transform") return True
python
def should_transform(self): if not HAS_DIAZO: self.log.info("HAS_DIAZO: false") return False if asbool(self.request.META.get(DIAZO_OFF_REQUEST_HEADER)): self.log.info("DIAZO_OFF_REQUEST_HEADER in request.META: off") return False if asbool(self.response.get(DIAZO_OFF_RESPONSE_HEADER)): self.log.info("DIAZO_OFF_RESPONSE_HEADER in response.get: off") return False if self.request.is_ajax(): self.log.info("Request is AJAX") return False if self.response.streaming: self.log.info("Response has streaming") return False content_type = self.response.get('Content-Type') if not is_html_content_type(content_type): self.log.info("Content-type: false") return False content_encoding = self.response.get('Content-Encoding') if content_encoding in ('zip', 'compress'): self.log.info("Content encode is %s", content_encoding) return False status_code = str(self.response.status_code) if status_code.startswith('3') or \ status_code == '204' or \ status_code == '401': self.log.info("Status code: %s", status_code) return False if len(self.response.content) == 0: self.log.info("Response Content is EMPTY") return False self.log.info("Transform") return True
[ "def", "should_transform", "(", "self", ")", ":", "if", "not", "HAS_DIAZO", ":", "self", ".", "log", ".", "info", "(", "\"HAS_DIAZO: false\"", ")", "return", "False", "if", "asbool", "(", "self", ".", "request", ".", "META", ".", "get", "(", "DIAZO_OFF_REQUEST_HEADER", ")", ")", ":", "self", ".", "log", ".", "info", "(", "\"DIAZO_OFF_REQUEST_HEADER in request.META: off\"", ")", "return", "False", "if", "asbool", "(", "self", ".", "response", ".", "get", "(", "DIAZO_OFF_RESPONSE_HEADER", ")", ")", ":", "self", ".", "log", ".", "info", "(", "\"DIAZO_OFF_RESPONSE_HEADER in response.get: off\"", ")", "return", "False", "if", "self", ".", "request", ".", "is_ajax", "(", ")", ":", "self", ".", "log", ".", "info", "(", "\"Request is AJAX\"", ")", "return", "False", "if", "self", ".", "response", ".", "streaming", ":", "self", ".", "log", ".", "info", "(", "\"Response has streaming\"", ")", "return", "False", "content_type", "=", "self", ".", "response", ".", "get", "(", "'Content-Type'", ")", "if", "not", "is_html_content_type", "(", "content_type", ")", ":", "self", ".", "log", ".", "info", "(", "\"Content-type: false\"", ")", "return", "False", "content_encoding", "=", "self", ".", "response", ".", "get", "(", "'Content-Encoding'", ")", "if", "content_encoding", "in", "(", "'zip'", ",", "'compress'", ")", ":", "self", ".", "log", ".", "info", "(", "\"Content encode is %s\"", ",", "content_encoding", ")", "return", "False", "status_code", "=", "str", "(", "self", ".", "response", ".", "status_code", ")", "if", "status_code", ".", "startswith", "(", "'3'", ")", "or", "status_code", "==", "'204'", "or", "status_code", "==", "'401'", ":", "self", ".", "log", ".", "info", "(", "\"Status code: %s\"", ",", "status_code", ")", "return", "False", "if", "len", "(", "self", ".", "response", ".", "content", ")", "==", "0", ":", "self", ".", "log", ".", "info", "(", "\"Response Content is EMPTY\"", ")", "return", "False", "self", ".", "log", ".", "info", "(", "\"Transform\"", ")", "return", "True" ]
Determine if we should transform the response :returns: A boolean value
[ "Determine", "if", "we", "should", "transform", "the", "response" ]
train
https://github.com/TracyWebTech/django-revproxy/blob/b8d1d9e44eadbafbd16bc03f04d15560089d4472/revproxy/transformer.py#L62-L110
TracyWebTech/django-revproxy
revproxy/transformer.py
DiazoTransformer.transform
def transform(self, rules, theme_template, is_html5, context_data=None): """Method used to make a transformation on the content of the http response based on the rules and theme_templates passed as paremters :param rules: A file with a set of diazo rules to make a transformation over the original response content :param theme_template: A file containing the template used to format the the original response content :param is_html5: A boolean parameter to identify a html5 doctype :returns: A response with a content transformed based on the rules and theme_template """ if not self.should_transform(): self.log.info("Don't need to be transformed") return self.response theme = loader.render_to_string(theme_template, context=context_data, request=self.request) output_xslt = compile_theme( rules=rules, theme=StringIO(theme), ) transform = etree.XSLT(output_xslt) self.log.debug("Transform: %s", transform) charset = get_charset(self.response.get('Content-Type')) try: decoded_response = self.response.content.decode(charset) except UnicodeDecodeError: decoded_response = self.response.content.decode(charset, 'ignore') self.log.warning("Charset is {} and type of encode used in file is\ different. Some unknown characteres might be\ ignored.".format(charset)) content_doc = etree.fromstring(decoded_response, parser=etree.HTMLParser()) self.response.content = transform(content_doc) if is_html5: self.set_html5_doctype() self.reset_headers() self.log.debug("Response transformer: %s", self.response) return self.response
python
def transform(self, rules, theme_template, is_html5, context_data=None): if not self.should_transform(): self.log.info("Don't need to be transformed") return self.response theme = loader.render_to_string(theme_template, context=context_data, request=self.request) output_xslt = compile_theme( rules=rules, theme=StringIO(theme), ) transform = etree.XSLT(output_xslt) self.log.debug("Transform: %s", transform) charset = get_charset(self.response.get('Content-Type')) try: decoded_response = self.response.content.decode(charset) except UnicodeDecodeError: decoded_response = self.response.content.decode(charset, 'ignore') self.log.warning("Charset is {} and type of encode used in file is\ different. Some unknown characteres might be\ ignored.".format(charset)) content_doc = etree.fromstring(decoded_response, parser=etree.HTMLParser()) self.response.content = transform(content_doc) if is_html5: self.set_html5_doctype() self.reset_headers() self.log.debug("Response transformer: %s", self.response) return self.response
[ "def", "transform", "(", "self", ",", "rules", ",", "theme_template", ",", "is_html5", ",", "context_data", "=", "None", ")", ":", "if", "not", "self", ".", "should_transform", "(", ")", ":", "self", ".", "log", ".", "info", "(", "\"Don't need to be transformed\"", ")", "return", "self", ".", "response", "theme", "=", "loader", ".", "render_to_string", "(", "theme_template", ",", "context", "=", "context_data", ",", "request", "=", "self", ".", "request", ")", "output_xslt", "=", "compile_theme", "(", "rules", "=", "rules", ",", "theme", "=", "StringIO", "(", "theme", ")", ",", ")", "transform", "=", "etree", ".", "XSLT", "(", "output_xslt", ")", "self", ".", "log", ".", "debug", "(", "\"Transform: %s\"", ",", "transform", ")", "charset", "=", "get_charset", "(", "self", ".", "response", ".", "get", "(", "'Content-Type'", ")", ")", "try", ":", "decoded_response", "=", "self", ".", "response", ".", "content", ".", "decode", "(", "charset", ")", "except", "UnicodeDecodeError", ":", "decoded_response", "=", "self", ".", "response", ".", "content", ".", "decode", "(", "charset", ",", "'ignore'", ")", "self", ".", "log", ".", "warning", "(", "\"Charset is {} and type of encode used in file is\\\n different. Some unknown characteres might be\\\n ignored.\"", ".", "format", "(", "charset", ")", ")", "content_doc", "=", "etree", ".", "fromstring", "(", "decoded_response", ",", "parser", "=", "etree", ".", "HTMLParser", "(", ")", ")", "self", ".", "response", ".", "content", "=", "transform", "(", "content_doc", ")", "if", "is_html5", ":", "self", ".", "set_html5_doctype", "(", ")", "self", ".", "reset_headers", "(", ")", "self", ".", "log", ".", "debug", "(", "\"Response transformer: %s\"", ",", "self", ".", "response", ")", "return", "self", ".", "response" ]
Method used to make a transformation on the content of the http response based on the rules and theme_templates passed as paremters :param rules: A file with a set of diazo rules to make a transformation over the original response content :param theme_template: A file containing the template used to format the the original response content :param is_html5: A boolean parameter to identify a html5 doctype :returns: A response with a content transformed based on the rules and theme_template
[ "Method", "used", "to", "make", "a", "transformation", "on", "the", "content", "of", "the", "http", "response", "based", "on", "the", "rules", "and", "theme_templates", "passed", "as", "paremters" ]
train
https://github.com/TracyWebTech/django-revproxy/blob/b8d1d9e44eadbafbd16bc03f04d15560089d4472/revproxy/transformer.py#L112-L161
TracyWebTech/django-revproxy
revproxy/transformer.py
DiazoTransformer.set_html5_doctype
def set_html5_doctype(self): """Method used to transform a doctype in to a properly html5 doctype """ doctype = b'<!DOCTYPE html>\n' content = doctype_re.subn(doctype, self.response.content, 1)[0] self.response.content = content
python
def set_html5_doctype(self): doctype = b'<!DOCTYPE html>\n' content = doctype_re.subn(doctype, self.response.content, 1)[0] self.response.content = content
[ "def", "set_html5_doctype", "(", "self", ")", ":", "doctype", "=", "b'<!DOCTYPE html>\\n'", "content", "=", "doctype_re", ".", "subn", "(", "doctype", ",", "self", ".", "response", ".", "content", ",", "1", ")", "[", "0", "]", "self", ".", "response", ".", "content", "=", "content" ]
Method used to transform a doctype in to a properly html5 doctype
[ "Method", "used", "to", "transform", "a", "doctype", "in", "to", "a", "properly", "html5", "doctype" ]
train
https://github.com/TracyWebTech/django-revproxy/blob/b8d1d9e44eadbafbd16bc03f04d15560089d4472/revproxy/transformer.py#L170-L175
TracyWebTech/django-revproxy
revproxy/connection.py
_output
def _output(self, s): """Host header should always be first""" if s.lower().startswith(b'host: '): self._buffer.insert(1, s) else: self._buffer.append(s)
python
def _output(self, s): if s.lower().startswith(b'host: '): self._buffer.insert(1, s) else: self._buffer.append(s)
[ "def", "_output", "(", "self", ",", "s", ")", ":", "if", "s", ".", "lower", "(", ")", ".", "startswith", "(", "b'host: '", ")", ":", "self", ".", "_buffer", ".", "insert", "(", "1", ",", "s", ")", "else", ":", "self", ".", "_buffer", ".", "append", "(", "s", ")" ]
Host header should always be first
[ "Host", "header", "should", "always", "be", "first" ]
train
https://github.com/TracyWebTech/django-revproxy/blob/b8d1d9e44eadbafbd16bc03f04d15560089d4472/revproxy/connection.py#L6-L12
TracyWebTech/django-revproxy
revproxy/response.py
get_django_response
def get_django_response(proxy_response, strict_cookies=False): """This method is used to create an appropriate response based on the Content-Length of the proxy_response. If the content is bigger than MIN_STREAMING_LENGTH, which is found on utils.py, than django.http.StreamingHttpResponse will be created, else a django.http.HTTPResponse will be created instead :param proxy_response: An Instance of urllib3.response.HTTPResponse that will create an appropriate response :param strict_cookies: Whether to only accept RFC-compliant cookies :returns: Returns an appropriate response based on the proxy_response content-length """ status = proxy_response.status headers = proxy_response.headers logger.debug('Proxy response headers: %s', headers) content_type = headers.get('Content-Type') logger.debug('Content-Type: %s', content_type) if should_stream(proxy_response): logger.info('Content-Length is bigger than %s', DEFAULT_AMT) response = StreamingHttpResponse(proxy_response.stream(DEFAULT_AMT), status=status, content_type=content_type) else: content = proxy_response.data or b'' response = HttpResponse(content, status=status, content_type=content_type) logger.info('Normalizing response headers') set_response_headers(response, headers) logger.debug('Response headers: %s', getattr(response, '_headers')) cookies = proxy_response.headers.getlist('set-cookie') logger.info('Checking for invalid cookies') for cookie_string in cookies: cookie_dict = cookie_from_string(cookie_string, strict_cookies=strict_cookies) # if cookie is invalid cookie_dict will be None if cookie_dict: response.set_cookie(**cookie_dict) logger.debug('Response cookies: %s', response.cookies) return response
python
def get_django_response(proxy_response, strict_cookies=False): status = proxy_response.status headers = proxy_response.headers logger.debug('Proxy response headers: %s', headers) content_type = headers.get('Content-Type') logger.debug('Content-Type: %s', content_type) if should_stream(proxy_response): logger.info('Content-Length is bigger than %s', DEFAULT_AMT) response = StreamingHttpResponse(proxy_response.stream(DEFAULT_AMT), status=status, content_type=content_type) else: content = proxy_response.data or b'' response = HttpResponse(content, status=status, content_type=content_type) logger.info('Normalizing response headers') set_response_headers(response, headers) logger.debug('Response headers: %s', getattr(response, '_headers')) cookies = proxy_response.headers.getlist('set-cookie') logger.info('Checking for invalid cookies') for cookie_string in cookies: cookie_dict = cookie_from_string(cookie_string, strict_cookies=strict_cookies) if cookie_dict: response.set_cookie(**cookie_dict) logger.debug('Response cookies: %s', response.cookies) return response
[ "def", "get_django_response", "(", "proxy_response", ",", "strict_cookies", "=", "False", ")", ":", "status", "=", "proxy_response", ".", "status", "headers", "=", "proxy_response", ".", "headers", "logger", ".", "debug", "(", "'Proxy response headers: %s'", ",", "headers", ")", "content_type", "=", "headers", ".", "get", "(", "'Content-Type'", ")", "logger", ".", "debug", "(", "'Content-Type: %s'", ",", "content_type", ")", "if", "should_stream", "(", "proxy_response", ")", ":", "logger", ".", "info", "(", "'Content-Length is bigger than %s'", ",", "DEFAULT_AMT", ")", "response", "=", "StreamingHttpResponse", "(", "proxy_response", ".", "stream", "(", "DEFAULT_AMT", ")", ",", "status", "=", "status", ",", "content_type", "=", "content_type", ")", "else", ":", "content", "=", "proxy_response", ".", "data", "or", "b''", "response", "=", "HttpResponse", "(", "content", ",", "status", "=", "status", ",", "content_type", "=", "content_type", ")", "logger", ".", "info", "(", "'Normalizing response headers'", ")", "set_response_headers", "(", "response", ",", "headers", ")", "logger", ".", "debug", "(", "'Response headers: %s'", ",", "getattr", "(", "response", ",", "'_headers'", ")", ")", "cookies", "=", "proxy_response", ".", "headers", ".", "getlist", "(", "'set-cookie'", ")", "logger", ".", "info", "(", "'Checking for invalid cookies'", ")", "for", "cookie_string", "in", "cookies", ":", "cookie_dict", "=", "cookie_from_string", "(", "cookie_string", ",", "strict_cookies", "=", "strict_cookies", ")", "# if cookie is invalid cookie_dict will be None", "if", "cookie_dict", ":", "response", ".", "set_cookie", "(", "*", "*", "cookie_dict", ")", "logger", ".", "debug", "(", "'Response cookies: %s'", ",", "response", ".", "cookies", ")", "return", "response" ]
This method is used to create an appropriate response based on the Content-Length of the proxy_response. If the content is bigger than MIN_STREAMING_LENGTH, which is found on utils.py, than django.http.StreamingHttpResponse will be created, else a django.http.HTTPResponse will be created instead :param proxy_response: An Instance of urllib3.response.HTTPResponse that will create an appropriate response :param strict_cookies: Whether to only accept RFC-compliant cookies :returns: Returns an appropriate response based on the proxy_response content-length
[ "This", "method", "is", "used", "to", "create", "an", "appropriate", "response", "based", "on", "the", "Content", "-", "Length", "of", "the", "proxy_response", ".", "If", "the", "content", "is", "bigger", "than", "MIN_STREAMING_LENGTH", "which", "is", "found", "on", "utils", ".", "py", "than", "django", ".", "http", ".", "StreamingHttpResponse", "will", "be", "created", "else", "a", "django", ".", "http", ".", "HTTPResponse", "will", "be", "created", "instead" ]
train
https://github.com/TracyWebTech/django-revproxy/blob/b8d1d9e44eadbafbd16bc03f04d15560089d4472/revproxy/response.py#L13-L61
TracyWebTech/django-revproxy
revproxy/views.py
ProxyView.get_request_headers
def get_request_headers(self): """Return request headers that will be sent to upstream. The header REMOTE_USER is set to the current user if AuthenticationMiddleware is enabled and the view's add_remote_user property is True. .. versionadded:: 0.9.8 """ request_headers = self.get_proxy_request_headers(self.request) if (self.add_remote_user and hasattr(self.request, 'user') and self.request.user.is_active): request_headers['REMOTE_USER'] = self.request.user.get_username() self.log.info("REMOTE_USER set") return request_headers
python
def get_request_headers(self): request_headers = self.get_proxy_request_headers(self.request) if (self.add_remote_user and hasattr(self.request, 'user') and self.request.user.is_active): request_headers['REMOTE_USER'] = self.request.user.get_username() self.log.info("REMOTE_USER set") return request_headers
[ "def", "get_request_headers", "(", "self", ")", ":", "request_headers", "=", "self", ".", "get_proxy_request_headers", "(", "self", ".", "request", ")", "if", "(", "self", ".", "add_remote_user", "and", "hasattr", "(", "self", ".", "request", ",", "'user'", ")", "and", "self", ".", "request", ".", "user", ".", "is_active", ")", ":", "request_headers", "[", "'REMOTE_USER'", "]", "=", "self", ".", "request", ".", "user", ".", "get_username", "(", ")", "self", ".", "log", ".", "info", "(", "\"REMOTE_USER set\"", ")", "return", "request_headers" ]
Return request headers that will be sent to upstream. The header REMOTE_USER is set to the current user if AuthenticationMiddleware is enabled and the view's add_remote_user property is True. .. versionadded:: 0.9.8
[ "Return", "request", "headers", "that", "will", "be", "sent", "to", "upstream", "." ]
train
https://github.com/TracyWebTech/django-revproxy/blob/b8d1d9e44eadbafbd16bc03f04d15560089d4472/revproxy/views.py#L117-L134
TracyWebTech/django-revproxy
revproxy/views.py
ProxyView.get_encoded_query_params
def get_encoded_query_params(self): """Return encoded query params to be used in proxied request""" get_data = encode_items(self.request.GET.lists()) return urlencode(get_data)
python
def get_encoded_query_params(self): get_data = encode_items(self.request.GET.lists()) return urlencode(get_data)
[ "def", "get_encoded_query_params", "(", "self", ")", ":", "get_data", "=", "encode_items", "(", "self", ".", "request", ".", "GET", ".", "lists", "(", ")", ")", "return", "urlencode", "(", "get_data", ")" ]
Return encoded query params to be used in proxied request
[ "Return", "encoded", "query", "params", "to", "be", "used", "in", "proxied", "request" ]
train
https://github.com/TracyWebTech/django-revproxy/blob/b8d1d9e44eadbafbd16bc03f04d15560089d4472/revproxy/views.py#L140-L143
jsfenfen/990-xml-reader
irs_reader/file_utils.py
stream_download
def stream_download(url, target_path, verbose=False): """ Download a large file without loading it into memory. """ response = requests.get(url, stream=True) handle = open(target_path, "wb") if verbose: print("Beginning streaming download of %s" % url) start = datetime.now() try: content_length = int(response.headers['Content-Length']) content_MB = content_length/1048576.0 print("Total file size: %.2f MB" % content_MB) except KeyError: pass # allow Content-Length to be missing for chunk in response.iter_content(chunk_size=512): if chunk: # filter out keep-alive new chunks handle.write(chunk) if verbose: print( "Download completed to %s in %s" % (target_path, datetime.now() - start))
python
def stream_download(url, target_path, verbose=False): response = requests.get(url, stream=True) handle = open(target_path, "wb") if verbose: print("Beginning streaming download of %s" % url) start = datetime.now() try: content_length = int(response.headers['Content-Length']) content_MB = content_length/1048576.0 print("Total file size: %.2f MB" % content_MB) except KeyError: pass for chunk in response.iter_content(chunk_size=512): if chunk: handle.write(chunk) if verbose: print( "Download completed to %s in %s" % (target_path, datetime.now() - start))
[ "def", "stream_download", "(", "url", ",", "target_path", ",", "verbose", "=", "False", ")", ":", "response", "=", "requests", ".", "get", "(", "url", ",", "stream", "=", "True", ")", "handle", "=", "open", "(", "target_path", ",", "\"wb\"", ")", "if", "verbose", ":", "print", "(", "\"Beginning streaming download of %s\"", "%", "url", ")", "start", "=", "datetime", ".", "now", "(", ")", "try", ":", "content_length", "=", "int", "(", "response", ".", "headers", "[", "'Content-Length'", "]", ")", "content_MB", "=", "content_length", "/", "1048576.0", "print", "(", "\"Total file size: %.2f MB\"", "%", "content_MB", ")", "except", "KeyError", ":", "pass", "# allow Content-Length to be missing", "for", "chunk", "in", "response", ".", "iter_content", "(", "chunk_size", "=", "512", ")", ":", "if", "chunk", ":", "# filter out keep-alive new chunks", "handle", ".", "write", "(", "chunk", ")", "if", "verbose", ":", "print", "(", "\"Download completed to %s in %s\"", "%", "(", "target_path", ",", "datetime", ".", "now", "(", ")", "-", "start", ")", ")" ]
Download a large file without loading it into memory.
[ "Download", "a", "large", "file", "without", "loading", "it", "into", "memory", "." ]
train
https://github.com/jsfenfen/990-xml-reader/blob/00020529b789081329a31a2e30b5ee729ce7596a/irs_reader/file_utils.py#L20-L39
jsfenfen/990-xml-reader
irs_reader/file_utils.py
validate_object_id
def validate_object_id(object_id): """ It's easy to make a mistake entering these, validate the format """ result = re.match(OBJECT_ID_RE, str(object_id)) if not result: print("'%s' appears not to be a valid 990 object_id" % object_id) raise RuntimeError(OBJECT_ID_MSG) return object_id
python
def validate_object_id(object_id): result = re.match(OBJECT_ID_RE, str(object_id)) if not result: print("'%s' appears not to be a valid 990 object_id" % object_id) raise RuntimeError(OBJECT_ID_MSG) return object_id
[ "def", "validate_object_id", "(", "object_id", ")", ":", "result", "=", "re", ".", "match", "(", "OBJECT_ID_RE", ",", "str", "(", "object_id", ")", ")", "if", "not", "result", ":", "print", "(", "\"'%s' appears not to be a valid 990 object_id\"", "%", "object_id", ")", "raise", "RuntimeError", "(", "OBJECT_ID_MSG", ")", "return", "object_id" ]
It's easy to make a mistake entering these, validate the format
[ "It", "s", "easy", "to", "make", "a", "mistake", "entering", "these", "validate", "the", "format" ]
train
https://github.com/jsfenfen/990-xml-reader/blob/00020529b789081329a31a2e30b5ee729ce7596a/irs_reader/file_utils.py#L42-L48
jsfenfen/990-xml-reader
irs_reader/sked_dict_reader.py
SkedDictReader._get_table_start
def _get_table_start(self): """ prefill the columns we need for all tables """ if self.documentation: standardized_table_start = { 'object_id': { 'value': self.object_id, 'ordering': -1, 'line_number': 'NA', 'description': 'IRS-assigned object id', 'db_type': 'String(18)' }, 'ein': { 'value': self.ein, 'ordering': -2, 'line_number': 'NA', 'description': 'IRS employer id number', 'db_type': 'String(9)' } } if self.documentId: standardized_table_start['documentId'] = { 'value': self.documentId, 'description': 'Document ID', 'ordering': 0 } else: standardized_table_start = { 'object_id': self.object_id, 'ein': self.ein } if self.documentId: standardized_table_start['documentId'] = self.documentId return standardized_table_start
python
def _get_table_start(self): if self.documentation: standardized_table_start = { 'object_id': { 'value': self.object_id, 'ordering': -1, 'line_number': 'NA', 'description': 'IRS-assigned object id', 'db_type': 'String(18)' }, 'ein': { 'value': self.ein, 'ordering': -2, 'line_number': 'NA', 'description': 'IRS employer id number', 'db_type': 'String(9)' } } if self.documentId: standardized_table_start['documentId'] = { 'value': self.documentId, 'description': 'Document ID', 'ordering': 0 } else: standardized_table_start = { 'object_id': self.object_id, 'ein': self.ein } if self.documentId: standardized_table_start['documentId'] = self.documentId return standardized_table_start
[ "def", "_get_table_start", "(", "self", ")", ":", "if", "self", ".", "documentation", ":", "standardized_table_start", "=", "{", "'object_id'", ":", "{", "'value'", ":", "self", ".", "object_id", ",", "'ordering'", ":", "-", "1", ",", "'line_number'", ":", "'NA'", ",", "'description'", ":", "'IRS-assigned object id'", ",", "'db_type'", ":", "'String(18)'", "}", ",", "'ein'", ":", "{", "'value'", ":", "self", ".", "ein", ",", "'ordering'", ":", "-", "2", ",", "'line_number'", ":", "'NA'", ",", "'description'", ":", "'IRS employer id number'", ",", "'db_type'", ":", "'String(9)'", "}", "}", "if", "self", ".", "documentId", ":", "standardized_table_start", "[", "'documentId'", "]", "=", "{", "'value'", ":", "self", ".", "documentId", ",", "'description'", ":", "'Document ID'", ",", "'ordering'", ":", "0", "}", "else", ":", "standardized_table_start", "=", "{", "'object_id'", ":", "self", ".", "object_id", ",", "'ein'", ":", "self", ".", "ein", "}", "if", "self", ".", "documentId", ":", "standardized_table_start", "[", "'documentId'", "]", "=", "self", ".", "documentId", "return", "standardized_table_start" ]
prefill the columns we need for all tables
[ "prefill", "the", "columns", "we", "need", "for", "all", "tables" ]
train
https://github.com/jsfenfen/990-xml-reader/blob/00020529b789081329a31a2e30b5ee729ce7596a/irs_reader/sked_dict_reader.py#L45-L78
jsfenfen/990-xml-reader
irs_reader/text_format_utils.py
debracket
def debracket(string): """ Eliminate the bracketed var names in doc, line strings """ result = re.sub(BRACKET_RE, ';', str(string)) result = result.lstrip(';') result = result.lstrip(' ') result = result.replace('; ;',';') return result
python
def debracket(string): result = re.sub(BRACKET_RE, ';', str(string)) result = result.lstrip(';') result = result.lstrip(' ') result = result.replace('; ;',';') return result
[ "def", "debracket", "(", "string", ")", ":", "result", "=", "re", ".", "sub", "(", "BRACKET_RE", ",", "';'", ",", "str", "(", "string", ")", ")", "result", "=", "result", ".", "lstrip", "(", "';'", ")", "result", "=", "result", ".", "lstrip", "(", "' '", ")", "result", "=", "result", ".", "replace", "(", "'; ;'", ",", "';'", ")", "return", "result" ]
Eliminate the bracketed var names in doc, line strings
[ "Eliminate", "the", "bracketed", "var", "names", "in", "doc", "line", "strings" ]
train
https://github.com/jsfenfen/990-xml-reader/blob/00020529b789081329a31a2e30b5ee729ce7596a/irs_reader/text_format_utils.py#L15-L21
jsfenfen/990-xml-reader
irs_reader/xmlrunner.py
XMLRunner.run_sked
def run_sked(self, object_id, sked, verbose=False): """ sked is the proper name of the schedule: IRS990, IRS990EZ, IRS990PF, IRS990ScheduleA, etc. """ self.whole_filing_data = [] self.filing_keyerr_data = [] this_filing = Filing(object_id) this_filing.process(verbose=verbose) this_version = this_filing.get_version() if this_version in ALLOWED_VERSIONSTRINGS or ( self.csv_format and this_version in CSV_ALLOWED_VERSIONSTRINGS ): this_version = this_filing.get_version() ein = this_filing.get_ein() sked_dict = this_filing.get_schedule(sked) self._run_schedule(sked, object_id, sked_dict, ein) this_filing.set_result(self.whole_filing_data) this_filing.set_keyerrors(self.filing_keyerr_data) return this_filing else: print("Filing version %s isn't supported for this operation" % this_version ) return this_filing
python
def run_sked(self, object_id, sked, verbose=False): self.whole_filing_data = [] self.filing_keyerr_data = [] this_filing = Filing(object_id) this_filing.process(verbose=verbose) this_version = this_filing.get_version() if this_version in ALLOWED_VERSIONSTRINGS or ( self.csv_format and this_version in CSV_ALLOWED_VERSIONSTRINGS ): this_version = this_filing.get_version() ein = this_filing.get_ein() sked_dict = this_filing.get_schedule(sked) self._run_schedule(sked, object_id, sked_dict, ein) this_filing.set_result(self.whole_filing_data) this_filing.set_keyerrors(self.filing_keyerr_data) return this_filing else: print("Filing version %s isn't supported for this operation" % this_version ) return this_filing
[ "def", "run_sked", "(", "self", ",", "object_id", ",", "sked", ",", "verbose", "=", "False", ")", ":", "self", ".", "whole_filing_data", "=", "[", "]", "self", ".", "filing_keyerr_data", "=", "[", "]", "this_filing", "=", "Filing", "(", "object_id", ")", "this_filing", ".", "process", "(", "verbose", "=", "verbose", ")", "this_version", "=", "this_filing", ".", "get_version", "(", ")", "if", "this_version", "in", "ALLOWED_VERSIONSTRINGS", "or", "(", "self", ".", "csv_format", "and", "this_version", "in", "CSV_ALLOWED_VERSIONSTRINGS", ")", ":", "this_version", "=", "this_filing", ".", "get_version", "(", ")", "ein", "=", "this_filing", ".", "get_ein", "(", ")", "sked_dict", "=", "this_filing", ".", "get_schedule", "(", "sked", ")", "self", ".", "_run_schedule", "(", "sked", ",", "object_id", ",", "sked_dict", ",", "ein", ")", "this_filing", ".", "set_result", "(", "self", ".", "whole_filing_data", ")", "this_filing", ".", "set_keyerrors", "(", "self", ".", "filing_keyerr_data", ")", "return", "this_filing", "else", ":", "print", "(", "\"Filing version %s isn't supported for this operation\"", "%", "this_version", ")", "return", "this_filing" ]
sked is the proper name of the schedule: IRS990, IRS990EZ, IRS990PF, IRS990ScheduleA, etc.
[ "sked", "is", "the", "proper", "name", "of", "the", "schedule", ":", "IRS990", "IRS990EZ", "IRS990PF", "IRS990ScheduleA", "etc", "." ]
train
https://github.com/jsfenfen/990-xml-reader/blob/00020529b789081329a31a2e30b5ee729ce7596a/irs_reader/xmlrunner.py#L161-L182
jsfenfen/990-xml-reader
irs_reader/filing.py
Filing._download
def _download(self, force_overwrite=False, verbose=False): """ Download the file if it's not already there. We shouldn't *need* to overwrite; the xml is not supposed to update. """ if not force_overwrite: # If the file is already there, we're done if os.path.isfile(self.filepath): if verbose: print( "File already available at %s -- skipping" % (self.filepath) ) return False stream_download(self.URL, self.filepath, verbose=verbose) return True
python
def _download(self, force_overwrite=False, verbose=False): if not force_overwrite: if os.path.isfile(self.filepath): if verbose: print( "File already available at %s -- skipping" % (self.filepath) ) return False stream_download(self.URL, self.filepath, verbose=verbose) return True
[ "def", "_download", "(", "self", ",", "force_overwrite", "=", "False", ",", "verbose", "=", "False", ")", ":", "if", "not", "force_overwrite", ":", "# If the file is already there, we're done", "if", "os", ".", "path", ".", "isfile", "(", "self", ".", "filepath", ")", ":", "if", "verbose", ":", "print", "(", "\"File already available at %s -- skipping\"", "%", "(", "self", ".", "filepath", ")", ")", "return", "False", "stream_download", "(", "self", ".", "URL", ",", "self", ".", "filepath", ",", "verbose", "=", "verbose", ")", "return", "True" ]
Download the file if it's not already there. We shouldn't *need* to overwrite; the xml is not supposed to update.
[ "Download", "the", "file", "if", "it", "s", "not", "already", "there", ".", "We", "shouldn", "t", "*", "need", "*", "to", "overwrite", ";", "the", "xml", "is", "not", "supposed", "to", "update", "." ]
train
https://github.com/jsfenfen/990-xml-reader/blob/00020529b789081329a31a2e30b5ee729ce7596a/irs_reader/filing.py#L53-L68
jsfenfen/990-xml-reader
irs_reader/filing.py
Filing._set_schedules
def _set_schedules(self): """ Attach the known and unknown schedules """ self.schedules = ['ReturnHeader990x', ] self.otherforms = [] for sked in self.raw_irs_dict['Return']['ReturnData'].keys(): if not sked.startswith("@"): if sked in KNOWN_SCHEDULES: self.schedules.append(sked) else: self.otherforms.append(sked)
python
def _set_schedules(self): self.schedules = ['ReturnHeader990x', ] self.otherforms = [] for sked in self.raw_irs_dict['Return']['ReturnData'].keys(): if not sked.startswith("@"): if sked in KNOWN_SCHEDULES: self.schedules.append(sked) else: self.otherforms.append(sked)
[ "def", "_set_schedules", "(", "self", ")", ":", "self", ".", "schedules", "=", "[", "'ReturnHeader990x'", ",", "]", "self", ".", "otherforms", "=", "[", "]", "for", "sked", "in", "self", ".", "raw_irs_dict", "[", "'Return'", "]", "[", "'ReturnData'", "]", ".", "keys", "(", ")", ":", "if", "not", "sked", ".", "startswith", "(", "\"@\"", ")", ":", "if", "sked", "in", "KNOWN_SCHEDULES", ":", "self", ".", "schedules", ".", "append", "(", "sked", ")", "else", ":", "self", ".", "otherforms", ".", "append", "(", "sked", ")" ]
Attach the known and unknown schedules
[ "Attach", "the", "known", "and", "unknown", "schedules" ]
train
https://github.com/jsfenfen/990-xml-reader/blob/00020529b789081329a31a2e30b5ee729ce7596a/irs_reader/filing.py#L101-L110
jsfenfen/990-xml-reader
irs_reader/filing.py
Filing.get_parsed_sked
def get_parsed_sked(self, skedname): """ Returns an array because multiple sked K's are allowed""" if not self.processed: raise Exception("Filing must be processed to return parsed sked") if skedname in self.schedules: matching_skeds = [] for sked in self.result: if sked['schedule_name']==skedname: matching_skeds.append(sked) return matching_skeds else: return []
python
def get_parsed_sked(self, skedname): if not self.processed: raise Exception("Filing must be processed to return parsed sked") if skedname in self.schedules: matching_skeds = [] for sked in self.result: if sked['schedule_name']==skedname: matching_skeds.append(sked) return matching_skeds else: return []
[ "def", "get_parsed_sked", "(", "self", ",", "skedname", ")", ":", "if", "not", "self", ".", "processed", ":", "raise", "Exception", "(", "\"Filing must be processed to return parsed sked\"", ")", "if", "skedname", "in", "self", ".", "schedules", ":", "matching_skeds", "=", "[", "]", "for", "sked", "in", "self", ".", "result", ":", "if", "sked", "[", "'schedule_name'", "]", "==", "skedname", ":", "matching_skeds", ".", "append", "(", "sked", ")", "return", "matching_skeds", "else", ":", "return", "[", "]" ]
Returns an array because multiple sked K's are allowed
[ "Returns", "an", "array", "because", "multiple", "sked", "K", "s", "are", "allowed" ]
train
https://github.com/jsfenfen/990-xml-reader/blob/00020529b789081329a31a2e30b5ee729ce7596a/irs_reader/filing.py#L176-L187
tus/tus-py-client
tusclient/uploader.py
Uploader.headers
def headers(self): """ Return headers of the uploader instance. This would include the headers of the client instance. """ client_headers = getattr(self.client, 'headers', {}) return dict(self.DEFAULT_HEADERS, **client_headers)
python
def headers(self): client_headers = getattr(self.client, 'headers', {}) return dict(self.DEFAULT_HEADERS, **client_headers)
[ "def", "headers", "(", "self", ")", ":", "client_headers", "=", "getattr", "(", "self", ".", "client", ",", "'headers'", ",", "{", "}", ")", "return", "dict", "(", "self", ".", "DEFAULT_HEADERS", ",", "*", "*", "client_headers", ")" ]
Return headers of the uploader instance. This would include the headers of the client instance.
[ "Return", "headers", "of", "the", "uploader", "instance", ".", "This", "would", "include", "the", "headers", "of", "the", "client", "instance", "." ]
train
https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/uploader.py#L139-L145
tus/tus-py-client
tusclient/uploader.py
Uploader.headers_as_list
def headers_as_list(self): """ Does the same as 'headers' except it is returned as a list. """ headers = self.headers headers_list = ['{}: {}'.format(key, value) for key, value in iteritems(headers)] return headers_list
python
def headers_as_list(self): headers = self.headers headers_list = ['{}: {}'.format(key, value) for key, value in iteritems(headers)] return headers_list
[ "def", "headers_as_list", "(", "self", ")", ":", "headers", "=", "self", ".", "headers", "headers_list", "=", "[", "'{}: {}'", ".", "format", "(", "key", ",", "value", ")", "for", "key", ",", "value", "in", "iteritems", "(", "headers", ")", "]", "return", "headers_list" ]
Does the same as 'headers' except it is returned as a list.
[ "Does", "the", "same", "as", "headers", "except", "it", "is", "returned", "as", "a", "list", "." ]
train
https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/uploader.py#L148-L154
tus/tus-py-client
tusclient/uploader.py
Uploader.get_offset
def get_offset(self): """ Return offset from tus server. This is different from the instance attribute 'offset' because this makes an http request to the tus server to retrieve the offset. """ resp = requests.head(self.url, headers=self.headers) offset = resp.headers.get('upload-offset') if offset is None: msg = 'Attempt to retrieve offset fails with status {}'.format(resp.status_code) raise TusCommunicationError(msg, resp.status_code, resp.content) return int(offset)
python
def get_offset(self): resp = requests.head(self.url, headers=self.headers) offset = resp.headers.get('upload-offset') if offset is None: msg = 'Attempt to retrieve offset fails with status {}'.format(resp.status_code) raise TusCommunicationError(msg, resp.status_code, resp.content) return int(offset)
[ "def", "get_offset", "(", "self", ")", ":", "resp", "=", "requests", ".", "head", "(", "self", ".", "url", ",", "headers", "=", "self", ".", "headers", ")", "offset", "=", "resp", ".", "headers", ".", "get", "(", "'upload-offset'", ")", "if", "offset", "is", "None", ":", "msg", "=", "'Attempt to retrieve offset fails with status {}'", ".", "format", "(", "resp", ".", "status_code", ")", "raise", "TusCommunicationError", "(", "msg", ",", "resp", ".", "status_code", ",", "resp", ".", "content", ")", "return", "int", "(", "offset", ")" ]
Return offset from tus server. This is different from the instance attribute 'offset' because this makes an http request to the tus server to retrieve the offset.
[ "Return", "offset", "from", "tus", "server", "." ]
train
https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/uploader.py#L170-L182
tus/tus-py-client
tusclient/uploader.py
Uploader.encode_metadata
def encode_metadata(self): """ Return list of encoded metadata as defined by the Tus protocol. """ encoded_list = [] for key, value in iteritems(self.metadata): key_str = str(key) # dict keys may be of any object type. # confirm that the key does not contain unwanted characters. if re.search(r'^$|[\s,]+', key_str): msg = 'Upload-metadata key "{}" cannot be empty nor contain spaces or commas.' raise ValueError(msg.format(key_str)) value_bytes = b(value) # python 3 only encodes bytes encoded_list.append('{} {}'.format(key_str, b64encode(value_bytes).decode('ascii'))) return encoded_list
python
def encode_metadata(self): encoded_list = [] for key, value in iteritems(self.metadata): key_str = str(key) if re.search(r'^$|[\s,]+', key_str): msg = 'Upload-metadata key "{}" cannot be empty nor contain spaces or commas.' raise ValueError(msg.format(key_str)) value_bytes = b(value) encoded_list.append('{} {}'.format(key_str, b64encode(value_bytes).decode('ascii'))) return encoded_list
[ "def", "encode_metadata", "(", "self", ")", ":", "encoded_list", "=", "[", "]", "for", "key", ",", "value", "in", "iteritems", "(", "self", ".", "metadata", ")", ":", "key_str", "=", "str", "(", "key", ")", "# dict keys may be of any object type.", "# confirm that the key does not contain unwanted characters.", "if", "re", ".", "search", "(", "r'^$|[\\s,]+'", ",", "key_str", ")", ":", "msg", "=", "'Upload-metadata key \"{}\" cannot be empty nor contain spaces or commas.'", "raise", "ValueError", "(", "msg", ".", "format", "(", "key_str", ")", ")", "value_bytes", "=", "b", "(", "value", ")", "# python 3 only encodes bytes", "encoded_list", ".", "append", "(", "'{} {}'", ".", "format", "(", "key_str", ",", "b64encode", "(", "value_bytes", ")", ".", "decode", "(", "'ascii'", ")", ")", ")", "return", "encoded_list" ]
Return list of encoded metadata as defined by the Tus protocol.
[ "Return", "list", "of", "encoded", "metadata", "as", "defined", "by", "the", "Tus", "protocol", "." ]
train
https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/uploader.py#L184-L199
tus/tus-py-client
tusclient/uploader.py
Uploader.get_url
def get_url(self): """ Return the tus upload url. If resumability is enabled, this would try to get the url from storage if available, otherwise it would request a new upload url from the tus server. """ if self.store_url and self.url_storage: key = self.fingerprinter.get_fingerprint(self.get_file_stream()) url = self.url_storage.get_item(key) if not url: url = self.create_url() self.url_storage.set_item(key, url) return url else: return self.create_url()
python
def get_url(self): if self.store_url and self.url_storage: key = self.fingerprinter.get_fingerprint(self.get_file_stream()) url = self.url_storage.get_item(key) if not url: url = self.create_url() self.url_storage.set_item(key, url) return url else: return self.create_url()
[ "def", "get_url", "(", "self", ")", ":", "if", "self", ".", "store_url", "and", "self", ".", "url_storage", ":", "key", "=", "self", ".", "fingerprinter", ".", "get_fingerprint", "(", "self", ".", "get_file_stream", "(", ")", ")", "url", "=", "self", ".", "url_storage", ".", "get_item", "(", "key", ")", "if", "not", "url", ":", "url", "=", "self", ".", "create_url", "(", ")", "self", ".", "url_storage", ".", "set_item", "(", "key", ",", "url", ")", "return", "url", "else", ":", "return", "self", ".", "create_url", "(", ")" ]
Return the tus upload url. If resumability is enabled, this would try to get the url from storage if available, otherwise it would request a new upload url from the tus server.
[ "Return", "the", "tus", "upload", "url", "." ]
train
https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/uploader.py#L201-L216
tus/tus-py-client
tusclient/uploader.py
Uploader.create_url
def create_url(self): """ Return upload url. Makes request to tus server to create a new upload url for the required file upload. """ headers = self.headers headers['upload-length'] = str(self.file_size) headers['upload-metadata'] = ','.join(self.encode_metadata()) resp = requests.post(self.client.url, headers=headers) url = resp.headers.get("location") if url is None: msg = 'Attempt to retrieve create file url with status {}'.format(resp.status_code) raise TusCommunicationError(msg, resp.status_code, resp.content) return urljoin(self.client.url, url)
python
def create_url(self): headers = self.headers headers['upload-length'] = str(self.file_size) headers['upload-metadata'] = ','.join(self.encode_metadata()) resp = requests.post(self.client.url, headers=headers) url = resp.headers.get("location") if url is None: msg = 'Attempt to retrieve create file url with status {}'.format(resp.status_code) raise TusCommunicationError(msg, resp.status_code, resp.content) return urljoin(self.client.url, url)
[ "def", "create_url", "(", "self", ")", ":", "headers", "=", "self", ".", "headers", "headers", "[", "'upload-length'", "]", "=", "str", "(", "self", ".", "file_size", ")", "headers", "[", "'upload-metadata'", "]", "=", "','", ".", "join", "(", "self", ".", "encode_metadata", "(", ")", ")", "resp", "=", "requests", ".", "post", "(", "self", ".", "client", ".", "url", ",", "headers", "=", "headers", ")", "url", "=", "resp", ".", "headers", ".", "get", "(", "\"location\"", ")", "if", "url", "is", "None", ":", "msg", "=", "'Attempt to retrieve create file url with status {}'", ".", "format", "(", "resp", ".", "status_code", ")", "raise", "TusCommunicationError", "(", "msg", ",", "resp", ".", "status_code", ",", "resp", ".", "content", ")", "return", "urljoin", "(", "self", ".", "client", ".", "url", ",", "url", ")" ]
Return upload url. Makes request to tus server to create a new upload url for the required file upload.
[ "Return", "upload", "url", "." ]
train
https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/uploader.py#L219-L233
tus/tus-py-client
tusclient/uploader.py
Uploader.request_length
def request_length(self): """ Return length of next chunk upload. """ remainder = self.stop_at - self.offset return self.chunk_size if remainder > self.chunk_size else remainder
python
def request_length(self): remainder = self.stop_at - self.offset return self.chunk_size if remainder > self.chunk_size else remainder
[ "def", "request_length", "(", "self", ")", ":", "remainder", "=", "self", ".", "stop_at", "-", "self", ".", "offset", "return", "self", ".", "chunk_size", "if", "remainder", ">", "self", ".", "chunk_size", "else", "remainder" ]
Return length of next chunk upload.
[ "Return", "length", "of", "next", "chunk", "upload", "." ]
train
https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/uploader.py#L236-L241
tus/tus-py-client
tusclient/uploader.py
Uploader.verify_upload
def verify_upload(self): """ Confirm that the last upload was sucessful. Raises TusUploadFailed exception if the upload was not sucessful. """ if self.request.status_code == 204: return True else: raise TusUploadFailed('', self.request.status_code, self.request.response_content)
python
def verify_upload(self): if self.request.status_code == 204: return True else: raise TusUploadFailed('', self.request.status_code, self.request.response_content)
[ "def", "verify_upload", "(", "self", ")", ":", "if", "self", ".", "request", ".", "status_code", "==", "204", ":", "return", "True", "else", ":", "raise", "TusUploadFailed", "(", "''", ",", "self", ".", "request", ".", "status_code", ",", "self", ".", "request", ".", "response_content", ")" ]
Confirm that the last upload was sucessful. Raises TusUploadFailed exception if the upload was not sucessful.
[ "Confirm", "that", "the", "last", "upload", "was", "sucessful", ".", "Raises", "TusUploadFailed", "exception", "if", "the", "upload", "was", "not", "sucessful", "." ]
train
https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/uploader.py#L243-L251
tus/tus-py-client
tusclient/uploader.py
Uploader.get_file_stream
def get_file_stream(self): """ Return a file stream instance of the upload. """ if self.file_stream: self.file_stream.seek(0) return self.file_stream elif os.path.isfile(self.file_path): return open(self.file_path, 'rb') else: raise ValueError("invalid file {}".format(self.file_path))
python
def get_file_stream(self): if self.file_stream: self.file_stream.seek(0) return self.file_stream elif os.path.isfile(self.file_path): return open(self.file_path, 'rb') else: raise ValueError("invalid file {}".format(self.file_path))
[ "def", "get_file_stream", "(", "self", ")", ":", "if", "self", ".", "file_stream", ":", "self", ".", "file_stream", ".", "seek", "(", "0", ")", "return", "self", ".", "file_stream", "elif", "os", ".", "path", ".", "isfile", "(", "self", ".", "file_path", ")", ":", "return", "open", "(", "self", ".", "file_path", ",", "'rb'", ")", "else", ":", "raise", "ValueError", "(", "\"invalid file {}\"", ".", "format", "(", "self", ".", "file_path", ")", ")" ]
Return a file stream instance of the upload.
[ "Return", "a", "file", "stream", "instance", "of", "the", "upload", "." ]
train
https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/uploader.py#L253-L263
tus/tus-py-client
tusclient/uploader.py
Uploader.file_size
def file_size(self): """ Return size of the file. """ stream = self.get_file_stream() stream.seek(0, os.SEEK_END) return stream.tell()
python
def file_size(self): stream = self.get_file_stream() stream.seek(0, os.SEEK_END) return stream.tell()
[ "def", "file_size", "(", "self", ")", ":", "stream", "=", "self", ".", "get_file_stream", "(", ")", "stream", ".", "seek", "(", "0", ",", "os", ".", "SEEK_END", ")", "return", "stream", ".", "tell", "(", ")" ]
Return size of the file.
[ "Return", "size", "of", "the", "file", "." ]
train
https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/uploader.py#L266-L272
tus/tus-py-client
tusclient/uploader.py
Uploader.upload
def upload(self, stop_at=None): """ Perform file upload. Performs continous upload of chunks of the file. The size uploaded at each cycle is the value of the attribute 'chunk_size'. :Args: - stop_at (Optional[int]): Determines at what offset value the upload should stop. If not specified this defaults to the file size. """ self.stop_at = stop_at or self.file_size while self.offset < self.stop_at: self.upload_chunk() else: if self.log_func: self.log_func("maximum upload specified({} bytes) has been reached".format(self.stop_at))
python
def upload(self, stop_at=None): self.stop_at = stop_at or self.file_size while self.offset < self.stop_at: self.upload_chunk() else: if self.log_func: self.log_func("maximum upload specified({} bytes) has been reached".format(self.stop_at))
[ "def", "upload", "(", "self", ",", "stop_at", "=", "None", ")", ":", "self", ".", "stop_at", "=", "stop_at", "or", "self", ".", "file_size", "while", "self", ".", "offset", "<", "self", ".", "stop_at", ":", "self", ".", "upload_chunk", "(", ")", "else", ":", "if", "self", ".", "log_func", ":", "self", ".", "log_func", "(", "\"maximum upload specified({} bytes) has been reached\"", ".", "format", "(", "self", ".", "stop_at", ")", ")" ]
Perform file upload. Performs continous upload of chunks of the file. The size uploaded at each cycle is the value of the attribute 'chunk_size'. :Args: - stop_at (Optional[int]): Determines at what offset value the upload should stop. If not specified this defaults to the file size.
[ "Perform", "file", "upload", "." ]
train
https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/uploader.py#L274-L292
tus/tus-py-client
tusclient/uploader.py
Uploader.upload_chunk
def upload_chunk(self): """ Upload chunk of file. """ self._retried = 0 self._do_request() self.offset = int(self.request.response_headers.get('upload-offset')) if self.log_func: msg = '{} bytes uploaded ...'.format(self.offset) self.log_func(msg)
python
def upload_chunk(self): self._retried = 0 self._do_request() self.offset = int(self.request.response_headers.get('upload-offset')) if self.log_func: msg = '{} bytes uploaded ...'.format(self.offset) self.log_func(msg)
[ "def", "upload_chunk", "(", "self", ")", ":", "self", ".", "_retried", "=", "0", "self", ".", "_do_request", "(", ")", "self", ".", "offset", "=", "int", "(", "self", ".", "request", ".", "response_headers", ".", "get", "(", "'upload-offset'", ")", ")", "if", "self", ".", "log_func", ":", "msg", "=", "'{} bytes uploaded ...'", ".", "format", "(", "self", ".", "offset", ")", "self", ".", "log_func", "(", "msg", ")" ]
Upload chunk of file.
[ "Upload", "chunk", "of", "file", "." ]
train
https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/uploader.py#L294-L303
tus/tus-py-client
tusclient/storage/filestorage.py
FileStorage.get_item
def get_item(self, key): """ Return the tus url of a file, identified by the key specified. :Args: - key[str]: The unique id for the stored item (in this case, url) :Returns: url[str] """ result = self._db.search(self._urls.key == key) return result[0].get('url') if result else None
python
def get_item(self, key): result = self._db.search(self._urls.key == key) return result[0].get('url') if result else None
[ "def", "get_item", "(", "self", ",", "key", ")", ":", "result", "=", "self", ".", "_db", ".", "search", "(", "self", ".", "_urls", ".", "key", "==", "key", ")", "return", "result", "[", "0", "]", ".", "get", "(", "'url'", ")", "if", "result", "else", "None" ]
Return the tus url of a file, identified by the key specified. :Args: - key[str]: The unique id for the stored item (in this case, url) :Returns: url[str]
[ "Return", "the", "tus", "url", "of", "a", "file", "identified", "by", "the", "key", "specified", "." ]
train
https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/storage/filestorage.py#L14-L23
tus/tus-py-client
tusclient/storage/filestorage.py
FileStorage.set_item
def set_item(self, key, url): """ Store the url value under the unique key. :Args: - key[str]: The unique id to which the item (in this case, url) would be stored. - value[str]: The actual url value to be stored. """ if self._db.search(self._urls.key == key): self._db.update({'url': url}, self._urls.key == key) else: self._db.insert({'key': key, 'url': url})
python
def set_item(self, key, url): if self._db.search(self._urls.key == key): self._db.update({'url': url}, self._urls.key == key) else: self._db.insert({'key': key, 'url': url})
[ "def", "set_item", "(", "self", ",", "key", ",", "url", ")", ":", "if", "self", ".", "_db", ".", "search", "(", "self", ".", "_urls", ".", "key", "==", "key", ")", ":", "self", ".", "_db", ".", "update", "(", "{", "'url'", ":", "url", "}", ",", "self", ".", "_urls", ".", "key", "==", "key", ")", "else", ":", "self", ".", "_db", ".", "insert", "(", "{", "'key'", ":", "key", ",", "'url'", ":", "url", "}", ")" ]
Store the url value under the unique key. :Args: - key[str]: The unique id to which the item (in this case, url) would be stored. - value[str]: The actual url value to be stored.
[ "Store", "the", "url", "value", "under", "the", "unique", "key", "." ]
train
https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/storage/filestorage.py#L25-L36
tus/tus-py-client
tusclient/storage/filestorage.py
FileStorage.remove_item
def remove_item(self, key): """ Remove/Delete the url value under the unique key from storage. """ self._db.remove(self._urls.key==key)
python
def remove_item(self, key): self._db.remove(self._urls.key==key)
[ "def", "remove_item", "(", "self", ",", "key", ")", ":", "self", ".", "_db", ".", "remove", "(", "self", ".", "_urls", ".", "key", "==", "key", ")" ]
Remove/Delete the url value under the unique key from storage.
[ "Remove", "/", "Delete", "the", "url", "value", "under", "the", "unique", "key", "from", "storage", "." ]
train
https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/storage/filestorage.py#L38-L42
tus/tus-py-client
tusclient/request.py
TusRequest.perform
def perform(self): """ Perform actual request. """ try: host = '{}://{}'.format(self._url.scheme, self._url.netloc) path = self._url.geturl().replace(host, '', 1) chunk = self.file.read(self._content_length) if self._upload_checksum: self._request_headers["upload-checksum"] = \ " ".join(( self._checksum_algorithm_name, base64.b64encode( self._checksum_algorithm(chunk).digest() ).decode("ascii"), )) self.handle.request("PATCH", path, chunk, self._request_headers) self._response = self.handle.getresponse() self.status_code = self._response.status self.response_headers = {k.lower(): v for k, v in self._response.getheaders()} except http.client.HTTPException as e: raise TusUploadFailed(e) # wrap connection related errors not raised by the http.client.HTTP(S)Connection # as TusUploadFailed exceptions to enable retries except OSError as e: if e.errno in (errno.EPIPE, errno.ESHUTDOWN, errno.ECONNABORTED, errno.ECONNREFUSED, errno.ECONNRESET): raise TusUploadFailed(e) raise e
python
def perform(self): try: host = '{}://{}'.format(self._url.scheme, self._url.netloc) path = self._url.geturl().replace(host, '', 1) chunk = self.file.read(self._content_length) if self._upload_checksum: self._request_headers["upload-checksum"] = \ " ".join(( self._checksum_algorithm_name, base64.b64encode( self._checksum_algorithm(chunk).digest() ).decode("ascii"), )) self.handle.request("PATCH", path, chunk, self._request_headers) self._response = self.handle.getresponse() self.status_code = self._response.status self.response_headers = {k.lower(): v for k, v in self._response.getheaders()} except http.client.HTTPException as e: raise TusUploadFailed(e) except OSError as e: if e.errno in (errno.EPIPE, errno.ESHUTDOWN, errno.ECONNABORTED, errno.ECONNREFUSED, errno.ECONNRESET): raise TusUploadFailed(e) raise e
[ "def", "perform", "(", "self", ")", ":", "try", ":", "host", "=", "'{}://{}'", ".", "format", "(", "self", ".", "_url", ".", "scheme", ",", "self", ".", "_url", ".", "netloc", ")", "path", "=", "self", ".", "_url", ".", "geturl", "(", ")", ".", "replace", "(", "host", ",", "''", ",", "1", ")", "chunk", "=", "self", ".", "file", ".", "read", "(", "self", ".", "_content_length", ")", "if", "self", ".", "_upload_checksum", ":", "self", ".", "_request_headers", "[", "\"upload-checksum\"", "]", "=", "\" \"", ".", "join", "(", "(", "self", ".", "_checksum_algorithm_name", ",", "base64", ".", "b64encode", "(", "self", ".", "_checksum_algorithm", "(", "chunk", ")", ".", "digest", "(", ")", ")", ".", "decode", "(", "\"ascii\"", ")", ",", ")", ")", "self", ".", "handle", ".", "request", "(", "\"PATCH\"", ",", "path", ",", "chunk", ",", "self", ".", "_request_headers", ")", "self", ".", "_response", "=", "self", ".", "handle", ".", "getresponse", "(", ")", "self", ".", "status_code", "=", "self", ".", "_response", ".", "status", "self", ".", "response_headers", "=", "{", "k", ".", "lower", "(", ")", ":", "v", "for", "k", ",", "v", "in", "self", ".", "_response", ".", "getheaders", "(", ")", "}", "except", "http", ".", "client", ".", "HTTPException", "as", "e", ":", "raise", "TusUploadFailed", "(", "e", ")", "# wrap connection related errors not raised by the http.client.HTTP(S)Connection", "# as TusUploadFailed exceptions to enable retries", "except", "OSError", "as", "e", ":", "if", "e", ".", "errno", "in", "(", "errno", ".", "EPIPE", ",", "errno", ".", "ESHUTDOWN", ",", "errno", ".", "ECONNABORTED", ",", "errno", ".", "ECONNREFUSED", ",", "errno", ".", "ECONNRESET", ")", ":", "raise", "TusUploadFailed", "(", "e", ")", "raise", "e" ]
Perform actual request.
[ "Perform", "actual", "request", "." ]
train
https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/request.py#L56-L84
tus/tus-py-client
tusclient/fingerprint/fingerprint.py
Fingerprint.get_fingerprint
def get_fingerprint(self, fs): """ Return a unique fingerprint string value based on the file stream recevied :Args: - fs[file]: The file stream instance of the file for which a fingerprint would be generated. :Returns: fingerprint[str] """ hasher = hashlib.md5() # we encode the content to avoid python 3 uncicode errors buf = self._encode_data(fs.read(self.BLOCK_SIZE)) while len(buf) > 0: hasher.update(buf) buf = fs.read(self.BLOCK_SIZE) return 'md5:' + hasher.hexdigest()
python
def get_fingerprint(self, fs): hasher = hashlib.md5() buf = self._encode_data(fs.read(self.BLOCK_SIZE)) while len(buf) > 0: hasher.update(buf) buf = fs.read(self.BLOCK_SIZE) return 'md5:' + hasher.hexdigest()
[ "def", "get_fingerprint", "(", "self", ",", "fs", ")", ":", "hasher", "=", "hashlib", ".", "md5", "(", ")", "# we encode the content to avoid python 3 uncicode errors", "buf", "=", "self", ".", "_encode_data", "(", "fs", ".", "read", "(", "self", ".", "BLOCK_SIZE", ")", ")", "while", "len", "(", "buf", ")", ">", "0", ":", "hasher", ".", "update", "(", "buf", ")", "buf", "=", "fs", ".", "read", "(", "self", ".", "BLOCK_SIZE", ")", "return", "'md5:'", "+", "hasher", ".", "hexdigest", "(", ")" ]
Return a unique fingerprint string value based on the file stream recevied :Args: - fs[file]: The file stream instance of the file for which a fingerprint would be generated. :Returns: fingerprint[str]
[ "Return", "a", "unique", "fingerprint", "string", "value", "based", "on", "the", "file", "stream", "recevied" ]
train
https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/fingerprint/fingerprint.py#L15-L29
Yelp/threat_intel
threat_intel/util/http.py
SSLAdapter.init_poolmanager
def init_poolmanager(self, connections, maxsize, block=False, **pool_kwargs): """Called to initialize the HTTPAdapter when no proxy is used.""" try: pool_kwargs['ssl_version'] = ssl.PROTOCOL_TLS except AttributeError: pool_kwargs['ssl_version'] = ssl.PROTOCOL_SSLv23 return super(SSLAdapter, self).init_poolmanager(connections, maxsize, block, **pool_kwargs)
python
def init_poolmanager(self, connections, maxsize, block=False, **pool_kwargs): try: pool_kwargs['ssl_version'] = ssl.PROTOCOL_TLS except AttributeError: pool_kwargs['ssl_version'] = ssl.PROTOCOL_SSLv23 return super(SSLAdapter, self).init_poolmanager(connections, maxsize, block, **pool_kwargs)
[ "def", "init_poolmanager", "(", "self", ",", "connections", ",", "maxsize", ",", "block", "=", "False", ",", "*", "*", "pool_kwargs", ")", ":", "try", ":", "pool_kwargs", "[", "'ssl_version'", "]", "=", "ssl", ".", "PROTOCOL_TLS", "except", "AttributeError", ":", "pool_kwargs", "[", "'ssl_version'", "]", "=", "ssl", ".", "PROTOCOL_SSLv23", "return", "super", "(", "SSLAdapter", ",", "self", ")", ".", "init_poolmanager", "(", "connections", ",", "maxsize", ",", "block", ",", "*", "*", "pool_kwargs", ")" ]
Called to initialize the HTTPAdapter when no proxy is used.
[ "Called", "to", "initialize", "the", "HTTPAdapter", "when", "no", "proxy", "is", "used", "." ]
train
https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/util/http.py#L51-L57
Yelp/threat_intel
threat_intel/util/http.py
SSLAdapter.proxy_manager_for
def proxy_manager_for(self, proxy, **proxy_kwargs): """Called to initialize the HTTPAdapter when a proxy is used.""" try: proxy_kwargs['ssl_version'] = ssl.PROTOCOL_TLS except AttributeError: proxy_kwargs['ssl_version'] = ssl.PROTOCOL_SSLv23 return super(SSLAdapter, self).proxy_manager_for(proxy, **proxy_kwargs)
python
def proxy_manager_for(self, proxy, **proxy_kwargs): try: proxy_kwargs['ssl_version'] = ssl.PROTOCOL_TLS except AttributeError: proxy_kwargs['ssl_version'] = ssl.PROTOCOL_SSLv23 return super(SSLAdapter, self).proxy_manager_for(proxy, **proxy_kwargs)
[ "def", "proxy_manager_for", "(", "self", ",", "proxy", ",", "*", "*", "proxy_kwargs", ")", ":", "try", ":", "proxy_kwargs", "[", "'ssl_version'", "]", "=", "ssl", ".", "PROTOCOL_TLS", "except", "AttributeError", ":", "proxy_kwargs", "[", "'ssl_version'", "]", "=", "ssl", ".", "PROTOCOL_SSLv23", "return", "super", "(", "SSLAdapter", ",", "self", ")", ".", "proxy_manager_for", "(", "proxy", ",", "*", "*", "proxy_kwargs", ")" ]
Called to initialize the HTTPAdapter when a proxy is used.
[ "Called", "to", "initialize", "the", "HTTPAdapter", "when", "a", "proxy", "is", "used", "." ]
train
https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/util/http.py#L59-L65
Yelp/threat_intel
threat_intel/util/http.py
RateLimiter.make_calls
def make_calls(self, num_calls=1): """Adds appropriate sleep to avoid making too many calls. Args: num_calls: int the number of calls which will be made """ self._cull() while self._outstanding_calls + num_calls > self._max_calls_per_second: time.sleep(0) # yield self._cull() self._call_times.append(self.CallRecord(time=time.time(), num_calls=num_calls)) self._outstanding_calls += num_calls
python
def make_calls(self, num_calls=1): self._cull() while self._outstanding_calls + num_calls > self._max_calls_per_second: time.sleep(0) self._cull() self._call_times.append(self.CallRecord(time=time.time(), num_calls=num_calls)) self._outstanding_calls += num_calls
[ "def", "make_calls", "(", "self", ",", "num_calls", "=", "1", ")", ":", "self", ".", "_cull", "(", ")", "while", "self", ".", "_outstanding_calls", "+", "num_calls", ">", "self", ".", "_max_calls_per_second", ":", "time", ".", "sleep", "(", "0", ")", "# yield", "self", ".", "_cull", "(", ")", "self", ".", "_call_times", ".", "append", "(", "self", ".", "CallRecord", "(", "time", "=", "time", ".", "time", "(", ")", ",", "num_calls", "=", "num_calls", ")", ")", "self", ".", "_outstanding_calls", "+=", "num_calls" ]
Adds appropriate sleep to avoid making too many calls. Args: num_calls: int the number of calls which will be made
[ "Adds", "appropriate", "sleep", "to", "avoid", "making", "too", "many", "calls", "." ]
train
https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/util/http.py#L79-L91
Yelp/threat_intel
threat_intel/util/http.py
RateLimiter._cull
def _cull(self): """Remove calls more than 1 second old from the queue.""" right_now = time.time() cull_from = -1 for index in range(len(self._call_times)): if right_now - self._call_times[index].time >= 1.0: cull_from = index self._outstanding_calls -= self._call_times[index].num_calls else: break if cull_from > -1: self._call_times = self._call_times[cull_from + 1:]
python
def _cull(self): right_now = time.time() cull_from = -1 for index in range(len(self._call_times)): if right_now - self._call_times[index].time >= 1.0: cull_from = index self._outstanding_calls -= self._call_times[index].num_calls else: break if cull_from > -1: self._call_times = self._call_times[cull_from + 1:]
[ "def", "_cull", "(", "self", ")", ":", "right_now", "=", "time", ".", "time", "(", ")", "cull_from", "=", "-", "1", "for", "index", "in", "range", "(", "len", "(", "self", ".", "_call_times", ")", ")", ":", "if", "right_now", "-", "self", ".", "_call_times", "[", "index", "]", ".", "time", ">=", "1.0", ":", "cull_from", "=", "index", "self", ".", "_outstanding_calls", "-=", "self", ".", "_call_times", "[", "index", "]", ".", "num_calls", "else", ":", "break", "if", "cull_from", ">", "-", "1", ":", "self", ".", "_call_times", "=", "self", ".", "_call_times", "[", "cull_from", "+", "1", ":", "]" ]
Remove calls more than 1 second old from the queue.
[ "Remove", "calls", "more", "than", "1", "second", "old", "from", "the", "queue", "." ]
train
https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/util/http.py#L93-L106