repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
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): """Get the color of a given pixel""" 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", "]", ">>"...
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 ...
python
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 ...
[ "def", "fill_rect", "(", "framebuf", ",", "x", ",", "y", ",", "width", ",", "height", ",", "color", ")", ":", "# pylint: disable=too-many-arguments", "while", "height", ">", "0", ":", "index", "=", "(", "y", ">>", "3", ")", "*", "framebuf", ".", "strid...
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): """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)
[ "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"...
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: ...
python
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: ...
[ "def", "pixel", "(", "self", ",", "x", ",", "y", ",", "color", "=", "None", ")", ":", "if", "self", ".", "rotation", "==", "1", ":", "x", ",", "y", "=", "y", ",", "x", "x", "=", "self", ".", "width", "-", "x", "-", "1", "if", "self", ".",...
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): """Draw a horizontal line up to a given length.""" 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): """Draw a vertical line up to a given length.""" 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 = hei...
python
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 = hei...
[ "def", "rect", "(", "self", ",", "x", ",", "y", ",", "width", ",", "height", ",", "color", ",", "*", ",", "fill", "=", "False", ")", ":", "# pylint: disable=too-many-arguments", "if", "self", ".", "rotation", "==", "1", ":", "x", ",", "y", "=", "y"...
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: e...
python
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: e...
[ "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", ",", ...
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 <...
python
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 <...
[ "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", "...
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(st...
python
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(st...
[ "def", "text", "(", "self", ",", "string", ",", "x", ",", "y", ",", "color", ",", "*", ",", "font_name", "=", "\"font5x8.bin\"", ")", ":", "if", "not", "self", ".", "_font", "or", "self", ".", "_font", ".", "font_name", "!=", "font_name", ":", "# l...
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.w...
python
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.w...
[ "def", "image", "(", "self", ",", "img", ")", ":", "if", "img", ".", "mode", "!=", "'1'", ":", "raise", "ValueError", "(", "'Image must be in mode 1.'", ")", "imwidth", ",", "imheight", "=", "img", ".", "size", "if", "imwidth", "!=", "self", ".", "widt...
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...
python
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...
[ "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 \...
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='Mis...
python
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='Mis...
[ "def", "parse_auth_token_from_request", "(", "self", ",", "auth_header", ")", ":", "if", "not", "auth_header", ":", "raise", "falcon", ".", "HTTPUnauthorized", "(", "description", "=", "'Missing Authorization Header'", ")", "parts", "=", "auth_header", ".", "split",...
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) ...
python
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) ...
[ "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_heade...
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._decod...
python
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._decod...
[ "def", "authenticate", "(", "self", ",", "req", ",", "resp", ",", "resource", ")", ":", "payload", "=", "self", ".", "_decode_jwt_token", "(", "req", ")", "user", "=", "self", ".", "user_loader", "(", "payload", ")", "if", "not", "user", ":", "raise", ...
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", "...
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...
python
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...
[ "def", "get_auth_token", "(", "self", ",", "user_payload", ")", ":", "now", "=", "datetime", ".", "utcnow", "(", ")", "payload", "=", "{", "'user'", ":", "user_payload", "}", "if", "'iat'", "in", "self", ".", "verify_claims", ":", "payload", "[", "'iat'"...
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` """ usernam...
python
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` """ usernam...
[ "def", "authenticate", "(", "self", ",", "req", ",", "resp", ",", "resource", ")", ":", "username", ",", "password", "=", "self", ".", "_extract_credentials", "(", "req", ")", "user", "=", "self", ".", "user_loader", "(", "username", ",", "password", ")"...
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", ...
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 ...
python
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 ...
[ "def", "get_auth_token", "(", "self", ",", "user_payload", ")", ":", "username", "=", "user_payload", ".", "get", "(", "'username'", ")", "or", "None", "password", "=", "user_payload", ".", "get", "(", "'password'", ")", "or", "None", "if", "not", "usernam...
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( ...
python
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( ...
[ "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", "...
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( ...
python
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( ...
[ "def", "parse_auth_token_from_request", "(", "self", ",", "auth_header", ")", ":", "if", "not", "auth_header", ":", "raise", "falcon", ".", "HTTPUnauthorized", "(", "description", "=", "'Missing Authorization Header'", ")", "try", ":", "auth_header_prefix", ",", "_"...
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.setStyleShee...
python
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.setStyleShee...
[ "def", "_apply_base_theme", "(", "app", ")", ":", "if", "QT_VERSION", "<", "(", "5", ",", ")", ":", "app", ".", "setStyle", "(", "'plastique'", ")", "else", ":", "app", ".", "setStyle", "(", "'Fusion'", ")", "with", "open", "(", "_STYLESHEET", ")", "...
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(QPalet...
python
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(QPalet...
[ "def", "dark", "(", "app", ")", ":", "_apply_base_theme", "(", "app", ")", "darkPalette", "=", "QPalette", "(", ")", "# base", "darkPalette", ".", "setColor", "(", "QPalette", ".", "WindowText", ",", "QColor", "(", "180", ",", "180", ",", "180", ")", "...
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)...
python
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)...
[ "def", "pkgconfig", "(", "*", "packages", ",", "*", "*", "kw", ")", ":", "flag_map", "=", "{", "'-I'", ":", "'include_dirs'", ",", "'-L'", ":", "'library_dirs'", ",", "'-l'", ":", "'libraries'", "}", "output", "=", "sp", ".", "Popen", "(", "[", "\"pk...
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() c...
python
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() c...
[ "def", "inheritance_diagram_directive", "(", "name", ",", "arguments", ",", "options", ",", "content", ",", "lineno", ",", "content_offset", ",", "block_text", ",", "state", ",", "state_machine", ")", ":", "node", "=", "inheritance_diagram", "(", ")", "class_nam...
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(set...
python
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(set...
[ "def", "html_output_graph", "(", "self", ",", "node", ")", ":", "graph", "=", "node", "[", "'graph'", "]", "parts", "=", "node", "[", "'parts'", "]", "graph_hash", "=", "get_graph_hash", "(", "node", ")", "name", "=", "\"inheritance%s\"", "%", "graph_hash"...
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'...
python
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'...
[ "def", "latex_output_graph", "(", "self", ",", "node", ")", ":", "graph", "=", "node", "[", "'graph'", "]", "parts", "=", "node", "[", "'parts'", "]", "graph_hash", "=", "get_graph_hash", "(", "node", ")", "name", "=", "\"inheritance%s\"", "%", "graph_hash...
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...
python
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...
[ "def", "visit_inheritance_diagram", "(", "inner_func", ")", ":", "def", "visitor", "(", "self", ",", "node", ")", ":", "try", ":", "content", "=", "inner_func", "(", "self", ",", "node", ")", "except", "DotException", ",", "e", ":", "# Insert the exception a...
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 diagra...
python
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 diagra...
[ "def", "_import_class_or_module", "(", "self", ",", "name", ")", ":", "try", ":", "path", ",", "base", "=", "self", ".", "py_sig_re", ".", "match", "(", "name", ")", ".", "groups", "(", ")", "except", ":", "raise", "ValueError", "(", "\"Invalid class or ...
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): """ Import a list of classes. """ 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(...
python
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(...
[ "def", "_all_classes", "(", "self", ",", "classes", ")", ":", "all_classes", "=", "{", "}", "def", "recurse", "(", "cls", ")", ":", "all_classes", "[", "cls", "]", "=", "None", "for", "c", "in", "cls", ".", "__bases__", ":", "if", "c", "not", "in",...
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. *...
python
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. *...
[ "def", "generate_dot", "(", "self", ",", "fd", ",", "name", ",", "parts", "=", "0", ",", "urls", "=", "{", "}", ",", "graph_options", "=", "{", "}", ",", "node_options", "=", "{", "}", ",", "edge_options", "=", "{", "}", ")", ":", "g_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 d...
[ "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 th...
python
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 th...
[ "def", "run_dot", "(", "self", ",", "args", ",", "name", ",", "parts", "=", "0", ",", "urls", "=", "{", "}", ",", "graph_options", "=", "{", "}", ",", "node_options", "=", "{", "}", ",", "edge_options", "=", "{", "}", ")", ":", "try", ":", "dot...
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 ...
[ "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...
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): """ Minimize a function using ipopt. The call signature is exactly like for `scipy.optimize.mimize`. In options, all options...
[ "def", "minimize_ipopt", "(", "fun", ",", "x0", ",", "args", "=", "(", ")", ",", "kwargs", "=", "None", ",", "method", "=", "None", ",", "jac", "=", "None", ",", "hess", "=", "None", ",", "hessp", "=", "None", ",", "bounds", "=", "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-...
[ "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", "[", ...
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 environmen...
python
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 environmen...
[ "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", ":", "# m...
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): """The number of documents deleted.""" 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(): """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"")
[ "def", "generate_id", "(", ")", ":", "# TODO: Use six.string_type to Py3 compat", "try", ":", "return", "unicode", "(", "uuid1", "(", ")", ")", ".", "replace", "(", "u\"-\"", ",", "u\"\"", ")", "except", "NameError", ":", "return", "str", "(", "uuid1", "(", ...
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): """ Builds a new tinydb table at the parent database :return: """ 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 ex...
python
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 ex...
[ "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"...
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): """Backwards compatibility with insert""" 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", ...
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...
python
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...
[ "def", "insert_one", "(", "self", ",", "doc", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "table", "is", "None", ":", "self", ".", "build_table", "(", ")", "if", "not", "isinstance", "(", "doc", ",", "dict", ")", ":", ...
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 V...
python
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 V...
[ "def", "insert_many", "(", "self", ",", "docs", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "table", "is", "None", ":", "self", ".", "build_table", "(", ")", "if", "not", "isinstance", "(", "docs", ",", "list", ")", ":...
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 shou...
python
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 shou...
[ "def", "parse_query", "(", "self", ",", "query", ")", ":", "logger", ".", "debug", "(", "u'query to parse2: {}'", ".", "format", "(", "query", ")", ")", "# this should find all records", "if", "query", "==", "{", "}", "or", "query", "is", "None", ":", "ret...
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 w...
python
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 w...
[ "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",...
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,...
python
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,...
[ "def", "update", "(", "self", ",", "query", ",", "doc", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "doc", ",", "list", ")", ":", "return", "[", "self", ".", "update_one", "(", "query", ",", "item", ",", "*", "...
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_ta...
python
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_ta...
[ "def", "update_one", "(", "self", ",", "query", ",", "doc", ")", ":", "if", "self", ".", "table", "is", "None", ":", "self", ".", "build_table", "(", ")", "if", "u\"$set\"", "in", "doc", ":", "doc", "=", "doc", "[", "u\"$set\"", "]", "allcond", "="...
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.bui...
python
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.bui...
[ "def", "find", "(", "self", ",", "filter", "=", "None", ",", "sort", "=", "None", ",", "skip", "=", "None", ",", "limit", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "table", "is", "None", ":", "self", ...
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) ...
python
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) ...
[ "def", "find_one", "(", "self", ",", "filter", "=", "None", ")", ":", "if", "self", ".", "table", "is", "None", ":", "self", ".", "build_table", "(", ")", "allcond", "=", "self", ".", "parse_query", "(", "filter", ")", "return", "self", ".", "table",...
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): """Backwards compatibility with remove""" 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", "(...
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 DeleteR...
python
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 DeleteR...
[ "def", "delete_one", "(", "self", ",", "query", ")", ":", "item", "=", "self", ".", "find_one", "(", "query", ")", "result", "=", "self", ".", "table", ".", "remove", "(", "where", "(", "u'_id'", ")", "==", "item", "[", "u'_id'", "]", ")", "return"...
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']) ...
python
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']) ...
[ "def", "delete_many", "(", "self", ",", "query", ")", ":", "items", "=", "self", ".", "find", "(", "query", ")", "result", "=", "[", "self", ".", "table", ".", "remove", "(", "where", "(", "u'_id'", ")", "==", "item", "[", "u'_id'", "]", ")", "fo...
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 ...
python
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 ...
[ "def", "paginate", "(", "self", ",", "skip", ",", "limit", ")", ":", "if", "not", "self", ".", "count", "(", ")", "or", "not", "limit", ":", "return", "skip", "=", "skip", "or", "0", "pages", "=", "int", "(", "ceil", "(", "self", ".", "count", ...
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 ...
python
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 ...
[ "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", ...
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 ...
python
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 ...
[ "def", "sort", "(", "self", ",", "key_or_list", ",", "direction", "=", "None", ")", ":", "# checking input format", "sort_specifier", "=", "list", "(", ")", "if", "isinstance", "(", "key_or_list", ",", "list", ")", ":", "if", "direction", "is", "not", "Non...
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): """ 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
[ "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 = byte...
python
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 = byte...
[ "def", "display", "(", "self", ",", "image", ")", ":", "assert", "(", "image", ".", "mode", "==", "self", ".", "mode", ")", "assert", "(", "image", ".", "size", "==", "self", ".", "size", ")", "image", "=", "self", ".", "preprocess", "(", "image", ...
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....
python
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....
[ "def", "display", "(", "self", ",", "image", ")", ":", "assert", "(", "image", ".", "mode", "==", "self", ".", "mode", ")", "assert", "(", "image", ".", "size", "==", "self", ".", "size", ")", "image", "=", "self", ".", "preprocess", "(", "image", ...
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 urllib...
python
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 urllib...
[ "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", ...
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 bo...
[ "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",...
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 cont...
python
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 cont...
[ "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", "...
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('...
python
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('...
[ "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...
python
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...
[ "def", "normalize_request_headers", "(", "request", ")", ":", "norm_headers", "=", "{", "}", "for", "header", ",", "value", "in", "request", ".", "META", ".", "items", "(", ")", ":", "if", "required_header", "(", "header", ")", ":", "norm_header", "=", "...
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: encode...
python
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: encode...
[ "def", "encode_items", "(", "items", ")", ":", "encoded", "=", "[", "]", "for", "key", ",", "values", "in", "items", ":", "for", "value", "in", "values", ":", "encoded", ".", "append", "(", "(", "key", ".", "encode", "(", "'utf-8'", ")", ",", "valu...
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 cooki...
python
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 cooki...
[ "def", "cookie_from_string", "(", "cookie_string", ",", "strict_cookies", "=", "False", ")", ":", "if", "strict_cookies", ":", "cookies", "=", "SimpleCookie", "(", "COOKIE_PREFIX", "+", "cookie_string", ")", "if", "not", "cookies", ".", "keys", "(", ")", ":", ...
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_co...
[ "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",...
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 valu...
python
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 valu...
[ "def", "unquote", "(", "value", ")", ":", "if", "len", "(", "value", ")", ">", "1", "and", "value", "[", "0", "]", "==", "'\"'", "and", "value", "[", "-", "1", "]", "==", "'\"'", ":", "value", "=", "value", "[", "1", ":", "-", "1", "]", "."...
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...
python
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...
[ "def", "asbool", "(", "value", ")", ":", "is_string", "=", "isinstance", "(", "value", ",", "string_types", ")", "if", "is_string", ":", "value", "=", "value", ".", "strip", "(", ")", ".", "lower", "(", ")", "if", "value", "in", "(", "'true'", ",", ...
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", "conv...
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...
python
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...
[ "def", "should_transform", "(", "self", ")", ":", "if", "not", "HAS_DIAZO", ":", "self", ".", "log", ".", "info", "(", "\"HAS_DIAZO: false\"", ")", "return", "False", "if", "asbool", "(", "self", ".", "request", ".", "META", ".", "get", "(", "DIAZO_OFF_R...
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 ...
python
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 ...
[ "def", "transform", "(", "self", ",", "rules", ",", "theme_template", ",", "is_html5", ",", "context_data", "=", "None", ")", ":", "if", "not", "self", ".", "should_transform", "(", ")", ":", "self", ".", "log", ".", "info", "(", "\"Don't need to be transf...
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: ...
[ "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): """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
[ "def", "set_html5_doctype", "(", "self", ")", ":", "doctype", "=", "b'<!DOCTYPE html>\\n'", "content", "=", "doctype_re", ".", "subn", "(", "doctype", ",", "self", ".", "response", ".", "content", ",", "1", ")", "[", "0", "]", "self", ".", "response", "....
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): """Host header should always be first""" 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", ".", "appe...
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 create...
python
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 create...
[ "def", "get_django_response", "(", "proxy_response", ",", "strict_cookies", "=", "False", ")", ":", "status", "=", "proxy_response", ".", "status", "headers", "=", "proxy_response", ".", "headers", "logger", ".", "debug", "(", "'Proxy response headers: %s'", ",", ...
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 :p...
[ "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",...
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...
python
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...
[ "def", "get_request_headers", "(", "self", ")", ":", "request_headers", "=", "self", ".", "get_proxy_request_headers", "(", "self", ".", "request", ")", "if", "(", "self", ".", "add_remote_user", "and", "hasattr", "(", "self", ".", "request", ",", "'user'", ...
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): """Return encoded query params to be used in proxied request""" 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:...
python
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:...
[ "def", "stream_download", "(", "url", ",", "target_path", ",", "verbose", "=", "False", ")", ":", "response", "=", "requests", ".", "get", "(", "url", ",", "stream", "=", "True", ")", "handle", "=", "open", "(", "target_path", ",", "\"wb\"", ")", "if",...
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): """ 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
[ "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...
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', ...
python
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', ...
[ "def", "_get_table_start", "(", "self", ")", ":", "if", "self", ".", "documentation", ":", "standardized_table_start", "=", "{", "'object_id'", ":", "{", "'value'", ":", "self", ".", "object_id", ",", "'ordering'", ":", "-", "1", ",", "'line_number'", ":", ...
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): """ 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
[ "def", "debracket", "(", "string", ")", ":", "result", "=", "re", ".", "sub", "(", "BRACKET_RE", ",", "';'", ",", "str", "(", "string", ")", ")", "result", "=", "result", ".", "lstrip", "(", "';'", ")", "result", "=", "result", ".", "lstrip", "(", ...
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.proc...
python
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.proc...
[ "def", "run_sked", "(", "self", ",", "object_id", ",", "sked", ",", "verbose", "=", "False", ")", ":", "self", ".", "whole_filing_data", "=", "[", "]", "self", ".", "filing_keyerr_data", "=", "[", "]", "this_filing", "=", "Filing", "(", "object_id", ")",...
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.pa...
python
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.pa...
[ "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", ".", "filepat...
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: ...
python
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: ...
[ "def", "_set_schedules", "(", "self", ")", ":", "self", ".", "schedules", "=", "[", "'ReturnHeader990x'", ",", "]", "self", ".", "otherforms", "=", "[", "]", "for", "sked", "in", "self", ".", "raw_irs_dict", "[", "'Return'", "]", "[", "'ReturnData'", "]"...
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.resu...
python
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.resu...
[ "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_ske...
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): """ 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)
[ "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): """ 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
[ "def", "headers_as_list", "(", "self", ")", ":", "headers", "=", "self", ".", "headers", "headers_list", "=", "[", "'{}: {}'", ".", "format", "(", "key", ",", "value", ")", "for", "key", ",", "value", "in", "iteritems", "(", "headers", ")", "]", "retur...
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.hea...
python
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.hea...
[ "def", "get_offset", "(", "self", ")", ":", "resp", "=", "requests", ".", "head", "(", "self", ".", "url", ",", "headers", "=", "self", ".", "headers", ")", "offset", "=", "resp", ".", "headers", ".", "get", "(", "'upload-offset'", ")", "if", "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 con...
python
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 con...
[ "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.", "# confir...
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.fing...
python
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.fing...
[ "def", "get_url", "(", "self", ")", ":", "if", "self", ".", "store_url", "and", "self", ".", "url_storage", ":", "key", "=", "self", ".", "fingerprinter", ".", "get_fingerprint", "(", "self", ".", "get_file_stream", "(", ")", ")", "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.
[ "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(...
python
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(...
[ "def", "create_url", "(", "self", ")", ":", "headers", "=", "self", ".", "headers", "headers", "[", "'upload-length'", "]", "=", "str", "(", "self", ".", "file_size", ")", "headers", "[", "'upload-metadata'", "]", "=", "','", ".", "join", "(", "self", ...
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): """ Return length of next chunk upload. """ 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,...
python
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,...
[ "def", "verify_upload", "(", "self", ")", ":", "if", "self", ".", "request", ".", "status_code", "==", "204", ":", "return", "True", "else", ":", "raise", "TusUploadFailed", "(", "''", ",", "self", ".", "request", ".", "status_code", ",", "self", ".", ...
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: ...
python
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: ...
[ "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 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): """ Return size of the file. """ 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 th...
python
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 th...
[ "def", "upload", "(", "self", ",", "stop_at", "=", "None", ")", ":", "self", ".", "stop_at", "=", "stop_at", "or", "self", ".", "file_size", "while", "self", ".", "offset", "<", "self", ".", "stop_at", ":", "self", ".", "upload_chunk", "(", ")", "els...
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 ...
[ "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_fu...
python
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_fu...
[ "def", "upload_chunk", "(", "self", ")", ":", "self", ".", "_retried", "=", "0", "self", ".", "_do_request", "(", ")", "self", ".", "offset", "=", "int", "(", "self", ".", "request", ".", "response_headers", ".", "get", "(", "'upload-offset'", ")", ")"...
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...
python
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...
[ "def", "get_item", "(", "self", ",", "key", ")", ":", "result", "=", "self", ".", "_db", ".", "search", "(", "self", ".", "_urls", ".", "key", "==", "key", ")", "return", "result", "[", "0", "]", ".", "get", "(", "'url'", ")", "if", "result", "...
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 == k...
python
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 == k...
[ "def", "set_item", "(", "self", ",", "key", ",", "url", ")", ":", "if", "self", ".", "_db", ".", "search", "(", "self", ".", "_urls", ".", "key", "==", "key", ")", ":", "self", ".", "_db", ".", "update", "(", "{", "'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): """ Remove/Delete the url value under the unique key from storage. """ 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: ...
python
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: ...
[ "def", "perform", "(", "self", ")", ":", "try", ":", "host", "=", "'{}://{}'", ".", "format", "(", "self", ".", "_url", ".", "scheme", ",", "self", ".", "_url", ".", "netloc", ")", "path", "=", "self", ".", "_url", ".", "geturl", "(", ")", ".", ...
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.m...
python
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.m...
[ "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_S...
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 ...
python
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 ...
[ "def", "init_poolmanager", "(", "self", ",", "connections", ",", "maxsize", ",", "block", "=", "False", ",", "*", "*", "pool_kwargs", ")", ":", "try", ":", "pool_kwargs", "[", "'ssl_version'", "]", "=", "ssl", ".", "PROTOCOL_TLS", "except", "AttributeError",...
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(SSLAdapte...
python
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(SSLAdapte...
[ "def", "proxy_manager_for", "(", "self", ",", "proxy", ",", "*", "*", "proxy_kwargs", ")", ":", "try", ":", "proxy_kwargs", "[", "'ssl_version'", "]", "=", "ssl", ".", "PROTOCOL_TLS", "except", "AttributeError", ":", "proxy_kwargs", "[", "'ssl_version'", "]", ...
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)...
python
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)...
[ "def", "make_calls", "(", "self", ",", "num_calls", "=", "1", ")", ":", "self", ".", "_cull", "(", ")", "while", "self", ".", "_outstanding_calls", "+", "num_calls", ">", "self", ".", "_max_calls_per_second", ":", "time", ".", "sleep", "(", "0", ")", "...
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._outstandin...
python
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._outstandin...
[ "def", "_cull", "(", "self", ")", ":", "right_now", "=", "time", ".", "time", "(", ")", "cull_from", "=", "-", "1", "for", "index", "in", "range", "(", "len", "(", "self", ".", "_call_times", ")", ")", ":", "if", "right_now", "-", "self", ".", "_...
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