repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
PyMySQL/PyMySQL
pymysql/cursors.py
Cursor.fetchall
def fetchall(self): """Fetch all the rows""" self._check_executed() if self._rows is None: return () if self.rownumber: result = self._rows[self.rownumber:] else: result = self._rows self.rownumber = len(self._rows) return resul...
python
def fetchall(self): """Fetch all the rows""" self._check_executed() if self._rows is None: return () if self.rownumber: result = self._rows[self.rownumber:] else: result = self._rows self.rownumber = len(self._rows) return resul...
[ "def", "fetchall", "(", "self", ")", ":", "self", ".", "_check_executed", "(", ")", "if", "self", ".", "_rows", "is", "None", ":", "return", "(", ")", "if", "self", ".", "rownumber", ":", "result", "=", "self", ".", "_rows", "[", "self", ".", "rown...
Fetch all the rows
[ "Fetch", "all", "the", "rows" ]
3674bc6fd064bf88524e839c07690e8c35223709
https://github.com/PyMySQL/PyMySQL/blob/3674bc6fd064bf88524e839c07690e8c35223709/pymysql/cursors.py#L292-L302
train
PyMySQL/PyMySQL
pymysql/cursors.py
SSCursor.fetchone
def fetchone(self): """Fetch next row""" self._check_executed() row = self.read_next() if row is None: return None self.rownumber += 1 return row
python
def fetchone(self): """Fetch next row""" self._check_executed() row = self.read_next() if row is None: return None self.rownumber += 1 return row
[ "def", "fetchone", "(", "self", ")", ":", "self", ".", "_check_executed", "(", ")", "row", "=", "self", ".", "read_next", "(", ")", "if", "row", "is", "None", ":", "return", "None", "self", ".", "rownumber", "+=", "1", "return", "row" ]
Fetch next row
[ "Fetch", "next", "row" ]
3674bc6fd064bf88524e839c07690e8c35223709
https://github.com/PyMySQL/PyMySQL/blob/3674bc6fd064bf88524e839c07690e8c35223709/pymysql/cursors.py#L437-L444
train
PyMySQL/PyMySQL
pymysql/cursors.py
SSCursor.fetchmany
def fetchmany(self, size=None): """Fetch many""" self._check_executed() if size is None: size = self.arraysize rows = [] for i in range_type(size): row = self.read_next() if row is None: break rows.append(row) ...
python
def fetchmany(self, size=None): """Fetch many""" self._check_executed() if size is None: size = self.arraysize rows = [] for i in range_type(size): row = self.read_next() if row is None: break rows.append(row) ...
[ "def", "fetchmany", "(", "self", ",", "size", "=", "None", ")", ":", "self", ".", "_check_executed", "(", ")", "if", "size", "is", "None", ":", "size", "=", "self", ".", "arraysize", "rows", "=", "[", "]", "for", "i", "in", "range_type", "(", "size...
Fetch many
[ "Fetch", "many" ]
3674bc6fd064bf88524e839c07690e8c35223709
https://github.com/PyMySQL/PyMySQL/blob/3674bc6fd064bf88524e839c07690e8c35223709/pymysql/cursors.py#L465-L478
train
PyMySQL/PyMySQL
pymysql/converters.py
convert_datetime
def convert_datetime(obj): """Returns a DATETIME or TIMESTAMP column value as a datetime object: >>> datetime_or_None('2007-02-25 23:06:20') datetime.datetime(2007, 2, 25, 23, 6, 20) >>> datetime_or_None('2007-02-25T23:06:20') datetime.datetime(2007, 2, 25, 23, 6, 20) Illegal values ar...
python
def convert_datetime(obj): """Returns a DATETIME or TIMESTAMP column value as a datetime object: >>> datetime_or_None('2007-02-25 23:06:20') datetime.datetime(2007, 2, 25, 23, 6, 20) >>> datetime_or_None('2007-02-25T23:06:20') datetime.datetime(2007, 2, 25, 23, 6, 20) Illegal values ar...
[ "def", "convert_datetime", "(", "obj", ")", ":", "if", "not", "PY2", "and", "isinstance", "(", "obj", ",", "(", "bytes", ",", "bytearray", ")", ")", ":", "obj", "=", "obj", ".", "decode", "(", "'ascii'", ")", "m", "=", "DATETIME_RE", ".", "match", ...
Returns a DATETIME or TIMESTAMP column value as a datetime object: >>> datetime_or_None('2007-02-25 23:06:20') datetime.datetime(2007, 2, 25, 23, 6, 20) >>> datetime_or_None('2007-02-25T23:06:20') datetime.datetime(2007, 2, 25, 23, 6, 20) Illegal values are returned as None: >>> dat...
[ "Returns", "a", "DATETIME", "or", "TIMESTAMP", "column", "value", "as", "a", "datetime", "object", ":" ]
3674bc6fd064bf88524e839c07690e8c35223709
https://github.com/PyMySQL/PyMySQL/blob/3674bc6fd064bf88524e839c07690e8c35223709/pymysql/converters.py#L167-L195
train
PyMySQL/PyMySQL
pymysql/converters.py
convert_timedelta
def convert_timedelta(obj): """Returns a TIME column as a timedelta object: >>> timedelta_or_None('25:06:17') datetime.timedelta(1, 3977) >>> timedelta_or_None('-25:06:17') datetime.timedelta(-2, 83177) Illegal values are returned as None: >>> timedelta_or_None('random crap') is...
python
def convert_timedelta(obj): """Returns a TIME column as a timedelta object: >>> timedelta_or_None('25:06:17') datetime.timedelta(1, 3977) >>> timedelta_or_None('-25:06:17') datetime.timedelta(-2, 83177) Illegal values are returned as None: >>> timedelta_or_None('random crap') is...
[ "def", "convert_timedelta", "(", "obj", ")", ":", "if", "not", "PY2", "and", "isinstance", "(", "obj", ",", "(", "bytes", ",", "bytearray", ")", ")", ":", "obj", "=", "obj", ".", "decode", "(", "'ascii'", ")", "m", "=", "TIMEDELTA_RE", ".", "match", ...
Returns a TIME column as a timedelta object: >>> timedelta_or_None('25:06:17') datetime.timedelta(1, 3977) >>> timedelta_or_None('-25:06:17') datetime.timedelta(-2, 83177) Illegal values are returned as None: >>> timedelta_or_None('random crap') is None True Note that MyS...
[ "Returns", "a", "TIME", "column", "as", "a", "timedelta", "object", ":" ]
3674bc6fd064bf88524e839c07690e8c35223709
https://github.com/PyMySQL/PyMySQL/blob/3674bc6fd064bf88524e839c07690e8c35223709/pymysql/converters.py#L200-L238
train
PyMySQL/PyMySQL
pymysql/converters.py
convert_time
def convert_time(obj): """Returns a TIME column as a time object: >>> time_or_None('15:06:17') datetime.time(15, 6, 17) Illegal values are returned as None: >>> time_or_None('-25:06:17') is None True >>> time_or_None('random crap') is None True Note that MySQL always ...
python
def convert_time(obj): """Returns a TIME column as a time object: >>> time_or_None('15:06:17') datetime.time(15, 6, 17) Illegal values are returned as None: >>> time_or_None('-25:06:17') is None True >>> time_or_None('random crap') is None True Note that MySQL always ...
[ "def", "convert_time", "(", "obj", ")", ":", "if", "not", "PY2", "and", "isinstance", "(", "obj", ",", "(", "bytes", ",", "bytearray", ")", ")", ":", "obj", "=", "obj", ".", "decode", "(", "'ascii'", ")", "m", "=", "TIME_RE", ".", "match", "(", "...
Returns a TIME column as a time object: >>> time_or_None('15:06:17') datetime.time(15, 6, 17) Illegal values are returned as None: >>> time_or_None('-25:06:17') is None True >>> time_or_None('random crap') is None True Note that MySQL always returns TIME columns as (+|-)H...
[ "Returns", "a", "TIME", "column", "as", "a", "time", "object", ":" ]
3674bc6fd064bf88524e839c07690e8c35223709
https://github.com/PyMySQL/PyMySQL/blob/3674bc6fd064bf88524e839c07690e8c35223709/pymysql/converters.py#L243-L279
train
PyMySQL/PyMySQL
pymysql/converters.py
convert_date
def convert_date(obj): """Returns a DATE column as a date object: >>> date_or_None('2007-02-26') datetime.date(2007, 2, 26) Illegal values are returned as None: >>> date_or_None('2007-02-31') is None True >>> date_or_None('0000-00-00') is None True """ if not PY2 ...
python
def convert_date(obj): """Returns a DATE column as a date object: >>> date_or_None('2007-02-26') datetime.date(2007, 2, 26) Illegal values are returned as None: >>> date_or_None('2007-02-31') is None True >>> date_or_None('0000-00-00') is None True """ if not PY2 ...
[ "def", "convert_date", "(", "obj", ")", ":", "if", "not", "PY2", "and", "isinstance", "(", "obj", ",", "(", "bytes", ",", "bytearray", ")", ")", ":", "obj", "=", "obj", ".", "decode", "(", "'ascii'", ")", "try", ":", "return", "datetime", ".", "dat...
Returns a DATE column as a date object: >>> date_or_None('2007-02-26') datetime.date(2007, 2, 26) Illegal values are returned as None: >>> date_or_None('2007-02-31') is None True >>> date_or_None('0000-00-00') is None True
[ "Returns", "a", "DATE", "column", "as", "a", "date", "object", ":" ]
3674bc6fd064bf88524e839c07690e8c35223709
https://github.com/PyMySQL/PyMySQL/blob/3674bc6fd064bf88524e839c07690e8c35223709/pymysql/converters.py#L282-L301
train
PyMySQL/PyMySQL
pymysql/_socketio.py
SocketIO.write
def write(self, b): """Write the given bytes or bytearray object *b* to the socket and return the number of bytes written. This can be less than len(b) if not all data could be written. If the socket is non-blocking and no bytes could be written None is returned. """ se...
python
def write(self, b): """Write the given bytes or bytearray object *b* to the socket and return the number of bytes written. This can be less than len(b) if not all data could be written. If the socket is non-blocking and no bytes could be written None is returned. """ se...
[ "def", "write", "(", "self", ",", "b", ")", ":", "self", ".", "_checkClosed", "(", ")", "self", ".", "_checkWritable", "(", ")", "try", ":", "return", "self", ".", "_sock", ".", "send", "(", "b", ")", "except", "error", "as", "e", ":", "# XXX what ...
Write the given bytes or bytearray object *b* to the socket and return the number of bytes written. This can be less than len(b) if not all data could be written. If the socket is non-blocking and no bytes could be written None is returned.
[ "Write", "the", "given", "bytes", "or", "bytearray", "object", "*", "b", "*", "to", "the", "socket", "and", "return", "the", "number", "of", "bytes", "written", ".", "This", "can", "be", "less", "than", "len", "(", "b", ")", "if", "not", "all", "data...
3674bc6fd064bf88524e839c07690e8c35223709
https://github.com/PyMySQL/PyMySQL/blob/3674bc6fd064bf88524e839c07690e8c35223709/pymysql/_socketio.py#L71-L85
train
PyMySQL/PyMySQL
pymysql/_socketio.py
SocketIO.close
def close(self): """Close the SocketIO object. This doesn't close the underlying socket, except if all references to it have disappeared. """ if self.closed: return io.RawIOBase.close(self) self._sock._decref_socketios() self._sock = None
python
def close(self): """Close the SocketIO object. This doesn't close the underlying socket, except if all references to it have disappeared. """ if self.closed: return io.RawIOBase.close(self) self._sock._decref_socketios() self._sock = None
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "closed", ":", "return", "io", ".", "RawIOBase", ".", "close", "(", "self", ")", "self", ".", "_sock", ".", "_decref_socketios", "(", ")", "self", ".", "_sock", "=", "None" ]
Close the SocketIO object. This doesn't close the underlying socket, except if all references to it have disappeared.
[ "Close", "the", "SocketIO", "object", ".", "This", "doesn", "t", "close", "the", "underlying", "socket", "except", "if", "all", "references", "to", "it", "have", "disappeared", "." ]
3674bc6fd064bf88524e839c07690e8c35223709
https://github.com/PyMySQL/PyMySQL/blob/3674bc6fd064bf88524e839c07690e8c35223709/pymysql/_socketio.py#L125-L133
train
PyMySQL/PyMySQL
pymysql/protocol.py
MysqlPacket.read
def read(self, size): """Read the first 'size' bytes in packet and advance cursor past them.""" result = self._data[self._position:(self._position+size)] if len(result) != size: error = ('Result length not requested length:\n' 'Expected=%s. Actual=%s. Position:...
python
def read(self, size): """Read the first 'size' bytes in packet and advance cursor past them.""" result = self._data[self._position:(self._position+size)] if len(result) != size: error = ('Result length not requested length:\n' 'Expected=%s. Actual=%s. Position:...
[ "def", "read", "(", "self", ",", "size", ")", ":", "result", "=", "self", ".", "_data", "[", "self", ".", "_position", ":", "(", "self", ".", "_position", "+", "size", ")", "]", "if", "len", "(", "result", ")", "!=", "size", ":", "error", "=", ...
Read the first 'size' bytes in packet and advance cursor past them.
[ "Read", "the", "first", "size", "bytes", "in", "packet", "and", "advance", "cursor", "past", "them", "." ]
3674bc6fd064bf88524e839c07690e8c35223709
https://github.com/PyMySQL/PyMySQL/blob/3674bc6fd064bf88524e839c07690e8c35223709/pymysql/protocol.py#L63-L75
train
PyMySQL/PyMySQL
pymysql/protocol.py
MysqlPacket.read_all
def read_all(self): """Read all remaining data in the packet. (Subsequent read() will return errors.) """ result = self._data[self._position:] self._position = None # ensure no subsequent read() return result
python
def read_all(self): """Read all remaining data in the packet. (Subsequent read() will return errors.) """ result = self._data[self._position:] self._position = None # ensure no subsequent read() return result
[ "def", "read_all", "(", "self", ")", ":", "result", "=", "self", ".", "_data", "[", "self", ".", "_position", ":", "]", "self", ".", "_position", "=", "None", "# ensure no subsequent read()", "return", "result" ]
Read all remaining data in the packet. (Subsequent read() will return errors.)
[ "Read", "all", "remaining", "data", "in", "the", "packet", "." ]
3674bc6fd064bf88524e839c07690e8c35223709
https://github.com/PyMySQL/PyMySQL/blob/3674bc6fd064bf88524e839c07690e8c35223709/pymysql/protocol.py#L77-L84
train
PyMySQL/PyMySQL
pymysql/protocol.py
MysqlPacket.advance
def advance(self, length): """Advance the cursor in data buffer 'length' bytes.""" new_position = self._position + length if new_position < 0 or new_position > len(self._data): raise Exception('Invalid advance amount (%s) for cursor. ' 'Position=%s' % (le...
python
def advance(self, length): """Advance the cursor in data buffer 'length' bytes.""" new_position = self._position + length if new_position < 0 or new_position > len(self._data): raise Exception('Invalid advance amount (%s) for cursor. ' 'Position=%s' % (le...
[ "def", "advance", "(", "self", ",", "length", ")", ":", "new_position", "=", "self", ".", "_position", "+", "length", "if", "new_position", "<", "0", "or", "new_position", ">", "len", "(", "self", ".", "_data", ")", ":", "raise", "Exception", "(", "'In...
Advance the cursor in data buffer 'length' bytes.
[ "Advance", "the", "cursor", "in", "data", "buffer", "length", "bytes", "." ]
3674bc6fd064bf88524e839c07690e8c35223709
https://github.com/PyMySQL/PyMySQL/blob/3674bc6fd064bf88524e839c07690e8c35223709/pymysql/protocol.py#L86-L92
train
PyMySQL/PyMySQL
pymysql/protocol.py
MysqlPacket.rewind
def rewind(self, position=0): """Set the position of the data buffer cursor to 'position'.""" if position < 0 or position > len(self._data): raise Exception("Invalid position to rewind cursor to: %s." % position) self._position = position
python
def rewind(self, position=0): """Set the position of the data buffer cursor to 'position'.""" if position < 0 or position > len(self._data): raise Exception("Invalid position to rewind cursor to: %s." % position) self._position = position
[ "def", "rewind", "(", "self", ",", "position", "=", "0", ")", ":", "if", "position", "<", "0", "or", "position", ">", "len", "(", "self", ".", "_data", ")", ":", "raise", "Exception", "(", "\"Invalid position to rewind cursor to: %s.\"", "%", "position", "...
Set the position of the data buffer cursor to 'position'.
[ "Set", "the", "position", "of", "the", "data", "buffer", "cursor", "to", "position", "." ]
3674bc6fd064bf88524e839c07690e8c35223709
https://github.com/PyMySQL/PyMySQL/blob/3674bc6fd064bf88524e839c07690e8c35223709/pymysql/protocol.py#L94-L98
train
PyMySQL/PyMySQL
pymysql/protocol.py
MysqlPacket.read_length_encoded_integer
def read_length_encoded_integer(self): """Read a 'Length Coded Binary' number from the data buffer. Length coded numbers can be anywhere from 1 to 9 bytes depending on the value of the first byte. """ c = self.read_uint8() if c == NULL_COLUMN: return None ...
python
def read_length_encoded_integer(self): """Read a 'Length Coded Binary' number from the data buffer. Length coded numbers can be anywhere from 1 to 9 bytes depending on the value of the first byte. """ c = self.read_uint8() if c == NULL_COLUMN: return None ...
[ "def", "read_length_encoded_integer", "(", "self", ")", ":", "c", "=", "self", ".", "read_uint8", "(", ")", "if", "c", "==", "NULL_COLUMN", ":", "return", "None", "if", "c", "<", "UNSIGNED_CHAR_COLUMN", ":", "return", "c", "elif", "c", "==", "UNSIGNED_SHOR...
Read a 'Length Coded Binary' number from the data buffer. Length coded numbers can be anywhere from 1 to 9 bytes depending on the value of the first byte.
[ "Read", "a", "Length", "Coded", "Binary", "number", "from", "the", "data", "buffer", "." ]
3674bc6fd064bf88524e839c07690e8c35223709
https://github.com/PyMySQL/PyMySQL/blob/3674bc6fd064bf88524e839c07690e8c35223709/pymysql/protocol.py#L150-L166
train
PyMySQL/PyMySQL
pymysql/protocol.py
FieldDescriptorPacket._parse_field_descriptor
def _parse_field_descriptor(self, encoding): """Parse the 'Field Descriptor' (Metadata) packet. This is compatible with MySQL 4.1+ (not compatible with MySQL 4.0). """ self.catalog = self.read_length_coded_string() self.db = self.read_length_coded_string() self.table_nam...
python
def _parse_field_descriptor(self, encoding): """Parse the 'Field Descriptor' (Metadata) packet. This is compatible with MySQL 4.1+ (not compatible with MySQL 4.0). """ self.catalog = self.read_length_coded_string() self.db = self.read_length_coded_string() self.table_nam...
[ "def", "_parse_field_descriptor", "(", "self", ",", "encoding", ")", ":", "self", ".", "catalog", "=", "self", ".", "read_length_coded_string", "(", ")", "self", ".", "db", "=", "self", ".", "read_length_coded_string", "(", ")", "self", ".", "table_name", "=...
Parse the 'Field Descriptor' (Metadata) packet. This is compatible with MySQL 4.1+ (not compatible with MySQL 4.0).
[ "Parse", "the", "Field", "Descriptor", "(", "Metadata", ")", "packet", "." ]
3674bc6fd064bf88524e839c07690e8c35223709
https://github.com/PyMySQL/PyMySQL/blob/3674bc6fd064bf88524e839c07690e8c35223709/pymysql/protocol.py#L237-L249
train
PyMySQL/PyMySQL
pymysql/protocol.py
FieldDescriptorPacket.description
def description(self): """Provides a 7-item tuple compatible with the Python PEP249 DB Spec.""" return ( self.name, self.type_code, None, # TODO: display_length; should this be self.length? self.get_column_length(), # 'internal_size' self.get...
python
def description(self): """Provides a 7-item tuple compatible with the Python PEP249 DB Spec.""" return ( self.name, self.type_code, None, # TODO: display_length; should this be self.length? self.get_column_length(), # 'internal_size' self.get...
[ "def", "description", "(", "self", ")", ":", "return", "(", "self", ".", "name", ",", "self", ".", "type_code", ",", "None", ",", "# TODO: display_length; should this be self.length?", "self", ".", "get_column_length", "(", ")", ",", "# 'internal_size'", "self", ...
Provides a 7-item tuple compatible with the Python PEP249 DB Spec.
[ "Provides", "a", "7", "-", "item", "tuple", "compatible", "with", "the", "Python", "PEP249", "DB", "Spec", "." ]
3674bc6fd064bf88524e839c07690e8c35223709
https://github.com/PyMySQL/PyMySQL/blob/3674bc6fd064bf88524e839c07690e8c35223709/pymysql/protocol.py#L253-L262
train
PyMySQL/PyMySQL
pymysql/connections.py
Connection.close
def close(self): """ Send the quit message and close the socket. See `Connection.close() <https://www.python.org/dev/peps/pep-0249/#Connection.close>`_ in the specification. :raise Error: If the connection is already closed. """ if self._closed: rais...
python
def close(self): """ Send the quit message and close the socket. See `Connection.close() <https://www.python.org/dev/peps/pep-0249/#Connection.close>`_ in the specification. :raise Error: If the connection is already closed. """ if self._closed: rais...
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_closed", ":", "raise", "err", ".", "Error", "(", "\"Already closed\"", ")", "self", ".", "_closed", "=", "True", "if", "self", ".", "_sock", "is", "None", ":", "return", "send_data", "=", "s...
Send the quit message and close the socket. See `Connection.close() <https://www.python.org/dev/peps/pep-0249/#Connection.close>`_ in the specification. :raise Error: If the connection is already closed.
[ "Send", "the", "quit", "message", "and", "close", "the", "socket", "." ]
3674bc6fd064bf88524e839c07690e8c35223709
https://github.com/PyMySQL/PyMySQL/blob/3674bc6fd064bf88524e839c07690e8c35223709/pymysql/connections.py#L344-L364
train
PyMySQL/PyMySQL
pymysql/connections.py
Connection._force_close
def _force_close(self): """Close connection without QUIT message""" if self._sock: try: self._sock.close() except: # noqa pass self._sock = None self._rfile = None
python
def _force_close(self): """Close connection without QUIT message""" if self._sock: try: self._sock.close() except: # noqa pass self._sock = None self._rfile = None
[ "def", "_force_close", "(", "self", ")", ":", "if", "self", ".", "_sock", ":", "try", ":", "self", ".", "_sock", ".", "close", "(", ")", "except", ":", "# noqa", "pass", "self", ".", "_sock", "=", "None", "self", ".", "_rfile", "=", "None" ]
Close connection without QUIT message
[ "Close", "connection", "without", "QUIT", "message" ]
3674bc6fd064bf88524e839c07690e8c35223709
https://github.com/PyMySQL/PyMySQL/blob/3674bc6fd064bf88524e839c07690e8c35223709/pymysql/connections.py#L371-L379
train
PyMySQL/PyMySQL
pymysql/connections.py
Connection._send_autocommit_mode
def _send_autocommit_mode(self): """Set whether or not to commit after every execute()""" self._execute_command(COMMAND.COM_QUERY, "SET AUTOCOMMIT = %s" % self.escape(self.autocommit_mode)) self._read_ok_packet()
python
def _send_autocommit_mode(self): """Set whether or not to commit after every execute()""" self._execute_command(COMMAND.COM_QUERY, "SET AUTOCOMMIT = %s" % self.escape(self.autocommit_mode)) self._read_ok_packet()
[ "def", "_send_autocommit_mode", "(", "self", ")", ":", "self", ".", "_execute_command", "(", "COMMAND", ".", "COM_QUERY", ",", "\"SET AUTOCOMMIT = %s\"", "%", "self", ".", "escape", "(", "self", ".", "autocommit_mode", ")", ")", "self", ".", "_read_ok_packet", ...
Set whether or not to commit after every execute()
[ "Set", "whether", "or", "not", "to", "commit", "after", "every", "execute", "()" ]
3674bc6fd064bf88524e839c07690e8c35223709
https://github.com/PyMySQL/PyMySQL/blob/3674bc6fd064bf88524e839c07690e8c35223709/pymysql/connections.py#L401-L405
train
PyMySQL/PyMySQL
pymysql/connections.py
Connection.escape
def escape(self, obj, mapping=None): """Escape whatever value you pass to it. Non-standard, for internal use; do not use this in your applications. """ if isinstance(obj, str_type): return "'" + self.escape_string(obj) + "'" if isinstance(obj, (bytes, bytearray)): ...
python
def escape(self, obj, mapping=None): """Escape whatever value you pass to it. Non-standard, for internal use; do not use this in your applications. """ if isinstance(obj, str_type): return "'" + self.escape_string(obj) + "'" if isinstance(obj, (bytes, bytearray)): ...
[ "def", "escape", "(", "self", ",", "obj", ",", "mapping", "=", "None", ")", ":", "if", "isinstance", "(", "obj", ",", "str_type", ")", ":", "return", "\"'\"", "+", "self", ".", "escape_string", "(", "obj", ")", "+", "\"'\"", "if", "isinstance", "(", ...
Escape whatever value you pass to it. Non-standard, for internal use; do not use this in your applications.
[ "Escape", "whatever", "value", "you", "pass", "to", "it", "." ]
3674bc6fd064bf88524e839c07690e8c35223709
https://github.com/PyMySQL/PyMySQL/blob/3674bc6fd064bf88524e839c07690e8c35223709/pymysql/connections.py#L448-L460
train
PyMySQL/PyMySQL
pymysql/connections.py
Connection.ping
def ping(self, reconnect=True): """ Check if the server is alive. :param reconnect: If the connection is closed, reconnect. :raise Error: If the connection is closed and reconnect=False. """ if self._sock is None: if reconnect: self.connect() ...
python
def ping(self, reconnect=True): """ Check if the server is alive. :param reconnect: If the connection is closed, reconnect. :raise Error: If the connection is closed and reconnect=False. """ if self._sock is None: if reconnect: self.connect() ...
[ "def", "ping", "(", "self", ",", "reconnect", "=", "True", ")", ":", "if", "self", ".", "_sock", "is", "None", ":", "if", "reconnect", ":", "self", ".", "connect", "(", ")", "reconnect", "=", "False", "else", ":", "raise", "err", ".", "Error", "(",...
Check if the server is alive. :param reconnect: If the connection is closed, reconnect. :raise Error: If the connection is closed and reconnect=False.
[ "Check", "if", "the", "server", "is", "alive", "." ]
3674bc6fd064bf88524e839c07690e8c35223709
https://github.com/PyMySQL/PyMySQL/blob/3674bc6fd064bf88524e839c07690e8c35223709/pymysql/connections.py#L518-L539
train
PyMySQL/PyMySQL
pymysql/connections.py
Connection._read_packet
def _read_packet(self, packet_type=MysqlPacket): """Read an entire "mysql packet" in its entirety from the network and return a MysqlPacket type that represents the results. :raise OperationalError: If the connection to the MySQL server is lost. :raise InternalError: If the packet seque...
python
def _read_packet(self, packet_type=MysqlPacket): """Read an entire "mysql packet" in its entirety from the network and return a MysqlPacket type that represents the results. :raise OperationalError: If the connection to the MySQL server is lost. :raise InternalError: If the packet seque...
[ "def", "_read_packet", "(", "self", ",", "packet_type", "=", "MysqlPacket", ")", ":", "buff", "=", "bytearray", "(", ")", "while", "True", ":", "packet_header", "=", "self", ".", "_read_bytes", "(", "4", ")", "#if DEBUG: dump_packet(packet_header)", "btrl", ",...
Read an entire "mysql packet" in its entirety from the network and return a MysqlPacket type that represents the results. :raise OperationalError: If the connection to the MySQL server is lost. :raise InternalError: If the packet sequence number is wrong.
[ "Read", "an", "entire", "mysql", "packet", "in", "its", "entirety", "from", "the", "network", "and", "return", "a", "MysqlPacket", "type", "that", "represents", "the", "results", "." ]
3674bc6fd064bf88524e839c07690e8c35223709
https://github.com/PyMySQL/PyMySQL/blob/3674bc6fd064bf88524e839c07690e8c35223709/pymysql/connections.py#L635-L672
train
PyMySQL/PyMySQL
pymysql/connections.py
Connection._execute_command
def _execute_command(self, command, sql): """ :raise InterfaceError: If the connection is closed. :raise ValueError: If no username was specified. """ if not self._sock: raise err.InterfaceError("(0, '')") # If the last query was unbuffered, make sure it fini...
python
def _execute_command(self, command, sql): """ :raise InterfaceError: If the connection is closed. :raise ValueError: If no username was specified. """ if not self._sock: raise err.InterfaceError("(0, '')") # If the last query was unbuffered, make sure it fini...
[ "def", "_execute_command", "(", "self", ",", "command", ",", "sql", ")", ":", "if", "not", "self", ".", "_sock", ":", "raise", "err", ".", "InterfaceError", "(", "\"(0, '')\"", ")", "# If the last query was unbuffered, make sure it finishes before", "# sending new com...
:raise InterfaceError: If the connection is closed. :raise ValueError: If no username was specified.
[ ":", "raise", "InterfaceError", ":", "If", "the", "connection", "is", "closed", ".", ":", "raise", "ValueError", ":", "If", "no", "username", "was", "specified", "." ]
3674bc6fd064bf88524e839c07690e8c35223709
https://github.com/PyMySQL/PyMySQL/blob/3674bc6fd064bf88524e839c07690e8c35223709/pymysql/connections.py#L731-L771
train
PyMySQL/PyMySQL
pymysql/connections.py
LoadLocalFile.send_data
def send_data(self): """Send data packets from the local file to the server""" if not self.connection._sock: raise err.InterfaceError("(0, '')") conn = self.connection try: with open(self.filename, 'rb') as open_file: packet_size = min(conn.max_al...
python
def send_data(self): """Send data packets from the local file to the server""" if not self.connection._sock: raise err.InterfaceError("(0, '')") conn = self.connection try: with open(self.filename, 'rb') as open_file: packet_size = min(conn.max_al...
[ "def", "send_data", "(", "self", ")", ":", "if", "not", "self", ".", "connection", ".", "_sock", ":", "raise", "err", ".", "InterfaceError", "(", "\"(0, '')\"", ")", "conn", "=", "self", ".", "connection", "try", ":", "with", "open", "(", "self", ".", ...
Send data packets from the local file to the server
[ "Send", "data", "packets", "from", "the", "local", "file", "to", "the", "server" ]
3674bc6fd064bf88524e839c07690e8c35223709
https://github.com/PyMySQL/PyMySQL/blob/3674bc6fd064bf88524e839c07690e8c35223709/pymysql/connections.py#L1248-L1266
train
PyMySQL/PyMySQL
pymysql/_auth.py
scramble_native_password
def scramble_native_password(password, message): """Scramble used for mysql_native_password""" if not password: return b'' stage1 = sha1_new(password).digest() stage2 = sha1_new(stage1).digest() s = sha1_new() s.update(message[:SCRAMBLE_LENGTH]) s.update(stage2) result = s.diges...
python
def scramble_native_password(password, message): """Scramble used for mysql_native_password""" if not password: return b'' stage1 = sha1_new(password).digest() stage2 = sha1_new(stage1).digest() s = sha1_new() s.update(message[:SCRAMBLE_LENGTH]) s.update(stage2) result = s.diges...
[ "def", "scramble_native_password", "(", "password", ",", "message", ")", ":", "if", "not", "password", ":", "return", "b''", "stage1", "=", "sha1_new", "(", "password", ")", ".", "digest", "(", ")", "stage2", "=", "sha1_new", "(", "stage1", ")", ".", "di...
Scramble used for mysql_native_password
[ "Scramble", "used", "for", "mysql_native_password" ]
3674bc6fd064bf88524e839c07690e8c35223709
https://github.com/PyMySQL/PyMySQL/blob/3674bc6fd064bf88524e839c07690e8c35223709/pymysql/_auth.py#L34-L45
train
PyMySQL/PyMySQL
pymysql/_auth.py
sha2_rsa_encrypt
def sha2_rsa_encrypt(password, salt, public_key): """Encrypt password with salt and public_key. Used for sha256_password and caching_sha2_password. """ if not _have_cryptography: raise RuntimeError("'cryptography' package is required for sha256_password or caching_sha2_password auth methods") ...
python
def sha2_rsa_encrypt(password, salt, public_key): """Encrypt password with salt and public_key. Used for sha256_password and caching_sha2_password. """ if not _have_cryptography: raise RuntimeError("'cryptography' package is required for sha256_password or caching_sha2_password auth methods") ...
[ "def", "sha2_rsa_encrypt", "(", "password", ",", "salt", ",", "public_key", ")", ":", "if", "not", "_have_cryptography", ":", "raise", "RuntimeError", "(", "\"'cryptography' package is required for sha256_password or caching_sha2_password auth methods\"", ")", "message", "=",...
Encrypt password with salt and public_key. Used for sha256_password and caching_sha2_password.
[ "Encrypt", "password", "with", "salt", "and", "public_key", "." ]
3674bc6fd064bf88524e839c07690e8c35223709
https://github.com/PyMySQL/PyMySQL/blob/3674bc6fd064bf88524e839c07690e8c35223709/pymysql/_auth.py#L136-L152
train
PyMySQL/PyMySQL
pymysql/_auth.py
scramble_caching_sha2
def scramble_caching_sha2(password, nonce): # (bytes, bytes) -> bytes """Scramble algorithm used in cached_sha2_password fast path. XOR(SHA256(password), SHA256(SHA256(SHA256(password)), nonce)) """ if not password: return b'' p1 = hashlib.sha256(password).digest() p2 = hashlib.sha...
python
def scramble_caching_sha2(password, nonce): # (bytes, bytes) -> bytes """Scramble algorithm used in cached_sha2_password fast path. XOR(SHA256(password), SHA256(SHA256(SHA256(password)), nonce)) """ if not password: return b'' p1 = hashlib.sha256(password).digest() p2 = hashlib.sha...
[ "def", "scramble_caching_sha2", "(", "password", ",", "nonce", ")", ":", "# (bytes, bytes) -> bytes", "if", "not", "password", ":", "return", "b''", "p1", "=", "hashlib", ".", "sha256", "(", "password", ")", ".", "digest", "(", ")", "p2", "=", "hashlib", "...
Scramble algorithm used in cached_sha2_password fast path. XOR(SHA256(password), SHA256(SHA256(SHA256(password)), nonce))
[ "Scramble", "algorithm", "used", "in", "cached_sha2_password", "fast", "path", "." ]
3674bc6fd064bf88524e839c07690e8c35223709
https://github.com/PyMySQL/PyMySQL/blob/3674bc6fd064bf88524e839c07690e8c35223709/pymysql/_auth.py#L186-L205
train
coleifer/peewee
playhouse/sqlite_ext.py
ClosureTable
def ClosureTable(model_class, foreign_key=None, referencing_class=None, referencing_key=None): """Model factory for the transitive closure extension.""" if referencing_class is None: referencing_class = model_class if foreign_key is None: for field_obj in model_class._meta....
python
def ClosureTable(model_class, foreign_key=None, referencing_class=None, referencing_key=None): """Model factory for the transitive closure extension.""" if referencing_class is None: referencing_class = model_class if foreign_key is None: for field_obj in model_class._meta....
[ "def", "ClosureTable", "(", "model_class", ",", "foreign_key", "=", "None", ",", "referencing_class", "=", "None", ",", "referencing_key", "=", "None", ")", ":", "if", "referencing_class", "is", "None", ":", "referencing_class", "=", "model_class", "if", "foreig...
Model factory for the transitive closure extension.
[ "Model", "factory", "for", "the", "transitive", "closure", "extension", "." ]
ea9403b01acb039adb3a2472186d795c796b77a0
https://github.com/coleifer/peewee/blob/ea9403b01acb039adb3a2472186d795c796b77a0/playhouse/sqlite_ext.py#L719-L807
train
coleifer/peewee
playhouse/sqlite_ext.py
bm25
def bm25(raw_match_info, *args): """ Usage: # Format string *must* be pcnalx # Second parameter to bm25 specifies the index of the column, on # the table being queries. bm25(matchinfo(document_tbl, 'pcnalx'), 1) AS rank """ match_info = _parse_match_info(raw_match_info) ...
python
def bm25(raw_match_info, *args): """ Usage: # Format string *must* be pcnalx # Second parameter to bm25 specifies the index of the column, on # the table being queries. bm25(matchinfo(document_tbl, 'pcnalx'), 1) AS rank """ match_info = _parse_match_info(raw_match_info) ...
[ "def", "bm25", "(", "raw_match_info", ",", "*", "args", ")", ":", "match_info", "=", "_parse_match_info", "(", "raw_match_info", ")", "K", "=", "1.2", "B", "=", "0.75", "score", "=", "0.0", "P_O", ",", "C_O", ",", "N_O", ",", "A_O", "=", "range", "("...
Usage: # Format string *must* be pcnalx # Second parameter to bm25 specifies the index of the column, on # the table being queries. bm25(matchinfo(document_tbl, 'pcnalx'), 1) AS rank
[ "Usage", ":" ]
ea9403b01acb039adb3a2472186d795c796b77a0
https://github.com/coleifer/peewee/blob/ea9403b01acb039adb3a2472186d795c796b77a0/playhouse/sqlite_ext.py#L1172-L1223
train
coleifer/peewee
playhouse/sqlite_ext.py
FTSModel.search
def search(cls, term, weights=None, with_score=False, score_alias='score', explicit_ordering=False): """Full-text search using selected `term`.""" return cls._search( term, weights, with_score, score_alias, cls.rank, ...
python
def search(cls, term, weights=None, with_score=False, score_alias='score', explicit_ordering=False): """Full-text search using selected `term`.""" return cls._search( term, weights, with_score, score_alias, cls.rank, ...
[ "def", "search", "(", "cls", ",", "term", ",", "weights", "=", "None", ",", "with_score", "=", "False", ",", "score_alias", "=", "'score'", ",", "explicit_ordering", "=", "False", ")", ":", "return", "cls", ".", "_search", "(", "term", ",", "weights", ...
Full-text search using selected `term`.
[ "Full", "-", "text", "search", "using", "selected", "term", "." ]
ea9403b01acb039adb3a2472186d795c796b77a0
https://github.com/coleifer/peewee/blob/ea9403b01acb039adb3a2472186d795c796b77a0/playhouse/sqlite_ext.py#L391-L400
train
coleifer/peewee
playhouse/sqlite_ext.py
FTSModel.search_bm25
def search_bm25(cls, term, weights=None, with_score=False, score_alias='score', explicit_ordering=False): """Full-text search for selected `term` using BM25 algorithm.""" return cls._search( term, weights, with_score, score_alias, ...
python
def search_bm25(cls, term, weights=None, with_score=False, score_alias='score', explicit_ordering=False): """Full-text search for selected `term` using BM25 algorithm.""" return cls._search( term, weights, with_score, score_alias, ...
[ "def", "search_bm25", "(", "cls", ",", "term", ",", "weights", "=", "None", ",", "with_score", "=", "False", ",", "score_alias", "=", "'score'", ",", "explicit_ordering", "=", "False", ")", ":", "return", "cls", ".", "_search", "(", "term", ",", "weights...
Full-text search for selected `term` using BM25 algorithm.
[ "Full", "-", "text", "search", "for", "selected", "term", "using", "BM25", "algorithm", "." ]
ea9403b01acb039adb3a2472186d795c796b77a0
https://github.com/coleifer/peewee/blob/ea9403b01acb039adb3a2472186d795c796b77a0/playhouse/sqlite_ext.py#L403-L412
train
coleifer/peewee
playhouse/sqlite_ext.py
FTSModel.search_bm25f
def search_bm25f(cls, term, weights=None, with_score=False, score_alias='score', explicit_ordering=False): """Full-text search for selected `term` using BM25 algorithm.""" return cls._search( term, weights, with_score, score_alias, ...
python
def search_bm25f(cls, term, weights=None, with_score=False, score_alias='score', explicit_ordering=False): """Full-text search for selected `term` using BM25 algorithm.""" return cls._search( term, weights, with_score, score_alias, ...
[ "def", "search_bm25f", "(", "cls", ",", "term", ",", "weights", "=", "None", ",", "with_score", "=", "False", ",", "score_alias", "=", "'score'", ",", "explicit_ordering", "=", "False", ")", ":", "return", "cls", ".", "_search", "(", "term", ",", "weight...
Full-text search for selected `term` using BM25 algorithm.
[ "Full", "-", "text", "search", "for", "selected", "term", "using", "BM25", "algorithm", "." ]
ea9403b01acb039adb3a2472186d795c796b77a0
https://github.com/coleifer/peewee/blob/ea9403b01acb039adb3a2472186d795c796b77a0/playhouse/sqlite_ext.py#L415-L424
train
coleifer/peewee
playhouse/sqlite_ext.py
FTSModel.search_lucene
def search_lucene(cls, term, weights=None, with_score=False, score_alias='score', explicit_ordering=False): """Full-text search for selected `term` using BM25 algorithm.""" return cls._search( term, weights, with_score, score_alias, ...
python
def search_lucene(cls, term, weights=None, with_score=False, score_alias='score', explicit_ordering=False): """Full-text search for selected `term` using BM25 algorithm.""" return cls._search( term, weights, with_score, score_alias, ...
[ "def", "search_lucene", "(", "cls", ",", "term", ",", "weights", "=", "None", ",", "with_score", "=", "False", ",", "score_alias", "=", "'score'", ",", "explicit_ordering", "=", "False", ")", ":", "return", "cls", ".", "_search", "(", "term", ",", "weigh...
Full-text search for selected `term` using BM25 algorithm.
[ "Full", "-", "text", "search", "for", "selected", "term", "using", "BM25", "algorithm", "." ]
ea9403b01acb039adb3a2472186d795c796b77a0
https://github.com/coleifer/peewee/blob/ea9403b01acb039adb3a2472186d795c796b77a0/playhouse/sqlite_ext.py#L427-L436
train
coleifer/peewee
playhouse/sqlite_ext.py
FTS5Model.validate_query
def validate_query(query): """ Simple helper function to indicate whether a search query is a valid FTS5 query. Note: this simply looks at the characters being used, and is not guaranteed to catch all problematic queries. """ tokens = _quote_re.findall(query) for ...
python
def validate_query(query): """ Simple helper function to indicate whether a search query is a valid FTS5 query. Note: this simply looks at the characters being used, and is not guaranteed to catch all problematic queries. """ tokens = _quote_re.findall(query) for ...
[ "def", "validate_query", "(", "query", ")", ":", "tokens", "=", "_quote_re", ".", "findall", "(", "query", ")", "for", "token", "in", "tokens", ":", "if", "token", ".", "startswith", "(", "'\"'", ")", "and", "token", ".", "endswith", "(", "'\"'", ")", ...
Simple helper function to indicate whether a search query is a valid FTS5 query. Note: this simply looks at the characters being used, and is not guaranteed to catch all problematic queries.
[ "Simple", "helper", "function", "to", "indicate", "whether", "a", "search", "query", "is", "a", "valid", "FTS5", "query", ".", "Note", ":", "this", "simply", "looks", "at", "the", "characters", "being", "used", "and", "is", "not", "guaranteed", "to", "catc...
ea9403b01acb039adb3a2472186d795c796b77a0
https://github.com/coleifer/peewee/blob/ea9403b01acb039adb3a2472186d795c796b77a0/playhouse/sqlite_ext.py#L550-L562
train
coleifer/peewee
playhouse/sqlite_ext.py
FTS5Model.clean_query
def clean_query(query, replace=chr(26)): """ Clean a query of invalid tokens. """ accum = [] any_invalid = False tokens = _quote_re.findall(query) for token in tokens: if token.startswith('"') and token.endswith('"'): accum.append(token...
python
def clean_query(query, replace=chr(26)): """ Clean a query of invalid tokens. """ accum = [] any_invalid = False tokens = _quote_re.findall(query) for token in tokens: if token.startswith('"') and token.endswith('"'): accum.append(token...
[ "def", "clean_query", "(", "query", ",", "replace", "=", "chr", "(", "26", ")", ")", ":", "accum", "=", "[", "]", "any_invalid", "=", "False", "tokens", "=", "_quote_re", ".", "findall", "(", "query", ")", "for", "token", "in", "tokens", ":", "if", ...
Clean a query of invalid tokens.
[ "Clean", "a", "query", "of", "invalid", "tokens", "." ]
ea9403b01acb039adb3a2472186d795c796b77a0
https://github.com/coleifer/peewee/blob/ea9403b01acb039adb3a2472186d795c796b77a0/playhouse/sqlite_ext.py#L565-L586
train
coleifer/peewee
playhouse/sqlite_ext.py
FTS5Model.search
def search(cls, term, weights=None, with_score=False, score_alias='score', explicit_ordering=False): """Full-text search using selected `term`.""" return cls.search_bm25( FTS5Model.clean_query(term), weights, with_score, score_alias, ...
python
def search(cls, term, weights=None, with_score=False, score_alias='score', explicit_ordering=False): """Full-text search using selected `term`.""" return cls.search_bm25( FTS5Model.clean_query(term), weights, with_score, score_alias, ...
[ "def", "search", "(", "cls", ",", "term", ",", "weights", "=", "None", ",", "with_score", "=", "False", ",", "score_alias", "=", "'score'", ",", "explicit_ordering", "=", "False", ")", ":", "return", "cls", ".", "search_bm25", "(", "FTS5Model", ".", "cle...
Full-text search using selected `term`.
[ "Full", "-", "text", "search", "using", "selected", "term", "." ]
ea9403b01acb039adb3a2472186d795c796b77a0
https://github.com/coleifer/peewee/blob/ea9403b01acb039adb3a2472186d795c796b77a0/playhouse/sqlite_ext.py#L604-L612
train
coleifer/peewee
playhouse/sqlite_ext.py
FTS5Model.search_bm25
def search_bm25(cls, term, weights=None, with_score=False, score_alias='score', explicit_ordering=False): """Full-text search using selected `term`.""" if not weights: rank = SQL('rank') elif isinstance(weights, dict): weight_args = [] for ...
python
def search_bm25(cls, term, weights=None, with_score=False, score_alias='score', explicit_ordering=False): """Full-text search using selected `term`.""" if not weights: rank = SQL('rank') elif isinstance(weights, dict): weight_args = [] for ...
[ "def", "search_bm25", "(", "cls", ",", "term", ",", "weights", "=", "None", ",", "with_score", "=", "False", ",", "score_alias", "=", "'score'", ",", "explicit_ordering", "=", "False", ")", ":", "if", "not", "weights", ":", "rank", "=", "SQL", "(", "'r...
Full-text search using selected `term`.
[ "Full", "-", "text", "search", "using", "selected", "term", "." ]
ea9403b01acb039adb3a2472186d795c796b77a0
https://github.com/coleifer/peewee/blob/ea9403b01acb039adb3a2472186d795c796b77a0/playhouse/sqlite_ext.py#L615-L640
train
coleifer/peewee
playhouse/pool.py
PooledDatabase.manual_close
def manual_close(self): """ Close the underlying connection without returning it to the pool. """ if self.is_closed(): return False # Obtain reference to the connection in-use by the calling thread. conn = self.connection() # A connection will only b...
python
def manual_close(self): """ Close the underlying connection without returning it to the pool. """ if self.is_closed(): return False # Obtain reference to the connection in-use by the calling thread. conn = self.connection() # A connection will only b...
[ "def", "manual_close", "(", "self", ")", ":", "if", "self", ".", "is_closed", "(", ")", ":", "return", "False", "# Obtain reference to the connection in-use by the calling thread.", "conn", "=", "self", ".", "connection", "(", ")", "# A connection will only be re-added ...
Close the underlying connection without returning it to the pool.
[ "Close", "the", "underlying", "connection", "without", "returning", "it", "to", "the", "pool", "." ]
ea9403b01acb039adb3a2472186d795c796b77a0
https://github.com/coleifer/peewee/blob/ea9403b01acb039adb3a2472186d795c796b77a0/playhouse/pool.py#L190-L206
train
coleifer/peewee
examples/analytics/reports.py
Report.top_pages_by_time_period
def top_pages_by_time_period(self, interval='day'): """ Get a breakdown of top pages per interval, i.e. day url count 2014-01-01 /blog/ 11 2014-01-02 /blog/ 14 2014-01-03 /blog/ 9 """ date_trunc = fn.date_trunc(interval, PageView.timesta...
python
def top_pages_by_time_period(self, interval='day'): """ Get a breakdown of top pages per interval, i.e. day url count 2014-01-01 /blog/ 11 2014-01-02 /blog/ 14 2014-01-03 /blog/ 9 """ date_trunc = fn.date_trunc(interval, PageView.timesta...
[ "def", "top_pages_by_time_period", "(", "self", ",", "interval", "=", "'day'", ")", ":", "date_trunc", "=", "fn", ".", "date_trunc", "(", "interval", ",", "PageView", ".", "timestamp", ")", "return", "(", "self", ".", "get_query", "(", ")", ".", "select", ...
Get a breakdown of top pages per interval, i.e. day url count 2014-01-01 /blog/ 11 2014-01-02 /blog/ 14 2014-01-03 /blog/ 9
[ "Get", "a", "breakdown", "of", "top", "pages", "per", "interval", "i", ".", "e", "." ]
ea9403b01acb039adb3a2472186d795c796b77a0
https://github.com/coleifer/peewee/blob/ea9403b01acb039adb3a2472186d795c796b77a0/examples/analytics/reports.py#L19-L38
train
coleifer/peewee
examples/analytics/reports.py
Report.cookies
def cookies(self): """ Retrieve the cookies header from all the users who visited. """ return (self.get_query() .select(PageView.ip, PageView.headers['Cookie']) .where(PageView.headers['Cookie'].is_null(False)) .tuples())
python
def cookies(self): """ Retrieve the cookies header from all the users who visited. """ return (self.get_query() .select(PageView.ip, PageView.headers['Cookie']) .where(PageView.headers['Cookie'].is_null(False)) .tuples())
[ "def", "cookies", "(", "self", ")", ":", "return", "(", "self", ".", "get_query", "(", ")", ".", "select", "(", "PageView", ".", "ip", ",", "PageView", ".", "headers", "[", "'Cookie'", "]", ")", ".", "where", "(", "PageView", ".", "headers", "[", "...
Retrieve the cookies header from all the users who visited.
[ "Retrieve", "the", "cookies", "header", "from", "all", "the", "users", "who", "visited", "." ]
ea9403b01acb039adb3a2472186d795c796b77a0
https://github.com/coleifer/peewee/blob/ea9403b01acb039adb3a2472186d795c796b77a0/examples/analytics/reports.py#L40-L47
train
coleifer/peewee
examples/analytics/reports.py
Report.user_agents
def user_agents(self): """ Retrieve user-agents, sorted by most common to least common. """ return (self.get_query() .select( PageView.headers['User-Agent'], fn.Count(PageView.id)) .group_by(PageView.headers['User-Ag...
python
def user_agents(self): """ Retrieve user-agents, sorted by most common to least common. """ return (self.get_query() .select( PageView.headers['User-Agent'], fn.Count(PageView.id)) .group_by(PageView.headers['User-Ag...
[ "def", "user_agents", "(", "self", ")", ":", "return", "(", "self", ".", "get_query", "(", ")", ".", "select", "(", "PageView", ".", "headers", "[", "'User-Agent'", "]", ",", "fn", ".", "Count", "(", "PageView", ".", "id", ")", ")", ".", "group_by", ...
Retrieve user-agents, sorted by most common to least common.
[ "Retrieve", "user", "-", "agents", "sorted", "by", "most", "common", "to", "least", "common", "." ]
ea9403b01acb039adb3a2472186d795c796b77a0
https://github.com/coleifer/peewee/blob/ea9403b01acb039adb3a2472186d795c796b77a0/examples/analytics/reports.py#L49-L59
train
coleifer/peewee
examples/analytics/reports.py
Report.languages
def languages(self): """ Retrieve languages, sorted by most common to least common. The Accept-Languages header sometimes looks weird, i.e. "en-US,en;q=0.8,is;q=0.6,da;q=0.4" We will split on the first semi- colon. """ language = PageView.headers['Accept-Language'...
python
def languages(self): """ Retrieve languages, sorted by most common to least common. The Accept-Languages header sometimes looks weird, i.e. "en-US,en;q=0.8,is;q=0.6,da;q=0.4" We will split on the first semi- colon. """ language = PageView.headers['Accept-Language'...
[ "def", "languages", "(", "self", ")", ":", "language", "=", "PageView", ".", "headers", "[", "'Accept-Language'", "]", "first_language", "=", "fn", ".", "SubStr", "(", "language", ",", "# String to slice.", "1", ",", "# Left index.", "fn", ".", "StrPos", "("...
Retrieve languages, sorted by most common to least common. The Accept-Languages header sometimes looks weird, i.e. "en-US,en;q=0.8,is;q=0.6,da;q=0.4" We will split on the first semi- colon.
[ "Retrieve", "languages", "sorted", "by", "most", "common", "to", "least", "common", ".", "The", "Accept", "-", "Languages", "header", "sometimes", "looks", "weird", "i", ".", "e", ".", "en", "-", "US", "en", ";", "q", "=", "0", ".", "8", "is", ";", ...
ea9403b01acb039adb3a2472186d795c796b77a0
https://github.com/coleifer/peewee/blob/ea9403b01acb039adb3a2472186d795c796b77a0/examples/analytics/reports.py#L61-L77
train
coleifer/peewee
examples/analytics/reports.py
Report.trail
def trail(self): """ Get all visitors by IP and then list the pages they visited in order. """ inner = (self.get_query() .select(PageView.ip, PageView.url) .order_by(PageView.timestamp)) return (PageView .select( ...
python
def trail(self): """ Get all visitors by IP and then list the pages they visited in order. """ inner = (self.get_query() .select(PageView.ip, PageView.url) .order_by(PageView.timestamp)) return (PageView .select( ...
[ "def", "trail", "(", "self", ")", ":", "inner", "=", "(", "self", ".", "get_query", "(", ")", ".", "select", "(", "PageView", ".", "ip", ",", "PageView", ".", "url", ")", ".", "order_by", "(", "PageView", ".", "timestamp", ")", ")", "return", "(", ...
Get all visitors by IP and then list the pages they visited in order.
[ "Get", "all", "visitors", "by", "IP", "and", "then", "list", "the", "pages", "they", "visited", "in", "order", "." ]
ea9403b01acb039adb3a2472186d795c796b77a0
https://github.com/coleifer/peewee/blob/ea9403b01acb039adb3a2472186d795c796b77a0/examples/analytics/reports.py#L79-L91
train
coleifer/peewee
examples/analytics/reports.py
Report.top_referrers
def top_referrers(self, domain_only=True): """ What domains send us the most traffic? """ referrer = self._referrer_clause(domain_only) return (self.get_query() .select(referrer, fn.Count(PageView.id)) .group_by(referrer) .order_by(...
python
def top_referrers(self, domain_only=True): """ What domains send us the most traffic? """ referrer = self._referrer_clause(domain_only) return (self.get_query() .select(referrer, fn.Count(PageView.id)) .group_by(referrer) .order_by(...
[ "def", "top_referrers", "(", "self", ",", "domain_only", "=", "True", ")", ":", "referrer", "=", "self", ".", "_referrer_clause", "(", "domain_only", ")", "return", "(", "self", ".", "get_query", "(", ")", ".", "select", "(", "referrer", ",", "fn", ".", ...
What domains send us the most traffic?
[ "What", "domains", "send", "us", "the", "most", "traffic?" ]
ea9403b01acb039adb3a2472186d795c796b77a0
https://github.com/coleifer/peewee/blob/ea9403b01acb039adb3a2472186d795c796b77a0/examples/analytics/reports.py#L99-L108
train
coleifer/peewee
examples/diary.py
add_entry
def add_entry(): """Add entry""" print('Enter your entry. Press ctrl+d when finished.') data = sys.stdin.read().strip() if data and raw_input('Save entry? [Yn] ') != 'n': Entry.create(content=data) print('Saved successfully.')
python
def add_entry(): """Add entry""" print('Enter your entry. Press ctrl+d when finished.') data = sys.stdin.read().strip() if data and raw_input('Save entry? [Yn] ') != 'n': Entry.create(content=data) print('Saved successfully.')
[ "def", "add_entry", "(", ")", ":", "print", "(", "'Enter your entry. Press ctrl+d when finished.'", ")", "data", "=", "sys", ".", "stdin", ".", "read", "(", ")", ".", "strip", "(", ")", "if", "data", "and", "raw_input", "(", "'Save entry? [Yn] '", ")", "!=",...
Add entry
[ "Add", "entry" ]
ea9403b01acb039adb3a2472186d795c796b77a0
https://github.com/coleifer/peewee/blob/ea9403b01acb039adb3a2472186d795c796b77a0/examples/diary.py#L35-L41
train
coleifer/peewee
examples/diary.py
view_entries
def view_entries(search_query=None): """View previous entries""" query = Entry.select().order_by(Entry.timestamp.desc()) if search_query: query = query.where(Entry.content.contains(search_query)) for entry in query: timestamp = entry.timestamp.strftime('%A %B %d, %Y %I:%M%p') pr...
python
def view_entries(search_query=None): """View previous entries""" query = Entry.select().order_by(Entry.timestamp.desc()) if search_query: query = query.where(Entry.content.contains(search_query)) for entry in query: timestamp = entry.timestamp.strftime('%A %B %d, %Y %I:%M%p') pr...
[ "def", "view_entries", "(", "search_query", "=", "None", ")", ":", "query", "=", "Entry", ".", "select", "(", ")", ".", "order_by", "(", "Entry", ".", "timestamp", ".", "desc", "(", ")", ")", "if", "search_query", ":", "query", "=", "query", ".", "wh...
View previous entries
[ "View", "previous", "entries" ]
ea9403b01acb039adb3a2472186d795c796b77a0
https://github.com/coleifer/peewee/blob/ea9403b01acb039adb3a2472186d795c796b77a0/examples/diary.py#L43-L62
train
coleifer/peewee
examples/blog/app.py
Entry.html_content
def html_content(self): """ Generate HTML representation of the markdown-formatted blog entry, and also convert any media URLs into rich media objects such as video players or images. """ hilite = CodeHiliteExtension(linenums=False, css_class='highlight') extras =...
python
def html_content(self): """ Generate HTML representation of the markdown-formatted blog entry, and also convert any media URLs into rich media objects such as video players or images. """ hilite = CodeHiliteExtension(linenums=False, css_class='highlight') extras =...
[ "def", "html_content", "(", "self", ")", ":", "hilite", "=", "CodeHiliteExtension", "(", "linenums", "=", "False", ",", "css_class", "=", "'highlight'", ")", "extras", "=", "ExtraExtension", "(", ")", "markdown_content", "=", "markdown", "(", "self", ".", "c...
Generate HTML representation of the markdown-formatted blog entry, and also convert any media URLs into rich media objects such as video players or images.
[ "Generate", "HTML", "representation", "of", "the", "markdown", "-", "formatted", "blog", "entry", "and", "also", "convert", "any", "media", "URLs", "into", "rich", "media", "objects", "such", "as", "video", "players", "or", "images", "." ]
ea9403b01acb039adb3a2472186d795c796b77a0
https://github.com/coleifer/peewee/blob/ea9403b01acb039adb3a2472186d795c796b77a0/examples/blog/app.py#L66-L80
train
coleifer/peewee
playhouse/shortcuts.py
model_to_dict
def model_to_dict(model, recurse=True, backrefs=False, only=None, exclude=None, seen=None, extra_attrs=None, fields_from_query=None, max_depth=None, manytomany=False): """ Convert a model instance (and any related objects) to a dictionary. :param bool recurse: Whether fo...
python
def model_to_dict(model, recurse=True, backrefs=False, only=None, exclude=None, seen=None, extra_attrs=None, fields_from_query=None, max_depth=None, manytomany=False): """ Convert a model instance (and any related objects) to a dictionary. :param bool recurse: Whether fo...
[ "def", "model_to_dict", "(", "model", ",", "recurse", "=", "True", ",", "backrefs", "=", "False", ",", "only", "=", "None", ",", "exclude", "=", "None", ",", "seen", "=", "None", ",", "extra_attrs", "=", "None", ",", "fields_from_query", "=", "None", "...
Convert a model instance (and any related objects) to a dictionary. :param bool recurse: Whether foreign-keys should be recursed. :param bool backrefs: Whether lists of related objects should be recursed. :param only: A list (or set) of field instances indicating which fields should be included. ...
[ "Convert", "a", "model", "instance", "(", "and", "any", "related", "objects", ")", "to", "a", "dictionary", "." ]
ea9403b01acb039adb3a2472186d795c796b77a0
https://github.com/coleifer/peewee/blob/ea9403b01acb039adb3a2472186d795c796b77a0/playhouse/shortcuts.py#L10-L124
train
coleifer/peewee
peewee.py
ColumnBase._e
def _e(op, inv=False): """ Lightweight factory which returns a method that builds an Expression consisting of the left-hand and right-hand operands, using `op`. """ def inner(self, rhs): if inv: return Expression(rhs, op, self) return Expre...
python
def _e(op, inv=False): """ Lightweight factory which returns a method that builds an Expression consisting of the left-hand and right-hand operands, using `op`. """ def inner(self, rhs): if inv: return Expression(rhs, op, self) return Expre...
[ "def", "_e", "(", "op", ",", "inv", "=", "False", ")", ":", "def", "inner", "(", "self", ",", "rhs", ")", ":", "if", "inv", ":", "return", "Expression", "(", "rhs", ",", "op", ",", "self", ")", "return", "Expression", "(", "self", ",", "op", ",...
Lightweight factory which returns a method that builds an Expression consisting of the left-hand and right-hand operands, using `op`.
[ "Lightweight", "factory", "which", "returns", "a", "method", "that", "builds", "an", "Expression", "consisting", "of", "the", "left", "-", "hand", "and", "right", "-", "hand", "operands", "using", "op", "." ]
ea9403b01acb039adb3a2472186d795c796b77a0
https://github.com/coleifer/peewee/blob/ea9403b01acb039adb3a2472186d795c796b77a0/peewee.py#L1091-L1100
train
RomelTorres/alpha_vantage
alpha_vantage/foreignexchange.py
ForeignExchange.get_currency_exchange_intraday
def get_currency_exchange_intraday(self, from_symbol, to_symbol, interval='15min', outputsize='compact'): """ Returns the intraday exchange rate for any pair of physical currency (e.g., EUR) or physical currency (e.g., USD). Keyword Arguments: from_symbol: The currency you would lik...
python
def get_currency_exchange_intraday(self, from_symbol, to_symbol, interval='15min', outputsize='compact'): """ Returns the intraday exchange rate for any pair of physical currency (e.g., EUR) or physical currency (e.g., USD). Keyword Arguments: from_symbol: The currency you would lik...
[ "def", "get_currency_exchange_intraday", "(", "self", ",", "from_symbol", ",", "to_symbol", ",", "interval", "=", "'15min'", ",", "outputsize", "=", "'compact'", ")", ":", "_FUNCTION_KEY", "=", "'FX_INTRADAY'", "return", "_FUNCTION_KEY", ",", "\"Time Series FX ({})\""...
Returns the intraday exchange rate for any pair of physical currency (e.g., EUR) or physical currency (e.g., USD). Keyword Arguments: from_symbol: The currency you would like to get the exchange rate for. For example: from_currency=EUR or from_currency=USD. ...
[ "Returns", "the", "intraday", "exchange", "rate", "for", "any", "pair", "of", "physical", "currency", "(", "e", ".", "g", ".", "EUR", ")", "or", "physical", "currency", "(", "e", ".", "g", ".", "USD", ")", "." ]
4e0b5057e520e3e3de69cf947301765817290121
https://github.com/RomelTorres/alpha_vantage/blob/4e0b5057e520e3e3de69cf947301765817290121/alpha_vantage/foreignexchange.py#L37-L56
train
RomelTorres/alpha_vantage
alpha_vantage/alphavantage.py
AlphaVantage._call_api_on_func
def _call_api_on_func(cls, func): """ Decorator for forming the api call with the arguments of the function, it works by taking the arguments given to the function and building the url to call the api on it Keyword Arguments: func: The function to be decorated """ ...
python
def _call_api_on_func(cls, func): """ Decorator for forming the api call with the arguments of the function, it works by taking the arguments given to the function and building the url to call the api on it Keyword Arguments: func: The function to be decorated """ ...
[ "def", "_call_api_on_func", "(", "cls", ",", "func", ")", ":", "# Argument Handling", "if", "sys", ".", "version_info", "[", "0", "]", "<", "3", ":", "# Deprecated since version 3.0", "argspec", "=", "inspect", ".", "getargspec", "(", "func", ")", "else", ":...
Decorator for forming the api call with the arguments of the function, it works by taking the arguments given to the function and building the url to call the api on it Keyword Arguments: func: The function to be decorated
[ "Decorator", "for", "forming", "the", "api", "call", "with", "the", "arguments", "of", "the", "function", "it", "works", "by", "taking", "the", "arguments", "given", "to", "the", "function", "and", "building", "the", "url", "to", "call", "the", "api", "on"...
4e0b5057e520e3e3de69cf947301765817290121
https://github.com/RomelTorres/alpha_vantage/blob/4e0b5057e520e3e3de69cf947301765817290121/alpha_vantage/alphavantage.py#L65-L147
train
RomelTorres/alpha_vantage
alpha_vantage/alphavantage.py
AlphaVantage._output_format
def _output_format(cls, func, override=None): """ Decorator in charge of giving the output its right format, either json or pandas Keyword Arguments: func: The function to be decorated override: Override the internal format of the call, default None """ ...
python
def _output_format(cls, func, override=None): """ Decorator in charge of giving the output its right format, either json or pandas Keyword Arguments: func: The function to be decorated override: Override the internal format of the call, default None """ ...
[ "def", "_output_format", "(", "cls", ",", "func", ",", "override", "=", "None", ")", ":", "@", "wraps", "(", "func", ")", "def", "_format_wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "call_response", ",", "data_key", ",...
Decorator in charge of giving the output its right format, either json or pandas Keyword Arguments: func: The function to be decorated override: Override the internal format of the call, default None
[ "Decorator", "in", "charge", "of", "giving", "the", "output", "its", "right", "format", "either", "json", "or", "pandas" ]
4e0b5057e520e3e3de69cf947301765817290121
https://github.com/RomelTorres/alpha_vantage/blob/4e0b5057e520e3e3de69cf947301765817290121/alpha_vantage/alphavantage.py#L150-L203
train
RomelTorres/alpha_vantage
alpha_vantage/alphavantage.py
AlphaVantage.map_to_matype
def map_to_matype(self, matype): """ Convert to the alpha vantage math type integer. It returns an integer correspondent to the type of math to apply to a function. It raises ValueError if an integer greater than the supported math types is given. Keyword Arguments: ...
python
def map_to_matype(self, matype): """ Convert to the alpha vantage math type integer. It returns an integer correspondent to the type of math to apply to a function. It raises ValueError if an integer greater than the supported math types is given. Keyword Arguments: ...
[ "def", "map_to_matype", "(", "self", ",", "matype", ")", ":", "# Check if it is an integer or a string", "try", ":", "value", "=", "int", "(", "matype", ")", "if", "abs", "(", "value", ")", ">", "len", "(", "AlphaVantage", ".", "_ALPHA_VANTAGE_MATH_MAP", ")", ...
Convert to the alpha vantage math type integer. It returns an integer correspondent to the type of math to apply to a function. It raises ValueError if an integer greater than the supported math types is given. Keyword Arguments: matype: The math type of the alpha vantage a...
[ "Convert", "to", "the", "alpha", "vantage", "math", "type", "integer", ".", "It", "returns", "an", "integer", "correspondent", "to", "the", "type", "of", "math", "to", "apply", "to", "a", "function", ".", "It", "raises", "ValueError", "if", "an", "integer"...
4e0b5057e520e3e3de69cf947301765817290121
https://github.com/RomelTorres/alpha_vantage/blob/4e0b5057e520e3e3de69cf947301765817290121/alpha_vantage/alphavantage.py#L214-L241
train
RomelTorres/alpha_vantage
alpha_vantage/alphavantage.py
AlphaVantage._handle_api_call
def _handle_api_call(self, url): """ Handle the return call from the api and return a data and meta_data object. It raises a ValueError on problems Keyword Arguments: url: The url of the service data_key: The key for getting the data from the jso object me...
python
def _handle_api_call(self, url): """ Handle the return call from the api and return a data and meta_data object. It raises a ValueError on problems Keyword Arguments: url: The url of the service data_key: The key for getting the data from the jso object me...
[ "def", "_handle_api_call", "(", "self", ",", "url", ")", ":", "response", "=", "requests", ".", "get", "(", "url", ",", "proxies", "=", "self", ".", "proxy", ")", "if", "'json'", "in", "self", ".", "output_format", ".", "lower", "(", ")", "or", "'pan...
Handle the return call from the api and return a data and meta_data object. It raises a ValueError on problems Keyword Arguments: url: The url of the service data_key: The key for getting the data from the jso object meta_data_key: The key for getting the meta da...
[ "Handle", "the", "return", "call", "from", "the", "api", "and", "return", "a", "data", "and", "meta_data", "object", ".", "It", "raises", "a", "ValueError", "on", "problems" ]
4e0b5057e520e3e3de69cf947301765817290121
https://github.com/RomelTorres/alpha_vantage/blob/4e0b5057e520e3e3de69cf947301765817290121/alpha_vantage/alphavantage.py#L243-L269
train
RomelTorres/alpha_vantage
alpha_vantage/sectorperformance.py
SectorPerformances._output_format_sector
def _output_format_sector(func, override=None): """ Decorator in charge of giving the output its right format, either json or pandas (replacing the % for usable floats, range 0-1.0) Keyword Arguments: func: The function to be decorated override: Override the internal for...
python
def _output_format_sector(func, override=None): """ Decorator in charge of giving the output its right format, either json or pandas (replacing the % for usable floats, range 0-1.0) Keyword Arguments: func: The function to be decorated override: Override the internal for...
[ "def", "_output_format_sector", "(", "func", ",", "override", "=", "None", ")", ":", "@", "wraps", "(", "func", ")", "def", "_format_wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "json_response", ",", "data_key", ",", "met...
Decorator in charge of giving the output its right format, either json or pandas (replacing the % for usable floats, range 0-1.0) Keyword Arguments: func: The function to be decorated override: Override the internal format of the call, default None Returns: A...
[ "Decorator", "in", "charge", "of", "giving", "the", "output", "its", "right", "format", "either", "json", "or", "pandas", "(", "replacing", "the", "%", "for", "usable", "floats", "range", "0", "-", "1", ".", "0", ")" ]
4e0b5057e520e3e3de69cf947301765817290121
https://github.com/RomelTorres/alpha_vantage/blob/4e0b5057e520e3e3de69cf947301765817290121/alpha_vantage/sectorperformance.py#L33-L74
train
RomelTorres/alpha_vantage
alpha_vantage/techindicators.py
TechIndicators.get_macd
def get_macd(self, symbol, interval='daily', series_type='close', fastperiod=None, slowperiod=None, signalperiod=None): """ Return the moving average convergence/divergence time series in two json objects as data and meta_data. It raises ValueError when problems arise K...
python
def get_macd(self, symbol, interval='daily', series_type='close', fastperiod=None, slowperiod=None, signalperiod=None): """ Return the moving average convergence/divergence time series in two json objects as data and meta_data. It raises ValueError when problems arise K...
[ "def", "get_macd", "(", "self", ",", "symbol", ",", "interval", "=", "'daily'", ",", "series_type", "=", "'close'", ",", "fastperiod", "=", "None", ",", "slowperiod", "=", "None", ",", "signalperiod", "=", "None", ")", ":", "_FUNCTION_KEY", "=", "\"MACD\""...
Return the moving average convergence/divergence time series in two json objects as data and meta_data. It raises ValueError when problems arise Keyword Arguments: symbol: the symbol for the equity we want to get its data interval: time interval between two conscutive ...
[ "Return", "the", "moving", "average", "convergence", "/", "divergence", "time", "series", "in", "two", "json", "objects", "as", "data", "and", "meta_data", ".", "It", "raises", "ValueError", "when", "problems", "arise" ]
4e0b5057e520e3e3de69cf947301765817290121
https://github.com/RomelTorres/alpha_vantage/blob/4e0b5057e520e3e3de69cf947301765817290121/alpha_vantage/techindicators.py#L186-L204
train
RomelTorres/alpha_vantage
alpha_vantage/techindicators.py
TechIndicators.get_macdext
def get_macdext(self, symbol, interval='daily', series_type='close', fastperiod=None, slowperiod=None, signalperiod=None, fastmatype=None, slowmatype=None, signalmatype=None): """ Return the moving average convergence/divergence time series in two json objects as ...
python
def get_macdext(self, symbol, interval='daily', series_type='close', fastperiod=None, slowperiod=None, signalperiod=None, fastmatype=None, slowmatype=None, signalmatype=None): """ Return the moving average convergence/divergence time series in two json objects as ...
[ "def", "get_macdext", "(", "self", ",", "symbol", ",", "interval", "=", "'daily'", ",", "series_type", "=", "'close'", ",", "fastperiod", "=", "None", ",", "slowperiod", "=", "None", ",", "signalperiod", "=", "None", ",", "fastmatype", "=", "None", ",", ...
Return the moving average convergence/divergence time series in two json objects as data and meta_data. It raises ValueError when problems arise Keyword Arguments: symbol: the symbol for the equity we want to get its data interval: time interval between two conscutive ...
[ "Return", "the", "moving", "average", "convergence", "/", "divergence", "time", "series", "in", "two", "json", "objects", "as", "data", "and", "meta_data", ".", "It", "raises", "ValueError", "when", "problems", "arise" ]
4e0b5057e520e3e3de69cf947301765817290121
https://github.com/RomelTorres/alpha_vantage/blob/4e0b5057e520e3e3de69cf947301765817290121/alpha_vantage/techindicators.py#L208-L249
train
RomelTorres/alpha_vantage
alpha_vantage/techindicators.py
TechIndicators.get_stoch
def get_stoch(self, symbol, interval='daily', fastkperiod=None, slowkperiod=None, slowdperiod=None, slowkmatype=None, slowdmatype=None): """ Return the stochatic oscillator values in two json objects as data and meta_data. It raises ValueError when problems arise Keywo...
python
def get_stoch(self, symbol, interval='daily', fastkperiod=None, slowkperiod=None, slowdperiod=None, slowkmatype=None, slowdmatype=None): """ Return the stochatic oscillator values in two json objects as data and meta_data. It raises ValueError when problems arise Keywo...
[ "def", "get_stoch", "(", "self", ",", "symbol", ",", "interval", "=", "'daily'", ",", "fastkperiod", "=", "None", ",", "slowkperiod", "=", "None", ",", "slowdperiod", "=", "None", ",", "slowkmatype", "=", "None", ",", "slowdmatype", "=", "None", ")", ":"...
Return the stochatic oscillator values in two json objects as data and meta_data. It raises ValueError when problems arise Keyword Arguments: symbol: the symbol for the equity we want to get its data interval: time interval between two conscutive values, ...
[ "Return", "the", "stochatic", "oscillator", "values", "in", "two", "json", "objects", "as", "data", "and", "meta_data", ".", "It", "raises", "ValueError", "when", "problems", "arise" ]
4e0b5057e520e3e3de69cf947301765817290121
https://github.com/RomelTorres/alpha_vantage/blob/4e0b5057e520e3e3de69cf947301765817290121/alpha_vantage/techindicators.py#L253-L290
train
RomelTorres/alpha_vantage
alpha_vantage/techindicators.py
TechIndicators.get_stochrsi
def get_stochrsi(self, symbol, interval='daily', time_period=20, series_type='close', fastkperiod=None, fastdperiod=None, fastdmatype=None): """ Return the stochatic relative strength index in two json objects as data and meta_data. It raises ValueError when problems arise ...
python
def get_stochrsi(self, symbol, interval='daily', time_period=20, series_type='close', fastkperiod=None, fastdperiod=None, fastdmatype=None): """ Return the stochatic relative strength index in two json objects as data and meta_data. It raises ValueError when problems arise ...
[ "def", "get_stochrsi", "(", "self", ",", "symbol", ",", "interval", "=", "'daily'", ",", "time_period", "=", "20", ",", "series_type", "=", "'close'", ",", "fastkperiod", "=", "None", ",", "fastdperiod", "=", "None", ",", "fastdmatype", "=", "None", ")", ...
Return the stochatic relative strength index in two json objects as data and meta_data. It raises ValueError when problems arise Keyword Arguments: symbol: the symbol for the equity we want to get its data interval: time interval between two conscutive values, ...
[ "Return", "the", "stochatic", "relative", "strength", "index", "in", "two", "json", "objects", "as", "data", "and", "meta_data", ".", "It", "raises", "ValueError", "when", "problems", "arise" ]
4e0b5057e520e3e3de69cf947301765817290121
https://github.com/RomelTorres/alpha_vantage/blob/4e0b5057e520e3e3de69cf947301765817290121/alpha_vantage/techindicators.py#L347-L381
train
RomelTorres/alpha_vantage
alpha_vantage/techindicators.py
TechIndicators.get_apo
def get_apo(self, symbol, interval='daily', series_type='close', fastperiod=None, slowperiod=None, matype=None): """ Return the absolute price oscillator values in two json objects as data and meta_data. It raises ValueError when problems arise Keyword Arguments: ...
python
def get_apo(self, symbol, interval='daily', series_type='close', fastperiod=None, slowperiod=None, matype=None): """ Return the absolute price oscillator values in two json objects as data and meta_data. It raises ValueError when problems arise Keyword Arguments: ...
[ "def", "get_apo", "(", "self", ",", "symbol", ",", "interval", "=", "'daily'", ",", "series_type", "=", "'close'", ",", "fastperiod", "=", "None", ",", "slowperiod", "=", "None", ",", "matype", "=", "None", ")", ":", "_FUNCTION_KEY", "=", "\"APO\"", "ret...
Return the absolute price oscillator values in two json objects as data and meta_data. It raises ValueError when problems arise Keyword Arguments: symbol: the symbol for the equity we want to get its data interval: time interval between two conscutive values, ...
[ "Return", "the", "absolute", "price", "oscillator", "values", "in", "two", "json", "objects", "as", "data", "and", "meta_data", ".", "It", "raises", "ValueError", "when", "problems", "arise" ]
4e0b5057e520e3e3de69cf947301765817290121
https://github.com/RomelTorres/alpha_vantage/blob/4e0b5057e520e3e3de69cf947301765817290121/alpha_vantage/techindicators.py#L433-L463
train
RomelTorres/alpha_vantage
alpha_vantage/techindicators.py
TechIndicators.get_bbands
def get_bbands(self, symbol, interval='daily', time_period=20, series_type='close', nbdevup=None, nbdevdn=None, matype=None): """ Return the bollinger bands values in two json objects as data and meta_data. It raises ValueError when problems arise Keyword Arguments: ...
python
def get_bbands(self, symbol, interval='daily', time_period=20, series_type='close', nbdevup=None, nbdevdn=None, matype=None): """ Return the bollinger bands values in two json objects as data and meta_data. It raises ValueError when problems arise Keyword Arguments: ...
[ "def", "get_bbands", "(", "self", ",", "symbol", ",", "interval", "=", "'daily'", ",", "time_period", "=", "20", ",", "series_type", "=", "'close'", ",", "nbdevup", "=", "None", ",", "nbdevdn", "=", "None", ",", "matype", "=", "None", ")", ":", "_FUNCT...
Return the bollinger bands values in two json objects as data and meta_data. It raises ValueError when problems arise Keyword Arguments: symbol: the symbol for the equity we want to get its data interval: time interval between two conscutive values, sup...
[ "Return", "the", "bollinger", "bands", "values", "in", "two", "json", "objects", "as", "data", "and", "meta_data", ".", "It", "raises", "ValueError", "when", "problems", "arise" ]
4e0b5057e520e3e3de69cf947301765817290121
https://github.com/RomelTorres/alpha_vantage/blob/4e0b5057e520e3e3de69cf947301765817290121/alpha_vantage/techindicators.py#L780-L812
train
flask-restful/flask-restful
flask_restful/utils/__init__.py
unpack
def unpack(value): """Return a three tuple of data, code, and headers""" if not isinstance(value, tuple): return value, 200, {} try: data, code, headers = value return data, code, headers except ValueError: pass try: data, code = value return data, c...
python
def unpack(value): """Return a three tuple of data, code, and headers""" if not isinstance(value, tuple): return value, 200, {} try: data, code, headers = value return data, code, headers except ValueError: pass try: data, code = value return data, c...
[ "def", "unpack", "(", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "tuple", ")", ":", "return", "value", ",", "200", ",", "{", "}", "try", ":", "data", ",", "code", ",", "headers", "=", "value", "return", "data", ",", "code", ...
Return a three tuple of data, code, and headers
[ "Return", "a", "three", "tuple", "of", "data", "code", "and", "headers" ]
25544d697c1f82bafbd1320960df459f58a58e03
https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/flask_restful/utils/__init__.py#L18-L35
train
flask-restful/flask-restful
examples/xml_representation.py
output_xml
def output_xml(data, code, headers=None): """Makes a Flask response with a XML encoded body""" resp = make_response(dumps({'response' :data}), code) resp.headers.extend(headers or {}) return resp
python
def output_xml(data, code, headers=None): """Makes a Flask response with a XML encoded body""" resp = make_response(dumps({'response' :data}), code) resp.headers.extend(headers or {}) return resp
[ "def", "output_xml", "(", "data", ",", "code", ",", "headers", "=", "None", ")", ":", "resp", "=", "make_response", "(", "dumps", "(", "{", "'response'", ":", "data", "}", ")", ",", "code", ")", "resp", ".", "headers", ".", "extend", "(", "headers", ...
Makes a Flask response with a XML encoded body
[ "Makes", "a", "Flask", "response", "with", "a", "XML", "encoded", "body" ]
25544d697c1f82bafbd1320960df459f58a58e03
https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/examples/xml_representation.py#L6-L10
train
flask-restful/flask-restful
flask_restful/representations/json.py
output_json
def output_json(data, code, headers=None): """Makes a Flask response with a JSON encoded body""" settings = current_app.config.get('RESTFUL_JSON', {}) # If we're in debug mode, and the indent is not set, we set it to a # reasonable value here. Note that this won't override any existing value # th...
python
def output_json(data, code, headers=None): """Makes a Flask response with a JSON encoded body""" settings = current_app.config.get('RESTFUL_JSON', {}) # If we're in debug mode, and the indent is not set, we set it to a # reasonable value here. Note that this won't override any existing value # th...
[ "def", "output_json", "(", "data", ",", "code", ",", "headers", "=", "None", ")", ":", "settings", "=", "current_app", ".", "config", ".", "get", "(", "'RESTFUL_JSON'", ",", "{", "}", ")", "# If we're in debug mode, and the indent is not set, we set it to a", "# r...
Makes a Flask response with a JSON encoded body
[ "Makes", "a", "Flask", "response", "with", "a", "JSON", "encoded", "body" ]
25544d697c1f82bafbd1320960df459f58a58e03
https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/flask_restful/representations/json.py#L7-L25
train
flask-restful/flask-restful
flask_restful/__init__.py
abort
def abort(http_status_code, **kwargs): """Raise a HTTPException for the given http_status_code. Attach any keyword arguments to the exception for later processing. """ #noinspection PyUnresolvedReferences try: original_flask_abort(http_status_code) except HTTPException as e: if l...
python
def abort(http_status_code, **kwargs): """Raise a HTTPException for the given http_status_code. Attach any keyword arguments to the exception for later processing. """ #noinspection PyUnresolvedReferences try: original_flask_abort(http_status_code) except HTTPException as e: if l...
[ "def", "abort", "(", "http_status_code", ",", "*", "*", "kwargs", ")", ":", "#noinspection PyUnresolvedReferences", "try", ":", "original_flask_abort", "(", "http_status_code", ")", "except", "HTTPException", "as", "e", ":", "if", "len", "(", "kwargs", ")", ":",...
Raise a HTTPException for the given http_status_code. Attach any keyword arguments to the exception for later processing.
[ "Raise", "a", "HTTPException", "for", "the", "given", "http_status_code", ".", "Attach", "any", "keyword", "arguments", "to", "the", "exception", "for", "later", "processing", "." ]
25544d697c1f82bafbd1320960df459f58a58e03
https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/flask_restful/__init__.py#L23-L33
train
flask-restful/flask-restful
flask_restful/__init__.py
marshal
def marshal(data, fields, envelope=None): """Takes raw data (in the form of a dict, list, object) and a dict of fields to output and filters the data based on those fields. :param data: the actual object(s) from which the fields are taken from :param fields: a dict of whose keys will make up the final ...
python
def marshal(data, fields, envelope=None): """Takes raw data (in the form of a dict, list, object) and a dict of fields to output and filters the data based on those fields. :param data: the actual object(s) from which the fields are taken from :param fields: a dict of whose keys will make up the final ...
[ "def", "marshal", "(", "data", ",", "fields", ",", "envelope", "=", "None", ")", ":", "def", "make", "(", "cls", ")", ":", "if", "isinstance", "(", "cls", ",", "type", ")", ":", "return", "cls", "(", ")", "return", "cls", "if", "isinstance", "(", ...
Takes raw data (in the form of a dict, list, object) and a dict of fields to output and filters the data based on those fields. :param data: the actual object(s) from which the fields are taken from :param fields: a dict of whose keys will make up the final serialized response output ...
[ "Takes", "raw", "data", "(", "in", "the", "form", "of", "a", "dict", "list", "object", ")", "and", "a", "dict", "of", "fields", "to", "output", "and", "filters", "the", "data", "based", "on", "those", "fields", "." ]
25544d697c1f82bafbd1320960df459f58a58e03
https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/flask_restful/__init__.py#L591-L626
train
flask-restful/flask-restful
flask_restful/__init__.py
Api.init_app
def init_app(self, app): """Initialize this class with the given :class:`flask.Flask` application or :class:`flask.Blueprint` object. :param app: the Flask application or blueprint object :type app: flask.Flask :type app: flask.Blueprint Examples:: api = Ap...
python
def init_app(self, app): """Initialize this class with the given :class:`flask.Flask` application or :class:`flask.Blueprint` object. :param app: the Flask application or blueprint object :type app: flask.Flask :type app: flask.Blueprint Examples:: api = Ap...
[ "def", "init_app", "(", "self", ",", "app", ")", ":", "# If app is a blueprint, defer the initialization", "try", ":", "app", ".", "record", "(", "self", ".", "_deferred_blueprint_init", ")", "# Flask.Blueprint has a 'record' attribute, Flask.Api does not", "except", "Attri...
Initialize this class with the given :class:`flask.Flask` application or :class:`flask.Blueprint` object. :param app: the Flask application or blueprint object :type app: flask.Flask :type app: flask.Blueprint Examples:: api = Api() api.add_resource(......
[ "Initialize", "this", "class", "with", "the", "given", ":", "class", ":", "flask", ".", "Flask", "application", "or", ":", "class", ":", "flask", ".", "Blueprint", "object", "." ]
25544d697c1f82bafbd1320960df459f58a58e03
https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/flask_restful/__init__.py#L96-L118
train
flask-restful/flask-restful
flask_restful/__init__.py
Api._complete_url
def _complete_url(self, url_part, registration_prefix): """This method is used to defer the construction of the final url in the case that the Api is created with a Blueprint. :param url_part: The part of the url the endpoint is registered with :param registration_prefix: The part of th...
python
def _complete_url(self, url_part, registration_prefix): """This method is used to defer the construction of the final url in the case that the Api is created with a Blueprint. :param url_part: The part of the url the endpoint is registered with :param registration_prefix: The part of th...
[ "def", "_complete_url", "(", "self", ",", "url_part", ",", "registration_prefix", ")", ":", "parts", "=", "{", "'b'", ":", "registration_prefix", ",", "'a'", ":", "self", ".", "prefix", ",", "'e'", ":", "url_part", "}", "return", "''", ".", "join", "(", ...
This method is used to defer the construction of the final url in the case that the Api is created with a Blueprint. :param url_part: The part of the url the endpoint is registered with :param registration_prefix: The part of the url contributed by the blueprint. Generally speaking...
[ "This", "method", "is", "used", "to", "defer", "the", "construction", "of", "the", "final", "url", "in", "the", "case", "that", "the", "Api", "is", "created", "with", "a", "Blueprint", "." ]
25544d697c1f82bafbd1320960df459f58a58e03
https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/flask_restful/__init__.py#L120-L133
train
flask-restful/flask-restful
flask_restful/__init__.py
Api._init_app
def _init_app(self, app): """Perform initialization actions with the given :class:`flask.Flask` object. :param app: The flask application object :type app: flask.Flask """ app.handle_exception = partial(self.error_router, app.handle_exception) app.handle_user_exc...
python
def _init_app(self, app): """Perform initialization actions with the given :class:`flask.Flask` object. :param app: The flask application object :type app: flask.Flask """ app.handle_exception = partial(self.error_router, app.handle_exception) app.handle_user_exc...
[ "def", "_init_app", "(", "self", ",", "app", ")", ":", "app", ".", "handle_exception", "=", "partial", "(", "self", ".", "error_router", ",", "app", ".", "handle_exception", ")", "app", ".", "handle_user_exception", "=", "partial", "(", "self", ".", "error...
Perform initialization actions with the given :class:`flask.Flask` object. :param app: The flask application object :type app: flask.Flask
[ "Perform", "initialization", "actions", "with", "the", "given", ":", "class", ":", "flask", ".", "Flask", "object", "." ]
25544d697c1f82bafbd1320960df459f58a58e03
https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/flask_restful/__init__.py#L186-L198
train
flask-restful/flask-restful
flask_restful/__init__.py
Api.owns_endpoint
def owns_endpoint(self, endpoint): """Tests if an endpoint name (not path) belongs to this Api. Takes in to account the Blueprint name part of the endpoint name. :param endpoint: The name of the endpoint being checked :return: bool """ if self.blueprint: if...
python
def owns_endpoint(self, endpoint): """Tests if an endpoint name (not path) belongs to this Api. Takes in to account the Blueprint name part of the endpoint name. :param endpoint: The name of the endpoint being checked :return: bool """ if self.blueprint: if...
[ "def", "owns_endpoint", "(", "self", ",", "endpoint", ")", ":", "if", "self", ".", "blueprint", ":", "if", "endpoint", ".", "startswith", "(", "self", ".", "blueprint", ".", "name", ")", ":", "endpoint", "=", "endpoint", ".", "split", "(", "self", ".",...
Tests if an endpoint name (not path) belongs to this Api. Takes in to account the Blueprint name part of the endpoint name. :param endpoint: The name of the endpoint being checked :return: bool
[ "Tests", "if", "an", "endpoint", "name", "(", "not", "path", ")", "belongs", "to", "this", "Api", ".", "Takes", "in", "to", "account", "the", "Blueprint", "name", "part", "of", "the", "endpoint", "name", "." ]
25544d697c1f82bafbd1320960df459f58a58e03
https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/flask_restful/__init__.py#L200-L213
train
flask-restful/flask-restful
flask_restful/__init__.py
Api._should_use_fr_error_handler
def _should_use_fr_error_handler(self): """ Determine if error should be handled with FR or default Flask The goal is to return Flask error handlers for non-FR-related routes, and FR errors (with the correct media type) for FR endpoints. This method currently handles 404 and 405 errors....
python
def _should_use_fr_error_handler(self): """ Determine if error should be handled with FR or default Flask The goal is to return Flask error handlers for non-FR-related routes, and FR errors (with the correct media type) for FR endpoints. This method currently handles 404 and 405 errors....
[ "def", "_should_use_fr_error_handler", "(", "self", ")", ":", "adapter", "=", "current_app", ".", "create_url_adapter", "(", "request", ")", "try", ":", "adapter", ".", "match", "(", ")", "except", "MethodNotAllowed", "as", "e", ":", "# Check if the other HTTP met...
Determine if error should be handled with FR or default Flask The goal is to return Flask error handlers for non-FR-related routes, and FR errors (with the correct media type) for FR endpoints. This method currently handles 404 and 405 errors. :return: bool
[ "Determine", "if", "error", "should", "be", "handled", "with", "FR", "or", "default", "Flask" ]
25544d697c1f82bafbd1320960df459f58a58e03
https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/flask_restful/__init__.py#L215-L237
train
flask-restful/flask-restful
flask_restful/__init__.py
Api._has_fr_route
def _has_fr_route(self): """Encapsulating the rules for whether the request was to a Flask endpoint""" # 404's, 405's, which might not have a url_rule if self._should_use_fr_error_handler(): return True # for all other errors, just check if FR dispatched the route if ...
python
def _has_fr_route(self): """Encapsulating the rules for whether the request was to a Flask endpoint""" # 404's, 405's, which might not have a url_rule if self._should_use_fr_error_handler(): return True # for all other errors, just check if FR dispatched the route if ...
[ "def", "_has_fr_route", "(", "self", ")", ":", "# 404's, 405's, which might not have a url_rule", "if", "self", ".", "_should_use_fr_error_handler", "(", ")", ":", "return", "True", "# for all other errors, just check if FR dispatched the route", "if", "not", "request", ".", ...
Encapsulating the rules for whether the request was to a Flask endpoint
[ "Encapsulating", "the", "rules", "for", "whether", "the", "request", "was", "to", "a", "Flask", "endpoint" ]
25544d697c1f82bafbd1320960df459f58a58e03
https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/flask_restful/__init__.py#L239-L247
train
flask-restful/flask-restful
flask_restful/__init__.py
Api.error_router
def error_router(self, original_handler, e): """This function decides whether the error occured in a flask-restful endpoint or not. If it happened in a flask-restful endpoint, our handler will be dispatched. If it happened in an unrelated view, the app's original error handler will be di...
python
def error_router(self, original_handler, e): """This function decides whether the error occured in a flask-restful endpoint or not. If it happened in a flask-restful endpoint, our handler will be dispatched. If it happened in an unrelated view, the app's original error handler will be di...
[ "def", "error_router", "(", "self", ",", "original_handler", ",", "e", ")", ":", "if", "self", ".", "_has_fr_route", "(", ")", ":", "try", ":", "return", "self", ".", "handle_error", "(", "e", ")", "except", "Exception", ":", "pass", "# Fall through to ori...
This function decides whether the error occured in a flask-restful endpoint or not. If it happened in a flask-restful endpoint, our handler will be dispatched. If it happened in an unrelated view, the app's original error handler will be dispatched. In the event that the error occurred i...
[ "This", "function", "decides", "whether", "the", "error", "occured", "in", "a", "flask", "-", "restful", "endpoint", "or", "not", ".", "If", "it", "happened", "in", "a", "flask", "-", "restful", "endpoint", "our", "handler", "will", "be", "dispatched", "."...
25544d697c1f82bafbd1320960df459f58a58e03
https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/flask_restful/__init__.py#L249-L269
train
flask-restful/flask-restful
flask_restful/__init__.py
Api.handle_error
def handle_error(self, e): """Error handler for the API transforms a raised exception into a Flask response, with the appropriate HTTP status code and body. :param e: the raised Exception object :type e: Exception """ got_request_exception.send(current_app._get_current_...
python
def handle_error(self, e): """Error handler for the API transforms a raised exception into a Flask response, with the appropriate HTTP status code and body. :param e: the raised Exception object :type e: Exception """ got_request_exception.send(current_app._get_current_...
[ "def", "handle_error", "(", "self", ",", "e", ")", ":", "got_request_exception", ".", "send", "(", "current_app", ".", "_get_current_object", "(", ")", ",", "exception", "=", "e", ")", "if", "not", "isinstance", "(", "e", ",", "HTTPException", ")", "and", ...
Error handler for the API transforms a raised exception into a Flask response, with the appropriate HTTP status code and body. :param e: the raised Exception object :type e: Exception
[ "Error", "handler", "for", "the", "API", "transforms", "a", "raised", "exception", "into", "a", "Flask", "response", "with", "the", "appropriate", "HTTP", "status", "code", "and", "body", "." ]
25544d697c1f82bafbd1320960df459f58a58e03
https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/flask_restful/__init__.py#L271-L341
train
flask-restful/flask-restful
flask_restful/__init__.py
Api.add_resource
def add_resource(self, resource, *urls, **kwargs): """Adds a resource to the api. :param resource: the class name of your resource :type resource: :class:`Type[Resource]` :param urls: one or more url routes to match for the resource, standard flask routing rules ap...
python
def add_resource(self, resource, *urls, **kwargs): """Adds a resource to the api. :param resource: the class name of your resource :type resource: :class:`Type[Resource]` :param urls: one or more url routes to match for the resource, standard flask routing rules ap...
[ "def", "add_resource", "(", "self", ",", "resource", ",", "*", "urls", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "app", "is", "not", "None", ":", "self", ".", "_register_view", "(", "self", ".", "app", ",", "resource", ",", "*", "urls",...
Adds a resource to the api. :param resource: the class name of your resource :type resource: :class:`Type[Resource]` :param urls: one or more url routes to match for the resource, standard flask routing rules apply. Any url variables will be passed to...
[ "Adds", "a", "resource", "to", "the", "api", "." ]
25544d697c1f82bafbd1320960df459f58a58e03
https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/flask_restful/__init__.py#L348-L384
train
flask-restful/flask-restful
flask_restful/__init__.py
Api.resource
def resource(self, *urls, **kwargs): """Wraps a :class:`~flask_restful.Resource` class, adding it to the api. Parameters are the same as :meth:`~flask_restful.Api.add_resource`. Example:: app = Flask(__name__) api = restful.Api(app) @api.resource('/foo') ...
python
def resource(self, *urls, **kwargs): """Wraps a :class:`~flask_restful.Resource` class, adding it to the api. Parameters are the same as :meth:`~flask_restful.Api.add_resource`. Example:: app = Flask(__name__) api = restful.Api(app) @api.resource('/foo') ...
[ "def", "resource", "(", "self", ",", "*", "urls", ",", "*", "*", "kwargs", ")", ":", "def", "decorator", "(", "cls", ")", ":", "self", ".", "add_resource", "(", "cls", ",", "*", "urls", ",", "*", "*", "kwargs", ")", "return", "cls", "return", "de...
Wraps a :class:`~flask_restful.Resource` class, adding it to the api. Parameters are the same as :meth:`~flask_restful.Api.add_resource`. Example:: app = Flask(__name__) api = restful.Api(app) @api.resource('/foo') class Foo(Resource): d...
[ "Wraps", "a", ":", "class", ":", "~flask_restful", ".", "Resource", "class", "adding", "it", "to", "the", "api", ".", "Parameters", "are", "the", "same", "as", ":", "meth", ":", "~flask_restful", ".", "Api", ".", "add_resource", "." ]
25544d697c1f82bafbd1320960df459f58a58e03
https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/flask_restful/__init__.py#L386-L404
train
flask-restful/flask-restful
flask_restful/__init__.py
Api.output
def output(self, resource): """Wraps a resource (as a flask view function), for cases where the resource does not directly return a response object :param resource: The resource as a flask view function """ @wraps(resource) def wrapper(*args, **kwargs): resp ...
python
def output(self, resource): """Wraps a resource (as a flask view function), for cases where the resource does not directly return a response object :param resource: The resource as a flask view function """ @wraps(resource) def wrapper(*args, **kwargs): resp ...
[ "def", "output", "(", "self", ",", "resource", ")", ":", "@", "wraps", "(", "resource", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "resp", "=", "resource", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "...
Wraps a resource (as a flask view function), for cases where the resource does not directly return a response object :param resource: The resource as a flask view function
[ "Wraps", "a", "resource", "(", "as", "a", "flask", "view", "function", ")", "for", "cases", "where", "the", "resource", "does", "not", "directly", "return", "a", "response", "object" ]
25544d697c1f82bafbd1320960df459f58a58e03
https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/flask_restful/__init__.py#L450-L463
train
flask-restful/flask-restful
flask_restful/__init__.py
Api.url_for
def url_for(self, resource, **values): """Generates a URL to the given resource. Works like :func:`flask.url_for`.""" endpoint = resource.endpoint if self.blueprint: endpoint = '{0}.{1}'.format(self.blueprint.name, endpoint) return url_for(endpoint, **values)
python
def url_for(self, resource, **values): """Generates a URL to the given resource. Works like :func:`flask.url_for`.""" endpoint = resource.endpoint if self.blueprint: endpoint = '{0}.{1}'.format(self.blueprint.name, endpoint) return url_for(endpoint, **values)
[ "def", "url_for", "(", "self", ",", "resource", ",", "*", "*", "values", ")", ":", "endpoint", "=", "resource", ".", "endpoint", "if", "self", ".", "blueprint", ":", "endpoint", "=", "'{0}.{1}'", ".", "format", "(", "self", ".", "blueprint", ".", "name...
Generates a URL to the given resource. Works like :func:`flask.url_for`.
[ "Generates", "a", "URL", "to", "the", "given", "resource", "." ]
25544d697c1f82bafbd1320960df459f58a58e03
https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/flask_restful/__init__.py#L465-L472
train
flask-restful/flask-restful
flask_restful/__init__.py
Api.make_response
def make_response(self, data, *args, **kwargs): """Looks up the representation transformer for the requested media type, invoking the transformer to create a response object. This defaults to default_mediatype if no transformer is found for the requested mediatype. If default_mediatype i...
python
def make_response(self, data, *args, **kwargs): """Looks up the representation transformer for the requested media type, invoking the transformer to create a response object. This defaults to default_mediatype if no transformer is found for the requested mediatype. If default_mediatype i...
[ "def", "make_response", "(", "self", ",", "data", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "default_mediatype", "=", "kwargs", ".", "pop", "(", "'fallback_mediatype'", ",", "None", ")", "or", "self", ".", "default_mediatype", "mediatype", "=", ...
Looks up the representation transformer for the requested media type, invoking the transformer to create a response object. This defaults to default_mediatype if no transformer is found for the requested mediatype. If default_mediatype is None, a 406 Not Acceptable response will be sent ...
[ "Looks", "up", "the", "representation", "transformer", "for", "the", "requested", "media", "type", "invoking", "the", "transformer", "to", "create", "a", "response", "object", ".", "This", "defaults", "to", "default_mediatype", "if", "no", "transformer", "is", "...
25544d697c1f82bafbd1320960df459f58a58e03
https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/flask_restful/__init__.py#L474-L499
train
flask-restful/flask-restful
flask_restful/__init__.py
Api.mediatypes
def mediatypes(self): """Returns a list of requested mediatypes sent in the Accept header""" return [h for h, q in sorted(request.accept_mimetypes, key=operator.itemgetter(1), reverse=True)]
python
def mediatypes(self): """Returns a list of requested mediatypes sent in the Accept header""" return [h for h, q in sorted(request.accept_mimetypes, key=operator.itemgetter(1), reverse=True)]
[ "def", "mediatypes", "(", "self", ")", ":", "return", "[", "h", "for", "h", ",", "q", "in", "sorted", "(", "request", ".", "accept_mimetypes", ",", "key", "=", "operator", ".", "itemgetter", "(", "1", ")", ",", "reverse", "=", "True", ")", "]" ]
Returns a list of requested mediatypes sent in the Accept header
[ "Returns", "a", "list", "of", "requested", "mediatypes", "sent", "in", "the", "Accept", "header" ]
25544d697c1f82bafbd1320960df459f58a58e03
https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/flask_restful/__init__.py#L501-L504
train
flask-restful/flask-restful
flask_restful/__init__.py
Api.representation
def representation(self, mediatype): """Allows additional representation transformers to be declared for the api. Transformers are functions that must be decorated with this method, passing the mediatype the transformer represents. Three arguments are passed to the transformer: ...
python
def representation(self, mediatype): """Allows additional representation transformers to be declared for the api. Transformers are functions that must be decorated with this method, passing the mediatype the transformer represents. Three arguments are passed to the transformer: ...
[ "def", "representation", "(", "self", ",", "mediatype", ")", ":", "def", "wrapper", "(", "func", ")", ":", "self", ".", "representations", "[", "mediatype", "]", "=", "func", "return", "func", "return", "wrapper" ]
Allows additional representation transformers to be declared for the api. Transformers are functions that must be decorated with this method, passing the mediatype the transformer represents. Three arguments are passed to the transformer: * The data to be represented in the response bod...
[ "Allows", "additional", "representation", "transformers", "to", "be", "declared", "for", "the", "api", ".", "Transformers", "are", "functions", "that", "must", "be", "decorated", "with", "this", "method", "passing", "the", "mediatype", "the", "transformer", "repre...
25544d697c1f82bafbd1320960df459f58a58e03
https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/flask_restful/__init__.py#L506-L530
train
flask-restful/flask-restful
flask_restful/reqparse.py
Argument.source
def source(self, request): """Pulls values off the request in the provided location :param request: The flask request object to parse arguments from """ if isinstance(self.location, six.string_types): value = getattr(request, self.location, MultiDict()) if callabl...
python
def source(self, request): """Pulls values off the request in the provided location :param request: The flask request object to parse arguments from """ if isinstance(self.location, six.string_types): value = getattr(request, self.location, MultiDict()) if callabl...
[ "def", "source", "(", "self", ",", "request", ")", ":", "if", "isinstance", "(", "self", ".", "location", ",", "six", ".", "string_types", ")", ":", "value", "=", "getattr", "(", "request", ",", "self", ".", "location", ",", "MultiDict", "(", ")", ")...
Pulls values off the request in the provided location :param request: The flask request object to parse arguments from
[ "Pulls", "values", "off", "the", "request", "in", "the", "provided", "location", ":", "param", "request", ":", "The", "flask", "request", "object", "to", "parse", "arguments", "from" ]
25544d697c1f82bafbd1320960df459f58a58e03
https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/flask_restful/reqparse.py#L109-L129
train
flask-restful/flask-restful
flask_restful/reqparse.py
Argument.handle_validation_error
def handle_validation_error(self, error, bundle_errors): """Called when an error is raised while parsing. Aborts the request with a 400 status and an error message :param error: the error that was raised :param bundle_errors: do not abort when first error occurs, return a di...
python
def handle_validation_error(self, error, bundle_errors): """Called when an error is raised while parsing. Aborts the request with a 400 status and an error message :param error: the error that was raised :param bundle_errors: do not abort when first error occurs, return a di...
[ "def", "handle_validation_error", "(", "self", ",", "error", ",", "bundle_errors", ")", ":", "error_str", "=", "six", ".", "text_type", "(", "error", ")", "error_msg", "=", "self", ".", "help", ".", "format", "(", "error_msg", "=", "error_str", ")", "if", ...
Called when an error is raised while parsing. Aborts the request with a 400 status and an error message :param error: the error that was raised :param bundle_errors: do not abort when first error occurs, return a dict with the name of the argument and the error message to be ...
[ "Called", "when", "an", "error", "is", "raised", "while", "parsing", ".", "Aborts", "the", "request", "with", "a", "400", "status", "and", "an", "error", "message" ]
25544d697c1f82bafbd1320960df459f58a58e03
https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/flask_restful/reqparse.py#L155-L170
train
flask-restful/flask-restful
flask_restful/reqparse.py
Argument.parse
def parse(self, request, bundle_errors=False): """Parses argument value(s) from the request, converting according to the argument's type. :param request: The flask request object to parse arguments from :param bundle_errors: Do not abort when first error occurs, return a dic...
python
def parse(self, request, bundle_errors=False): """Parses argument value(s) from the request, converting according to the argument's type. :param request: The flask request object to parse arguments from :param bundle_errors: Do not abort when first error occurs, return a dic...
[ "def", "parse", "(", "self", ",", "request", ",", "bundle_errors", "=", "False", ")", ":", "source", "=", "self", ".", "source", "(", "request", ")", "results", "=", "[", "]", "# Sentinels", "_not_found", "=", "False", "_found", "=", "True", "for", "op...
Parses argument value(s) from the request, converting according to the argument's type. :param request: The flask request object to parse arguments from :param bundle_errors: Do not abort when first error occurs, return a dict with the name of the argument and the error message to b...
[ "Parses", "argument", "value", "(", "s", ")", "from", "the", "request", "converting", "according", "to", "the", "argument", "s", "type", "." ]
25544d697c1f82bafbd1320960df459f58a58e03
https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/flask_restful/reqparse.py#L172-L256
train
flask-restful/flask-restful
flask_restful/reqparse.py
RequestParser.add_argument
def add_argument(self, *args, **kwargs): """Adds an argument to be parsed. Accepts either a single instance of Argument or arguments to be passed into :class:`Argument`'s constructor. See :class:`Argument`'s constructor for documentation on the available options. """ ...
python
def add_argument(self, *args, **kwargs): """Adds an argument to be parsed. Accepts either a single instance of Argument or arguments to be passed into :class:`Argument`'s constructor. See :class:`Argument`'s constructor for documentation on the available options. """ ...
[ "def", "add_argument", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "args", ")", "==", "1", "and", "isinstance", "(", "args", "[", "0", "]", ",", "self", ".", "argument_class", ")", ":", "self", ".", "args",...
Adds an argument to be parsed. Accepts either a single instance of Argument or arguments to be passed into :class:`Argument`'s constructor. See :class:`Argument`'s constructor for documentation on the available options.
[ "Adds", "an", "argument", "to", "be", "parsed", "." ]
25544d697c1f82bafbd1320960df459f58a58e03
https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/flask_restful/reqparse.py#L285-L305
train
flask-restful/flask-restful
flask_restful/reqparse.py
RequestParser.parse_args
def parse_args(self, req=None, strict=False, http_error_code=400): """Parse all arguments from the provided request and return the results as a Namespace :param req: Can be used to overwrite request from Flask :param strict: if req includes args not in parser, throw 400 BadRequest excep...
python
def parse_args(self, req=None, strict=False, http_error_code=400): """Parse all arguments from the provided request and return the results as a Namespace :param req: Can be used to overwrite request from Flask :param strict: if req includes args not in parser, throw 400 BadRequest excep...
[ "def", "parse_args", "(", "self", ",", "req", "=", "None", ",", "strict", "=", "False", ",", "http_error_code", "=", "400", ")", ":", "if", "req", "is", "None", ":", "req", "=", "request", "namespace", "=", "self", ".", "namespace_class", "(", ")", "...
Parse all arguments from the provided request and return the results as a Namespace :param req: Can be used to overwrite request from Flask :param strict: if req includes args not in parser, throw 400 BadRequest exception :param http_error_code: use custom error code for `flask_restful....
[ "Parse", "all", "arguments", "from", "the", "provided", "request", "and", "return", "the", "results", "as", "a", "Namespace" ]
25544d697c1f82bafbd1320960df459f58a58e03
https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/flask_restful/reqparse.py#L307-L338
train
flask-restful/flask-restful
flask_restful/reqparse.py
RequestParser.copy
def copy(self): """ Creates a copy of this RequestParser with the same set of arguments """ parser_copy = self.__class__(self.argument_class, self.namespace_class) parser_copy.args = deepcopy(self.args) parser_copy.trim = self.trim parser_copy.bundle_errors = self.bundle_errors ...
python
def copy(self): """ Creates a copy of this RequestParser with the same set of arguments """ parser_copy = self.__class__(self.argument_class, self.namespace_class) parser_copy.args = deepcopy(self.args) parser_copy.trim = self.trim parser_copy.bundle_errors = self.bundle_errors ...
[ "def", "copy", "(", "self", ")", ":", "parser_copy", "=", "self", ".", "__class__", "(", "self", ".", "argument_class", ",", "self", ".", "namespace_class", ")", "parser_copy", ".", "args", "=", "deepcopy", "(", "self", ".", "args", ")", "parser_copy", "...
Creates a copy of this RequestParser with the same set of arguments
[ "Creates", "a", "copy", "of", "this", "RequestParser", "with", "the", "same", "set", "of", "arguments" ]
25544d697c1f82bafbd1320960df459f58a58e03
https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/flask_restful/reqparse.py#L340-L346
train
flask-restful/flask-restful
flask_restful/reqparse.py
RequestParser.replace_argument
def replace_argument(self, name, *args, **kwargs): """ Replace the argument matching the given name with a new version. """ new_arg = self.argument_class(name, *args, **kwargs) for index, arg in enumerate(self.args[:]): if new_arg.name == arg.name: del self.args[index...
python
def replace_argument(self, name, *args, **kwargs): """ Replace the argument matching the given name with a new version. """ new_arg = self.argument_class(name, *args, **kwargs) for index, arg in enumerate(self.args[:]): if new_arg.name == arg.name: del self.args[index...
[ "def", "replace_argument", "(", "self", ",", "name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "new_arg", "=", "self", ".", "argument_class", "(", "name", ",", "*", "args", ",", "*", "*", "kwargs", ")", "for", "index", ",", "arg", "in", ...
Replace the argument matching the given name with a new version.
[ "Replace", "the", "argument", "matching", "the", "given", "name", "with", "a", "new", "version", "." ]
25544d697c1f82bafbd1320960df459f58a58e03
https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/flask_restful/reqparse.py#L348-L356
train
flask-restful/flask-restful
flask_restful/reqparse.py
RequestParser.remove_argument
def remove_argument(self, name): """ Remove the argument matching the given name. """ for index, arg in enumerate(self.args[:]): if name == arg.name: del self.args[index] break return self
python
def remove_argument(self, name): """ Remove the argument matching the given name. """ for index, arg in enumerate(self.args[:]): if name == arg.name: del self.args[index] break return self
[ "def", "remove_argument", "(", "self", ",", "name", ")", ":", "for", "index", ",", "arg", "in", "enumerate", "(", "self", ".", "args", "[", ":", "]", ")", ":", "if", "name", "==", "arg", ".", "name", ":", "del", "self", ".", "args", "[", "index",...
Remove the argument matching the given name.
[ "Remove", "the", "argument", "matching", "the", "given", "name", "." ]
25544d697c1f82bafbd1320960df459f58a58e03
https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/flask_restful/reqparse.py#L358-L364
train
flask-restful/flask-restful
flask_restful/fields.py
to_marshallable_type
def to_marshallable_type(obj): """Helper for converting an object to a dictionary only if it is not dictionary already or an indexable object nor a simple type""" if obj is None: return None # make it idempotent for None if hasattr(obj, '__marshallable__'): return obj.__marshallable__(...
python
def to_marshallable_type(obj): """Helper for converting an object to a dictionary only if it is not dictionary already or an indexable object nor a simple type""" if obj is None: return None # make it idempotent for None if hasattr(obj, '__marshallable__'): return obj.__marshallable__(...
[ "def", "to_marshallable_type", "(", "obj", ")", ":", "if", "obj", "is", "None", ":", "return", "None", "# make it idempotent for None", "if", "hasattr", "(", "obj", ",", "'__marshallable__'", ")", ":", "return", "obj", ".", "__marshallable__", "(", ")", "if", ...
Helper for converting an object to a dictionary only if it is not dictionary already or an indexable object nor a simple type
[ "Helper", "for", "converting", "an", "object", "to", "a", "dictionary", "only", "if", "it", "is", "not", "dictionary", "already", "or", "an", "indexable", "object", "nor", "a", "simple", "type" ]
25544d697c1f82bafbd1320960df459f58a58e03
https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/flask_restful/fields.py#L63-L75
train
flask-restful/flask-restful
flask_restful/fields.py
Raw.output
def output(self, key, obj): """Pulls the value for the given key from the object, applies the field's formatting and returns the result. If the key is not found in the object, returns the default value. Field classes that create values which do not require the existence of the key in the...
python
def output(self, key, obj): """Pulls the value for the given key from the object, applies the field's formatting and returns the result. If the key is not found in the object, returns the default value. Field classes that create values which do not require the existence of the key in the...
[ "def", "output", "(", "self", ",", "key", ",", "obj", ")", ":", "value", "=", "get_value", "(", "key", "if", "self", ".", "attribute", "is", "None", "else", "self", ".", "attribute", ",", "obj", ")", "if", "value", "is", "None", ":", "return", "sel...
Pulls the value for the given key from the object, applies the field's formatting and returns the result. If the key is not found in the object, returns the default value. Field classes that create values which do not require the existence of the key in the object should override this an...
[ "Pulls", "the", "value", "for", "the", "given", "key", "from", "the", "object", "applies", "the", "field", "s", "formatting", "and", "returns", "the", "result", ".", "If", "the", "key", "is", "not", "found", "in", "the", "object", "returns", "the", "defa...
25544d697c1f82bafbd1320960df459f58a58e03
https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/flask_restful/fields.py#L111-L126
train
flask-restful/flask-restful
flask_restful/inputs.py
url
def url(value): """Validate a URL. :param string value: The URL to validate :returns: The URL if valid. :raises: ValueError """ if not url_regex.search(value): message = u"{0} is not a valid URL".format(value) if url_regex.search('http://' + value): message += u". Di...
python
def url(value): """Validate a URL. :param string value: The URL to validate :returns: The URL if valid. :raises: ValueError """ if not url_regex.search(value): message = u"{0} is not a valid URL".format(value) if url_regex.search('http://' + value): message += u". Di...
[ "def", "url", "(", "value", ")", ":", "if", "not", "url_regex", ".", "search", "(", "value", ")", ":", "message", "=", "u\"{0} is not a valid URL\"", ".", "format", "(", "value", ")", "if", "url_regex", ".", "search", "(", "'http://'", "+", "value", ")",...
Validate a URL. :param string value: The URL to validate :returns: The URL if valid. :raises: ValueError
[ "Validate", "a", "URL", "." ]
25544d697c1f82bafbd1320960df459f58a58e03
https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/flask_restful/inputs.py#L28-L40
train
flask-restful/flask-restful
flask_restful/inputs.py
_normalize_interval
def _normalize_interval(start, end, value): """Normalize datetime intervals. Given a pair of datetime.date or datetime.datetime objects, returns a 2-tuple of tz-aware UTC datetimes spanning the same interval. For datetime.date objects, the returned interval starts at 00:00:00.0 on the first date a...
python
def _normalize_interval(start, end, value): """Normalize datetime intervals. Given a pair of datetime.date or datetime.datetime objects, returns a 2-tuple of tz-aware UTC datetimes spanning the same interval. For datetime.date objects, the returned interval starts at 00:00:00.0 on the first date a...
[ "def", "_normalize_interval", "(", "start", ",", "end", ",", "value", ")", ":", "if", "not", "isinstance", "(", "start", ",", "datetime", ")", ":", "start", "=", "datetime", ".", "combine", "(", "start", ",", "START_OF_DAY", ")", "end", "=", "datetime", ...
Normalize datetime intervals. Given a pair of datetime.date or datetime.datetime objects, returns a 2-tuple of tz-aware UTC datetimes spanning the same interval. For datetime.date objects, the returned interval starts at 00:00:00.0 on the first date and ends at 00:00:00.0 on the second. Naive dat...
[ "Normalize", "datetime", "intervals", "." ]
25544d697c1f82bafbd1320960df459f58a58e03
https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/flask_restful/inputs.py#L74-L102
train
flask-restful/flask-restful
flask_restful/inputs.py
_parse_interval
def _parse_interval(value): """Do some nasty try/except voodoo to get some sort of datetime object(s) out of the string. """ try: return sorted(aniso8601.parse_interval(value)) except ValueError: try: return aniso8601.parse_datetime(value), None except ValueError:...
python
def _parse_interval(value): """Do some nasty try/except voodoo to get some sort of datetime object(s) out of the string. """ try: return sorted(aniso8601.parse_interval(value)) except ValueError: try: return aniso8601.parse_datetime(value), None except ValueError:...
[ "def", "_parse_interval", "(", "value", ")", ":", "try", ":", "return", "sorted", "(", "aniso8601", ".", "parse_interval", "(", "value", ")", ")", "except", "ValueError", ":", "try", ":", "return", "aniso8601", ".", "parse_datetime", "(", "value", ")", ","...
Do some nasty try/except voodoo to get some sort of datetime object(s) out of the string.
[ "Do", "some", "nasty", "try", "/", "except", "voodoo", "to", "get", "some", "sort", "of", "datetime", "object", "(", "s", ")", "out", "of", "the", "string", "." ]
25544d697c1f82bafbd1320960df459f58a58e03
https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/flask_restful/inputs.py#L129-L139
train
flask-restful/flask-restful
flask_restful/inputs.py
iso8601interval
def iso8601interval(value, argument='argument'): """Parses ISO 8601-formatted datetime intervals into tuples of datetimes. Accepts both a single date(time) or a full interval using either start/end or start/duration notation, with the following behavior: - Intervals are defined as inclusive start, exc...
python
def iso8601interval(value, argument='argument'): """Parses ISO 8601-formatted datetime intervals into tuples of datetimes. Accepts both a single date(time) or a full interval using either start/end or start/duration notation, with the following behavior: - Intervals are defined as inclusive start, exc...
[ "def", "iso8601interval", "(", "value", ",", "argument", "=", "'argument'", ")", ":", "try", ":", "start", ",", "end", "=", "_parse_interval", "(", "value", ")", "if", "end", "is", "None", ":", "end", "=", "_expand_datetime", "(", "start", ",", "value", ...
Parses ISO 8601-formatted datetime intervals into tuples of datetimes. Accepts both a single date(time) or a full interval using either start/end or start/duration notation, with the following behavior: - Intervals are defined as inclusive start, exclusive end - Single datetimes are translated into th...
[ "Parses", "ISO", "8601", "-", "formatted", "datetime", "intervals", "into", "tuples", "of", "datetimes", "." ]
25544d697c1f82bafbd1320960df459f58a58e03
https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/flask_restful/inputs.py#L142-L184
train
flask-restful/flask-restful
flask_restful/inputs.py
natural
def natural(value, argument='argument'): """ Restrict input type to the natural numbers (0, 1, 2, 3...) """ value = _get_integer(value) if value < 0: error = ('Invalid {arg}: {value}. {arg} must be a non-negative ' 'integer'.format(arg=argument, value=value)) raise ValueErro...
python
def natural(value, argument='argument'): """ Restrict input type to the natural numbers (0, 1, 2, 3...) """ value = _get_integer(value) if value < 0: error = ('Invalid {arg}: {value}. {arg} must be a non-negative ' 'integer'.format(arg=argument, value=value)) raise ValueErro...
[ "def", "natural", "(", "value", ",", "argument", "=", "'argument'", ")", ":", "value", "=", "_get_integer", "(", "value", ")", "if", "value", "<", "0", ":", "error", "=", "(", "'Invalid {arg}: {value}. {arg} must be a non-negative '", "'integer'", ".", "format",...
Restrict input type to the natural numbers (0, 1, 2, 3...)
[ "Restrict", "input", "type", "to", "the", "natural", "numbers", "(", "0", "1", "2", "3", "...", ")" ]
25544d697c1f82bafbd1320960df459f58a58e03
https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/flask_restful/inputs.py#L200-L207
train
flask-restful/flask-restful
flask_restful/inputs.py
positive
def positive(value, argument='argument'): """ Restrict input type to the positive integers (1, 2, 3...) """ value = _get_integer(value) if value < 1: error = ('Invalid {arg}: {value}. {arg} must be a positive ' 'integer'.format(arg=argument, value=value)) raise ValueError(er...
python
def positive(value, argument='argument'): """ Restrict input type to the positive integers (1, 2, 3...) """ value = _get_integer(value) if value < 1: error = ('Invalid {arg}: {value}. {arg} must be a positive ' 'integer'.format(arg=argument, value=value)) raise ValueError(er...
[ "def", "positive", "(", "value", ",", "argument", "=", "'argument'", ")", ":", "value", "=", "_get_integer", "(", "value", ")", "if", "value", "<", "1", ":", "error", "=", "(", "'Invalid {arg}: {value}. {arg} must be a positive '", "'integer'", ".", "format", ...
Restrict input type to the positive integers (1, 2, 3...)
[ "Restrict", "input", "type", "to", "the", "positive", "integers", "(", "1", "2", "3", "...", ")" ]
25544d697c1f82bafbd1320960df459f58a58e03
https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/flask_restful/inputs.py#L210-L217
train
flask-restful/flask-restful
flask_restful/inputs.py
boolean
def boolean(value): """Parse the string ``"true"`` or ``"false"`` as a boolean (case insensitive). Also accepts ``"1"`` and ``"0"`` as ``True``/``False`` (respectively). If the input is from the request JSON body, the type is already a native python boolean, and will be passed through without furthe...
python
def boolean(value): """Parse the string ``"true"`` or ``"false"`` as a boolean (case insensitive). Also accepts ``"1"`` and ``"0"`` as ``True``/``False`` (respectively). If the input is from the request JSON body, the type is already a native python boolean, and will be passed through without furthe...
[ "def", "boolean", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "bool", ")", ":", "return", "value", "if", "not", "value", ":", "raise", "ValueError", "(", "\"boolean type must be non-null\"", ")", "value", "=", "value", ".", "lower", "(",...
Parse the string ``"true"`` or ``"false"`` as a boolean (case insensitive). Also accepts ``"1"`` and ``"0"`` as ``True``/``False`` (respectively). If the input is from the request JSON body, the type is already a native python boolean, and will be passed through without further parsing.
[ "Parse", "the", "string", "true", "or", "false", "as", "a", "boolean", "(", "case", "insensitive", ")", ".", "Also", "accepts", "1", "and", "0", "as", "True", "/", "False", "(", "respectively", ")", ".", "If", "the", "input", "is", "from", "the", "re...
25544d697c1f82bafbd1320960df459f58a58e03
https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/flask_restful/inputs.py#L237-L254
train
asweigart/pyautogui
pyautogui/_pyautogui_osx.py
_specialKeyEvent
def _specialKeyEvent(key, upDown): """ Helper method for special keys. Source: http://stackoverflow.com/questions/11045814/emulate-media-key-press-on-mac """ assert upDown in ('up', 'down'), "upDown argument must be 'up' or 'down'" key_code = special_key_translate_table[key] ev = AppKit.NSEve...
python
def _specialKeyEvent(key, upDown): """ Helper method for special keys. Source: http://stackoverflow.com/questions/11045814/emulate-media-key-press-on-mac """ assert upDown in ('up', 'down'), "upDown argument must be 'up' or 'down'" key_code = special_key_translate_table[key] ev = AppKit.NSEve...
[ "def", "_specialKeyEvent", "(", "key", ",", "upDown", ")", ":", "assert", "upDown", "in", "(", "'up'", ",", "'down'", ")", ",", "\"upDown argument must be 'up' or 'down'\"", "key_code", "=", "special_key_translate_table", "[", "key", "]", "ev", "=", "AppKit", "....
Helper method for special keys. Source: http://stackoverflow.com/questions/11045814/emulate-media-key-press-on-mac
[ "Helper", "method", "for", "special", "keys", "." ]
77524bd47334a89024013fd48e05151c3ac9289a
https://github.com/asweigart/pyautogui/blob/77524bd47334a89024013fd48e05151c3ac9289a/pyautogui/_pyautogui_osx.py#L264-L285
train
asweigart/pyautogui
pyautogui/_pyautogui_x11.py
_keyDown
def _keyDown(key): """Performs a keyboard key press without the release. This will put that key in a held down state. NOTE: For some reason, this does not seem to cause key repeats like would happen if a keyboard key was held down on a text field. Args: key (str): The key to be pressed down....
python
def _keyDown(key): """Performs a keyboard key press without the release. This will put that key in a held down state. NOTE: For some reason, this does not seem to cause key repeats like would happen if a keyboard key was held down on a text field. Args: key (str): The key to be pressed down....
[ "def", "_keyDown", "(", "key", ")", ":", "if", "key", "not", "in", "keyboardMapping", "or", "keyboardMapping", "[", "key", "]", "is", "None", ":", "return", "if", "type", "(", "key", ")", "==", "int", ":", "fake_input", "(", "_display", ",", "X", "."...
Performs a keyboard key press without the release. This will put that key in a held down state. NOTE: For some reason, this does not seem to cause key repeats like would happen if a keyboard key was held down on a text field. Args: key (str): The key to be pressed down. The valid names are liste...
[ "Performs", "a", "keyboard", "key", "press", "without", "the", "release", ".", "This", "will", "put", "that", "key", "in", "a", "held", "down", "state", "." ]
77524bd47334a89024013fd48e05151c3ac9289a
https://github.com/asweigart/pyautogui/blob/77524bd47334a89024013fd48e05151c3ac9289a/pyautogui/_pyautogui_x11.py#L99-L129
train