idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
29,900
def get_indexes ( self ) : ret = { } for index in self . iter_query_indexes ( ) : ret [ index . name ] = index return ret
Get a dict of index names to index
29,901
def from_description ( cls , table ) : throughput = table . provisioned_throughput attrs = { } for data in getattr ( table , "attribute_definitions" , [ ] ) : field = TableField ( data [ "AttributeName" ] , TYPES_REV [ data [ "AttributeType" ] ] ) attrs [ field . name ] = field for data in getattr ( table , "key_schema...
Factory method that uses the dynamo3 describe return value
29,902
def primary_key_attributes ( self ) : if self . range_key is None : return ( self . hash_key . name , ) else : return ( self . hash_key . name , self . range_key . name )
Get the names of the primary key attributes as a tuple
29,903
def primary_key_tuple ( self , item ) : if self . range_key is None : return ( item [ self . hash_key . name ] , ) else : return ( item [ self . hash_key . name ] , item [ self . range_key . name ] )
Get the primary key tuple from an item
29,904
def primary_key ( self , hkey , rkey = None ) : if isinstance ( hkey , dict ) : def decode ( val ) : if isinstance ( val , Decimal ) : return float ( val ) return val pkey = { self . hash_key . name : decode ( hkey [ self . hash_key . name ] ) } if self . range_key is not None : pkey [ self . range_key . name ] = decod...
Construct a primary key dictionary
29,905
def total_read_throughput ( self ) : total = self . read_throughput for index in itervalues ( self . global_indexes ) : total += index . read_throughput return total
Combined read throughput of table and global indexes
29,906
def total_write_throughput ( self ) : total = self . write_throughput for index in itervalues ( self . global_indexes ) : total += index . write_throughput return total
Combined write throughput of table and global indexes
29,907
def schema ( self ) : attrs = self . attrs . copy ( ) parts = [ "CREATE" , "TABLE" , self . name , "(%s," % self . hash_key . schema ] del attrs [ self . hash_key . name ] if self . range_key : parts . append ( self . range_key . schema + "," ) del attrs [ self . range_key . name ] if attrs : attr_def = ", " . join ( [...
The DQL query that will construct this table s schema
29,908
def pformat ( self ) : lines = [ ] lines . append ( ( "%s (%s)" % ( self . name , self . status ) ) . center ( 50 , "-" ) ) lines . append ( "items: {0:,} ({1:,} bytes)" . format ( self . item_count , self . size ) ) cap = self . consumed_capacity . get ( "__table__" , { } ) read = "Read: " + format_throughput ( self ....
Pretty string format
29,909
def resolve ( val ) : name = val . getName ( ) if name == "number" : try : return int ( val . number ) except ValueError : return Decimal ( val . number ) elif name == "str" : return unwrap ( val . str ) elif name == "null" : return None elif name == "binary" : return Binary ( val . binary [ 2 : - 1 ] ) elif name == "s...
Convert a pyparsing value to the python type
29,910
def dt_to_ts ( value ) : if not isinstance ( value , datetime ) : return value return calendar . timegm ( value . utctimetuple ( ) ) + value . microsecond / 1000000.0
If value is a datetime convert to timestamp
29,911
def eval_function ( value ) : name , args = value [ 0 ] , value [ 1 : ] if name == "NOW" : return datetime . utcnow ( ) . replace ( tzinfo = tzutc ( ) ) elif name in [ "TIMESTAMP" , "TS" ] : return parse ( unwrap ( args [ 0 ] ) ) . replace ( tzinfo = tzlocal ( ) ) elif name in [ "UTCTIMESTAMP" , "UTCTS" ] : return pars...
Evaluate a timestamp function
29,912
def eval_interval ( interval ) : kwargs = { "years" : 0 , "months" : 0 , "weeks" : 0 , "days" : 0 , "hours" : 0 , "minutes" : 0 , "seconds" : 0 , "microseconds" : 0 , } for section in interval [ 1 : ] : name = section . getName ( ) if name == "year" : kwargs [ "years" ] += int ( section [ 0 ] ) elif name == "month" : k...
Evaluate an interval expression
29,913
def eval_expression ( value ) : start = eval_function ( value . ts_expression [ 0 ] ) interval = eval_interval ( value . ts_expression [ 2 ] ) op = value . ts_expression [ 1 ] if op == "+" : return start + interval elif op == "-" : return start - interval else : raise SyntaxError ( "Unrecognized operator %r" % op )
Evaluate a full time expression
29,914
def linkcode_resolve ( domain , info ) : if domain != 'py' or not info [ 'module' ] : return None filename = info [ 'module' ] . replace ( '.' , '/' ) mod = importlib . import_module ( info [ 'module' ] ) basename = os . path . splitext ( mod . __file__ ) [ 0 ] if basename . endswith ( '__init__' ) : filename += '/__in...
Link source code to github
29,915
def run ( self , stdscr ) : self . win = stdscr curses . curs_set ( 0 ) stdscr . timeout ( 0 ) curses . init_pair ( 1 , curses . COLOR_CYAN , curses . COLOR_BLACK ) curses . init_pair ( 2 , curses . COLOR_GREEN , curses . COLOR_BLACK ) curses . init_pair ( 3 , curses . COLOR_YELLOW , curses . COLOR_BLACK ) curses . ini...
Initialize curses and refresh in a loop
29,916
def _calc_min_width ( self , table ) : width = len ( table . name ) cap = table . consumed_capacity [ "__table__" ] width = max ( width , 4 + len ( "%.1f/%d" % ( cap [ "read" ] , table . read_throughput ) ) ) width = max ( width , 4 + len ( "%.1f/%d" % ( cap [ "write" ] , table . write_throughput ) ) ) for index_name ,...
Calculate the minimum allowable width for a table
29,917
def _add_throughput ( self , y , x , width , op , title , available , used ) : percent = float ( used ) / available self . win . addstr ( y , x , "[" ) try : self . win . addstr ( y , x + width - 1 , "]" ) except curses . error : pass x += 1 right = "%.1f/%d:%s" % ( used , available , op ) pieces = self . _progress_bar...
Write a single throughput measure to a row
29,918
def refresh ( self , fetch_data ) : self . win . erase ( ) height , width = getmaxyx ( ) if curses . is_term_resized ( height , width ) : self . win . clear ( ) curses . resizeterm ( height , width ) y = 1 x = 0 columns = [ ] column = [ ] for table in self . _tables : desc = self . engine . describe ( table , fetch_dat...
Redraw the display
29,919
def add ( a , b ) : if a is None : if b is None : return None else : return b elif b is None : return a return a + b
Add two values ignoring None
29,920
def sub ( a , b ) : if a is None : if b is None : return None else : return - 1 * b elif b is None : return a return a - b
Subtract two values ignoring None
29,921
def mul ( a , b ) : if a is None : if b is None : return None else : return b elif b is None : return a return a * b
Multiply two values ignoring None
29,922
def div ( a , b ) : if a is None : if b is None : return None else : return 1 / b elif b is None : return a return a / b
Divide two values ignoring None
29,923
def parse_expression ( clause ) : if isinstance ( clause , Expression ) : return clause elif hasattr ( clause , "getName" ) and clause . getName ( ) != "field" : if clause . getName ( ) == "nested" : return AttributeSelection . from_statement ( clause ) elif clause . getName ( ) == "function" : return SelectFunction . ...
For a clause that could be a field value or expression
29,924
def from_statement ( cls , statement ) : if statement [ 0 ] in [ "TS" , "TIMESTAMP" , "UTCTIMESTAMP" , "UTCTS" ] : return TimestampFunction . from_statement ( statement ) elif statement [ 0 ] in [ "NOW" , "UTCNOW" ] : return NowFunction . from_statement ( statement ) else : raise SyntaxError ( "Unknown function %r" % s...
Create a selection function from a statement
29,925
def select_functions ( expr ) : body = Group ( expr ) return Group ( function ( "timestamp" , body , caseless = True ) | function ( "ts" , body , caseless = True ) | function ( "utctimestamp" , body , caseless = True ) | function ( "utcts" , body , caseless = True ) | function ( "now" , caseless = True ) | function ( "...
Create the function expressions for selection
29,926
def create_selection ( ) : operation = Forward ( ) nested = Group ( Suppress ( "(" ) + operation + Suppress ( ")" ) ) . setResultsName ( "nested" ) select_expr = Forward ( ) functions = select_functions ( select_expr ) maybe_nested = functions | nested | Group ( var_val ) operation <<= maybe_nested + OneOrMore ( oneOf ...
Create a selection expression
29,927
def create_query_constraint ( ) : op = oneOf ( "= < > >= <= != <>" , caseless = True ) . setName ( "operator" ) basic_constraint = ( var + op + var_val ) . setResultsName ( "operator" ) between = ( var + Suppress ( upkey ( "between" ) ) + value + Suppress ( and_ ) + value ) . setResultsName ( "between" ) is_in = ( var ...
Create a constraint for a query WHERE clause
29,928
def create_where ( ) : conjunction = Forward ( ) . setResultsName ( "conjunction" ) nested = Group ( Suppress ( "(" ) + conjunction + Suppress ( ")" ) ) . setResultsName ( "conjunction" ) maybe_nested = nested | constraint inverted = Group ( not_ + maybe_nested ) . setResultsName ( "not" ) full_constraint = maybe_neste...
Create a grammar for the where clause used by select
29,929
def create_keys_in ( ) : keys = Group ( Optional ( Suppress ( "(" ) ) + value + Optional ( Suppress ( "," ) + value ) + Optional ( Suppress ( ")" ) ) ) return ( Suppress ( upkey ( "keys" ) + upkey ( "in" ) ) + delimitedList ( keys ) ) . setResultsName ( "keys_in" )
Create a grammer for the KEYS IN clause used for queries
29,930
def evaluate ( self , item ) : try : for match in PATH_PATTERN . finditer ( self . field ) : path = match . group ( 0 ) if path [ 0 ] == "[" : try : item = item [ int ( match . group ( 1 ) ) ] except IndexError : item = item [ 0 ] else : item = item . get ( path ) except ( IndexError , TypeError , AttributeError ) : re...
Pull the field off the item
29,931
def main ( ) : venv_dir = tempfile . mkdtemp ( ) try : make_virtualenv ( venv_dir ) print ( "Downloading dependencies" ) pip = os . path . join ( venv_dir , "bin" , "pip" ) subprocess . check_call ( [ pip , "install" , "pex" ] ) print ( "Building executable" ) pex = os . path . join ( venv_dir , "bin" , "pex" ) subproc...
Build a standalone dql executable
29,932
def _maybe_replace_path ( self , match ) : path = match . group ( 0 ) if self . _should_replace ( path ) : return self . _replace_path ( path ) else : return path
Regex replacement method that will sub paths when needed
29,933
def _should_replace ( self , path ) : return ( self . _reserved_words is None or path . upper ( ) in self . _reserved_words or "-" in path )
True if should replace the path
29,934
def _replace_path ( self , path ) : if path in self . _field_to_key : return self . _field_to_key [ path ] next_key = "#f%d" % self . _next_field self . _next_field += 1 self . _field_to_key [ path ] = next_key self . _fields [ next_key ] = path return next_key
Get the replacement value for a path
29,935
def wrap ( string , length , indent ) : newline = "\n" + " " * indent return newline . join ( ( string [ i : i + length ] for i in range ( 0 , len ( string ) , length ) ) )
Wrap a string at a line length
29,936
def format_json ( json_object , indent ) : indent_str = "\n" + " " * indent json_str = json . dumps ( json_object , indent = 2 , default = serialize_json_var ) return indent_str . join ( json_str . split ( "\n" ) )
Pretty - format json data
29,937
def delta_to_str ( rd ) : parts = [ ] if rd . days > 0 : parts . append ( "%d day%s" % ( rd . days , plural ( rd . days ) ) ) clock_parts = [ ] if rd . hours > 0 : clock_parts . append ( "%02d" % rd . hours ) if rd . minutes > 0 or rd . hours > 0 : clock_parts . append ( "%02d" % rd . minutes ) if rd . seconds > 0 or r...
Convert a relativedelta to a human - readable string
29,938
def less_display ( ) : _ , filename = tempfile . mkstemp ( ) mode = stat . S_IRUSR | stat . S_IWUSR outfile = None outfile = os . fdopen ( os . open ( filename , os . O_WRONLY | os . O_CREAT , mode ) , "wb" ) try : yield SmartBuffer ( outfile ) outfile . flush ( ) subprocess . call ( [ "less" , "-FXR" , filename ] ) fi...
Use smoke and mirrors to acquire less for pretty paging
29,939
def stdout_display ( ) : if sys . version_info [ 0 ] == 2 : yield SmartBuffer ( sys . stdout ) else : yield SmartBuffer ( sys . stdout . buffer )
Print results straight to stdout
29,940
def display ( self ) : total = 0 count = 0 for i , result in enumerate ( self . _results ) : if total == 0 : self . pre_write ( ) self . write ( result ) count += 1 total += 1 if ( count >= self . pagesize and self . pagesize > 0 and i < len ( self . _results ) - 1 ) : self . wait ( ) count = 0 if total == 0 : self . _...
Write results to an output stream
29,941
def format_field ( self , field ) : if field is None : return "NULL" elif isinstance ( field , TypeError ) : return "TypeError" elif isinstance ( field , Decimal ) : if field % 1 == 0 : return str ( int ( field ) ) return str ( float ( field ) ) elif isinstance ( field , set ) : return "(" + ", " . join ( [ self . form...
Format a single Dynamo value
29,942
def _write_header ( self ) : self . _ostream . write ( len ( self . _header ) * "-" + "\n" ) self . _ostream . write ( self . _header ) self . _ostream . write ( "\n" ) self . _ostream . write ( len ( self . _header ) * "-" + "\n" )
Write out the table header
29,943
def write ( self , arg ) : if isinstance ( arg , str ) : arg = arg . encode ( self . encoding ) return self . _buffer . write ( arg )
Write a string or bytes object to the buffer
29,944
def prompt ( msg , default = NO_DEFAULT , validate = None ) : while True : response = input ( msg + " " ) . strip ( ) if not response : if default is NO_DEFAULT : continue return default if validate is None or validate ( response ) : return response
Prompt user for input
29,945
def promptyn ( msg , default = None ) : while True : yes = "Y" if default else "y" if default or default is None : no = "n" else : no = "N" confirm = prompt ( "%s [%s/%s]" % ( msg , yes , no ) , "" ) . lower ( ) if confirm in ( "y" , "yes" ) : return True elif confirm in ( "n" , "no" ) : return False elif not confirm a...
Display a blocking prompt until the user confirms
29,946
def repl_command ( fxn ) : @ functools . wraps ( fxn ) def wrapper ( self , arglist ) : args = [ ] kwargs = { } if arglist : for arg in shlex . split ( arglist ) : if "=" in arg : split = arg . split ( "=" , 1 ) kwargs [ split [ 0 ] ] = split [ 1 ] else : args . append ( arg ) return fxn ( self , * args , ** kwargs ) r...
Decorator for cmd methods
29,947
def get_enum_key ( key , choices ) : if key in choices : return key keys = [ k for k in choices if k . startswith ( key ) ] if len ( keys ) == 1 : return keys [ 0 ]
Get an enum by prefix or equality
29,948
def initialize ( self , region = "us-west-1" , host = None , port = 8000 , config_dir = None , session = None ) : try : import readline import rlcompleter except ImportError : pass else : if "libedit" in readline . __doc__ : readline . parse_and_bind ( "bind ^I rl_complete" ) else : readline . parse_and_bind ( "tab: co...
Set up the repl for execution .
29,949
def update_prompt ( self ) : prefix = "" if self . _local_endpoint is not None : prefix += "(%s:%d) " % self . _local_endpoint prefix += self . engine . region if self . engine . partial : self . prompt = len ( prefix ) * " " + "> " else : self . prompt = prefix + "> "
Update the prompt
29,950
def save_config ( self ) : if not os . path . exists ( self . _conf_dir ) : os . makedirs ( self . _conf_dir ) conf_file = os . path . join ( self . _conf_dir , "dql.json" ) with open ( conf_file , "w" ) as ofile : json . dump ( self . conf , ofile , indent = 2 )
Save the conf file
29,951
def load_config ( self ) : conf_file = os . path . join ( self . _conf_dir , "dql.json" ) if not os . path . exists ( conf_file ) : return { } with open ( conf_file , "r" ) as ifile : return json . load ( ifile )
Load your configuration settings from a file
29,952
def do_opt ( self , * args , ** kwargs ) : args = list ( args ) if not args : largest = 0 keys = [ key for key in self . conf if not key . startswith ( "_" ) ] for key in keys : largest = max ( largest , len ( key ) ) for key in keys : print ( "%s : %s" % ( key . rjust ( largest ) , self . conf [ key ] ) ) return optio...
Get and set options
29,953
def getopt_default ( self , option ) : if option not in self . conf : print ( "Unrecognized option %r" % option ) return print ( "%s: %s" % ( option , self . conf [ option ] ) )
Default method to get an option
29,954
def complete_opt ( self , text , line , begidx , endidx ) : tokens = line . split ( ) if len ( tokens ) == 1 : if text : return else : option = "" else : option = tokens [ 1 ] if len ( tokens ) == 1 or ( len ( tokens ) == 2 and text ) : return [ name [ 4 : ] + " " for name in dir ( self ) if name . startswith ( "opt_" ...
Autocomplete for options
29,955
def opt_pagesize ( self , pagesize ) : if pagesize != "auto" : pagesize = int ( pagesize ) self . conf [ "pagesize" ] = pagesize
Get or set the page size of the query output
29,956
def _print_enum_opt ( self , option , choices ) : for key in choices : if key == self . conf [ option ] : print ( "* %s" % key ) else : print ( " %s" % key )
Helper for enum options
29,957
def opt_display ( self , display ) : key = get_enum_key ( display , DISPLAYS ) if key is not None : self . conf [ "display" ] = key self . display = DISPLAYS [ key ] print ( "Set display %r" % key ) else : print ( "Unknown display %r" % display )
Set value for display option
29,958
def complete_opt_display ( self , text , * _ ) : return [ t + " " for t in DISPLAYS if t . startswith ( text ) ]
Autocomplete for display option
29,959
def opt_format ( self , fmt ) : key = get_enum_key ( fmt , FORMATTERS ) if key is not None : self . conf [ "format" ] = key print ( "Set format %r" % key ) else : print ( "Unknown format %r" % fmt )
Set value for format option
29,960
def complete_opt_format ( self , text , * _ ) : return [ t + " " for t in FORMATTERS if t . startswith ( text ) ]
Autocomplete for format option
29,961
def opt_allow_select_scan ( self , allow ) : allow = allow . lower ( ) in ( "true" , "t" , "yes" , "y" ) self . conf [ "allow_select_scan" ] = allow self . engine . allow_select_scan = allow
Set option allow_select_scan
29,962
def complete_opt_allow_select_scan ( self , text , * _ ) : return [ t for t in ( "true" , "false" , "yes" , "no" ) if t . startswith ( text . lower ( ) ) ]
Autocomplete for allow_select_scan option
29,963
def do_watch ( self , * args ) : tables = [ ] if not self . engine . cached_descriptions : self . engine . describe_all ( ) all_tables = list ( self . engine . cached_descriptions ) for arg in args : candidates = set ( ( t for t in all_tables if fnmatch ( t , arg ) ) ) for t in sorted ( candidates ) : if t not in table...
Watch Dynamo tables consumed capacity
29,964
def complete_watch ( self , text , * _ ) : return [ t + " " for t in self . engine . cached_descriptions if t . startswith ( text ) ]
Autocomplete for watch
29,965
def do_file ( self , filename ) : with open ( filename , "r" ) as infile : self . _run_cmd ( infile . read ( ) )
Read and execute a . dql file
29,966
def complete_file ( self , text , line , * _ ) : leading = line [ len ( "file " ) : ] curpath = os . path . join ( os . path . curdir , leading ) def isdql ( parent , filename ) : return not filename . startswith ( "." ) and ( os . path . isdir ( os . path . join ( parent , filename ) ) or filename . lower ( ) . endswi...
Autocomplete DQL file lookup
29,967
def do_ls ( self , table = None ) : if table is None : fields = OrderedDict ( [ ( "Name" , "name" ) , ( "Status" , "status" ) , ( "Read" , "total_read_throughput" ) , ( "Write" , "total_write_throughput" ) , ] ) tables = self . engine . describe_all ( ) sizes = [ 1 + max ( [ len ( str ( getattr ( t , f ) ) ) for t in t...
List all tables or print details of one table
29,968
def complete_ls ( self , text , * _ ) : return [ t + " " for t in self . engine . cached_descriptions if t . startswith ( text ) ]
Autocomplete for ls
29,969
def do_local ( self , host = "localhost" , port = 8000 ) : port = int ( port ) if host == "off" : self . _local_endpoint = None else : self . _local_endpoint = ( host , port ) self . onecmd ( "use %s" % self . engine . region )
Connect to a local DynamoDB instance . Use local off to disable .
29,970
def do_use ( self , region ) : if self . _local_endpoint is not None : host , port = self . _local_endpoint self . engine . connect ( region , session = self . session , host = host , port = port , is_secure = False ) else : self . engine . connect ( region , session = self . session )
Switch the AWS region
29,971
def complete_use ( self , text , * _ ) : return [ t + " " for t in REGIONS if t . startswith ( text ) ]
Autocomplete for use
29,972
def do_throttle ( self , * args ) : args = list ( args ) if not args : print ( self . throttle ) return if len ( args ) < 2 : return self . onecmd ( "help throttle" ) args , read , write = args [ : - 2 ] , args [ - 2 ] , args [ - 1 ] if len ( args ) == 2 : tablename , indexname = args self . throttle . set_index_limit ...
Set the allowed consumed throughput for DQL .
29,973
def do_unthrottle ( self , * args ) : if not args : if promptyn ( "Are you sure you want to clear all throttles?" ) : self . throttle . load ( { } ) elif len ( args ) == 1 : tablename = args [ 0 ] if tablename == "total" : self . throttle . set_total_limit ( ) elif tablename == "default" : self . throttle . set_default...
Remove the throughput limits for DQL that were set with throttle
29,974
def completedefault ( self , text , line , * _ ) : tokens = line . split ( ) try : before = tokens [ - 2 ] complete = before . lower ( ) in ( "from" , "update" , "table" , "into" ) if tokens [ 0 ] . lower ( ) == "dump" : complete = True if complete : return [ t + " " for t in self . engine . cached_descriptions if t . ...
Autocomplete table names in queries
29,975
def _run_cmd ( self , command ) : if self . throttle : tables = self . engine . describe_all ( False ) limiter = self . throttle . get_limiter ( tables ) else : limiter = None self . engine . rate_limit = limiter results = self . engine . execute ( command ) if results is None : pass elif isinstance ( results , basestr...
Run a DQL command
29,976
def run_command ( self , command ) : self . display = DISPLAYS [ "stdout" ] self . conf [ "pagesize" ] = 0 self . onecmd ( command )
Run a command passed in from the command line with - c
29,977
def function ( name , * args , ** kwargs ) : if kwargs . get ( "caseless" ) : name = upkey ( name ) else : name = Word ( name ) fxn_args = None for i , arg in enumerate ( args ) : if i == 0 : fxn_args = arg else : fxn_args += Suppress ( "," ) + arg if fxn_args is None : return name + Suppress ( "(" ) + Suppress ( ")" )...
Construct a parser for a standard function format
29,978
def make_interval ( long_name , short_name ) : return Group ( Regex ( "(-+)?[0-9]+" ) + ( upkey ( long_name + "s" ) | Regex ( long_name + "s" ) . setParseAction ( upcaseTokens ) | upkey ( long_name ) | Regex ( long_name ) . setParseAction ( upcaseTokens ) | upkey ( short_name ) | Regex ( short_name ) . setParseAction (...
Create an interval segment
29,979
def create_throughput ( variable = primitive ) : return ( Suppress ( upkey ( "throughput" ) | upkey ( "tp" ) ) + Suppress ( "(" ) + variable + Suppress ( "," ) + variable + Suppress ( ")" ) ) . setResultsName ( "throughput" )
Create a throughput specification
29,980
def create_throttle ( ) : throttle_amount = "*" | Combine ( number + "%" ) | number return Group ( function ( "throttle" , throttle_amount , throttle_amount , caseless = True ) ) . setResultsName ( "throttle" )
Create a THROTTLE statement
29,981
def _global_index ( ) : var_and_type = var + Optional ( type_ ) global_dec = Suppress ( upkey ( "global" ) ) + index range_key_etc = Suppress ( "," ) + Group ( throughput ) | Optional ( Group ( Suppress ( "," ) + var_and_type ) . setResultsName ( "range_key" ) ) + Optional ( Suppress ( "," ) + include_vars ) + Optional...
Create grammar for a global index declaration
29,982
def create_create ( ) : create = upkey ( "create" ) . setResultsName ( "action" ) hash_key = Group ( upkey ( "hash" ) + upkey ( "key" ) ) range_key = Group ( upkey ( "range" ) + upkey ( "key" ) ) local_index = Group ( index + Suppress ( "(" ) + primitive + Optional ( Suppress ( "," ) + include_vars ) + Suppress ( ")" )...
Create the grammar for the create statement
29,983
def create_delete ( ) : delete = upkey ( "delete" ) . setResultsName ( "action" ) return ( delete + from_ + table + Optional ( keys_in ) + Optional ( where ) + Optional ( using ) + Optional ( throttle ) )
Create the grammar for the delete statement
29,984
def create_insert ( ) : insert = upkey ( "insert" ) . setResultsName ( "action" ) attrs = Group ( delimitedList ( var ) ) . setResultsName ( "attrs" ) value_group = Group ( Suppress ( "(" ) + delimitedList ( value ) + Suppress ( ")" ) ) values = Group ( delimitedList ( value_group ) ) . setResultsName ( "list_values" )...
Create the grammar for the insert statement
29,985
def _create_update_expression ( ) : ine = ( Word ( "if_not_exists" ) + Suppress ( "(" ) + var + Suppress ( "," ) + var_val + Suppress ( ")" ) ) list_append = ( Word ( "list_append" ) + Suppress ( "(" ) + var_val + Suppress ( "," ) + var_val + Suppress ( ")" ) ) fxn = Group ( ine | list_append ) . setResultsName ( "set_...
Create the grammar for an update expression
29,986
def create_update ( ) : update = upkey ( "update" ) . setResultsName ( "action" ) returns , none , all_ , updated , old , new = map ( upkey , [ "returns" , "none" , "all" , "updated" , "old" , "new" ] ) return_ = returns + Group ( none | ( all_ + old ) | ( all_ + new ) | ( updated + old ) | ( updated + new ) ) . setRes...
Create the grammar for the update statement
29,987
def create_alter ( ) : alter = upkey ( "alter" ) . setResultsName ( "action" ) prim_or_star = primitive | "*" set_throughput = ( Suppress ( upkey ( "set" ) ) + Optional ( Suppress ( upkey ( "index" ) ) + var . setResultsName ( "index" ) ) + create_throughput ( prim_or_star ) ) drop_index = ( Suppress ( upkey ( "drop" )...
Create the grammar for the alter statement
29,988
def create_dump ( ) : dump = upkey ( "dump" ) . setResultsName ( "action" ) return ( dump + upkey ( "schema" ) + Optional ( Group ( delimitedList ( table ) ) . setResultsName ( "tables" ) ) )
Create the grammar for the dump statement
29,989
def create_load ( ) : load = upkey ( "load" ) . setResultsName ( "action" ) return ( load + Group ( filename ) . setResultsName ( "load_file" ) + upkey ( "into" ) + table + Optional ( throttle ) )
Create the grammar for the load statement
29,990
def create_parser ( ) : select = create_select ( ) scan = create_scan ( ) delete = create_delete ( ) update = create_update ( ) insert = create_insert ( ) create = create_create ( ) drop = create_drop ( ) alter = create_alter ( ) dump = create_dump ( ) load = create_load ( ) base = ( select | scan | delete | update | i...
Create the language parser
29,991
def main ( ) : parse = argparse . ArgumentParser ( description = main . __doc__ ) parse . add_argument ( "-c" , "--command" , help = "Run this command and exit" ) region = os . environ . get ( "AWS_REGION" , "us-west-1" ) parse . add_argument ( "-r" , "--region" , default = region , help = "AWS region to connect to (de...
Start the DQL client .
29,992
def build_definitions_example ( self ) : for def_name , def_spec in self . specification . get ( 'definitions' , { } ) . items ( ) : self . build_one_definition_example ( def_name )
Parse all definitions in the swagger specification .
29,993
def build_one_definition_example ( self , def_name ) : if def_name in self . definitions_example . keys ( ) : return True elif def_name not in self . specification [ 'definitions' ] . keys ( ) : return False self . definitions_example [ def_name ] = { } def_spec = self . specification [ 'definitions' ] [ def_name ] if ...
Build the example for the given definition .
29,994
def check_type ( value , type_def ) : if type_def == 'integer' : try : int ( value ) return True except ValueError : return isinstance ( value , six . integer_types ) and not isinstance ( value , bool ) elif type_def == 'number' : return isinstance ( value , ( six . integer_types , float ) ) and not isinstance ( value ...
Check if the value is in the type given in type_def .
29,995
def get_example_from_prop_spec ( self , prop_spec , from_allof = False ) : easy_keys = [ 'example' , 'x-example' , 'default' ] for key in easy_keys : if key in prop_spec . keys ( ) and self . use_example : return prop_spec [ key ] if 'enum' in prop_spec . keys ( ) : return prop_spec [ 'enum' ] [ 0 ] if '$ref' in prop_s...
Return an example value from a property specification .
29,996
def _get_example_from_properties ( self , spec ) : local_spec = deepcopy ( spec ) additional_property = False if 'additionalProperties' in local_spec : additional_property = True if 'properties' not in local_spec : local_spec [ 'properties' ] = { } local_spec [ 'properties' ] . update ( { 'any_prop1' : local_spec [ 'ad...
Get example from the properties of an object defined inline .
29,997
def _get_example_from_basic_type ( type ) : if type == 'integer' : return [ 42 , 24 ] elif type == 'number' : return [ 5.5 , 5.5 ] elif type == 'string' : return [ 'string' , 'string2' ] elif type == 'datetime' : return [ '2015-08-28T09:02:57.481Z' , '2015-08-28T09:02:57.481Z' ] elif type == 'boolean' : return [ False ...
Get example from the given type .
29,998
def _definition_from_example ( example ) : assert isinstance ( example , dict ) def _has_simple_type ( value ) : accepted = ( str , int , float , bool ) return isinstance ( value , accepted ) definition = { 'type' : 'object' , 'properties' : { } , } for key , value in example . items ( ) : if not _has_simple_type ( val...
Generates a swagger definition json from a given example Works only for simple types in the dict
29,999
def _example_from_allof ( self , prop_spec ) : example_dict = { } for definition in prop_spec [ 'allOf' ] : update = self . get_example_from_prop_spec ( definition , True ) example_dict . update ( update ) return example_dict
Get the examples from an allOf section .