idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
26,100
def run ( self , * args ) : if self . volumes : volumes = " --bind " + " --bind " . join ( self . volumes ) else : volumes = "" self . _print ( "Starting container [{0:s}]. Timeout set to {1:d}. The container ID is printed below." . format ( self . name , self . time_out ) ) utils . xrun ( "singularity run" , [ "instance://{0:s} {1:s}" . format ( self . name , self . RUNSCRIPT ) ] , timeout = self . time_out , kill_callback = self . stop ) self . status = "running" return 0
Run a singularity container instance
148
6
26,101
def stop ( self , * args ) : if self . volumes : volumes = " --bind " + " --bind " . join ( self . volumes ) else : volumes = "" self . _print ( "Stopping container [{}]. The container ID is printed below." . format ( self . name ) ) utils . xrun ( "singularity" , [ "instance.stop {0:s}" . format ( self . name ) ] ) self . status = "exited" return 0
Stop a singularity container instance
105
6
26,102
def build ( image , build_path , tag = None , build_args = None , fromline = None , args = [ ] ) : if tag : image = ":" . join ( [ image , tag ] ) bdir = tempfile . mkdtemp ( ) os . system ( 'cp -r {0:s}/* {1:s}' . format ( build_path , bdir ) ) if build_args : stdw = tempfile . NamedTemporaryFile ( dir = bdir , mode = 'w' ) with open ( "{}/Dockerfile" . format ( bdir ) ) as std : dfile = std . readlines ( ) for line in dfile : if fromline and line . lower ( ) . startswith ( 'from' ) : stdw . write ( 'FROM {:s}\n' . format ( fromline ) ) elif line . lower ( ) . startswith ( "cmd" ) : for arg in build_args : stdw . write ( arg + "\n" ) stdw . write ( line ) else : stdw . write ( line ) stdw . flush ( ) utils . xrun ( "docker build" , args + [ "--force-rm" , "-f" , stdw . name , "-t" , image , bdir ] ) stdw . close ( ) else : utils . xrun ( "docker build" , args + [ "--force-rm" , "-t" , image , bdir ] ) os . system ( 'rm -rf {:s}' . format ( bdir ) )
build a docker image
344
4
26,103
def pull ( image , tag = None ) : if tag : image = ":" . join ( [ image , tag ] ) utils . xrun ( "docker pull" , [ image ] )
pull a docker image
41
4
26,104
def info ( cabdir , header = False ) : # First check if cab exists pfile = "{}/parameters.json" . format ( cabdir ) if not os . path . exists ( pfile ) : raise RuntimeError ( "Cab could not be found at : {}" . format ( cabdir ) ) # Get cab info cab_definition = cab . CabDefinition ( parameter_file = pfile ) cab_definition . display ( header )
prints out help information about a cab
96
7
26,105
def xrun ( command , options , log = None , _log_container_as_started = False , logfile = None , timeout = - 1 , kill_callback = None ) : cmd = " " . join ( [ command ] + list ( map ( str , options ) ) ) def _print_info ( msg ) : if msg is None : return if log : log . info ( msg ) else : print ( msg ) def _print_warn ( msg ) : if msg is None : return if log : log . warn ( msg ) else : print ( msg ) _print_info ( u"Running: {0:s}" . format ( cmd ) ) sys . stdout . flush ( ) starttime = time . time ( ) process = p = None try : foutname = os . path . join ( "/tmp" , "stimela_output_{0:s}_{1:f}" . format ( hashlib . md5 ( cmd . encode ( 'utf-8' ) ) . hexdigest ( ) , starttime ) ) with open ( foutname , "w+" ) as fout : p = process = subprocess . Popen ( cmd , stderr = fout , stdout = fout , shell = True ) def clock_killer ( p ) : while process . poll ( ) is None and ( timeout >= 0 ) : currenttime = time . time ( ) if ( currenttime - starttime < timeout ) : DEBUG and _print_warn ( u"Clock Reaper: has been running for {0:f}, must finish in {1:f}" . format ( currenttime - starttime , timeout ) ) else : _print_warn ( u"Clock Reaper: Timeout reached for '{0:s}'... sending the KILL signal" . format ( cmd ) ) ( kill_callback is not None ) and kill_callback ( ) time . sleep ( INTERRUPT_TIME ) Thread ( target = clock_killer , args = tuple ( [ p ] ) ) . start ( ) while ( process . poll ( ) is None ) : currenttime = time . time ( ) DEBUG and _print_info ( u"God mode on: has been running for {0:f}" . format ( currenttime - starttime ) ) time . sleep ( INTERRUPT_TIME ) # this is probably not ideal as it interrupts the process every few seconds, #check whether there is an alternative with a callback assert hasattr ( process , "returncode" ) , "No returncode after termination!" with open ( foutname , "r" ) as fout : _print_info ( fout . read ( ) ) finally : if ( process is not None ) and process . returncode : raise StimelaCabRuntimeError ( '%s: returns errr code %d' % ( command , process . returncode ) )
Run something on command line .
610
6
26,106
def sumcols ( msname , col1 = None , col2 = None , outcol = None , cols = None , suntract = False ) : from pyrap . tables import table tab = table ( msname , readonly = False ) if cols : data = 0 for col in cols : data += tab . getcol ( col ) else : if subtract : data = tab . getcol ( col1 ) - tab . getcol ( col2 ) else : data = tab . getcol ( col1 ) + tab . getcol ( col2 ) rowchunk = nrows // 10 if nrows > 1000 else nrows for row0 in range ( 0 , nrows , rowchunk ) : nr = min ( rowchunk , nrows - row0 ) tab . putcol ( outcol , data [ row0 : row0 + nr ] , row0 , nr ) tab . close ( )
add col1 to col2 or sum columns in cols list . If subtract subtract col2 from col1
199
22
26,107
def compute_vis_noise ( msname , sefd , spw_id = 0 ) : from pyrap . tables import table tab = table ( msname ) spwtab = table ( msname + "/SPECTRAL_WINDOW" ) freq0 = spwtab . getcol ( "CHAN_FREQ" ) [ spw_id , 0 ] wavelength = 300e+6 / freq0 bw = spwtab . getcol ( "CHAN_WIDTH" ) [ spw_id , 0 ] dt = tab . getcol ( "EXPOSURE" , 0 , 1 ) [ 0 ] dtf = ( tab . getcol ( "TIME" , tab . nrows ( ) - 1 , 1 ) - tab . getcol ( "TIME" , 0 , 1 ) ) [ 0 ] # close tables properly, else the calls below will hang waiting for a lock... tab . close ( ) spwtab . close ( ) print ( ">>> %s freq %.2f MHz (lambda=%.2fm), bandwidth %.2g kHz, %.2fs integrations, %.2fh synthesis" % ( msname , freq0 * 1e-6 , wavelength , bw * 1e-3 , dt , dtf / 3600 ) ) noise = sefd / math . sqrt ( abs ( 2 * bw * dt ) ) print ( ">>> SEFD of %.2f Jy gives per-visibility noise of %.2f mJy" % ( sefd , noise * 1000 ) ) return noise
Computes nominal per - visibility noise
346
7
26,108
def fitsInfo ( fitsname = None ) : hdu = pyfits . open ( fitsname ) hdr = hdu [ 0 ] . header ra = hdr [ 'CRVAL1' ] dra = abs ( hdr [ 'CDELT1' ] ) raPix = hdr [ 'CRPIX1' ] dec = hdr [ 'CRVAL2' ] ddec = abs ( hdr [ 'CDELT2' ] ) decPix = hdr [ 'CRPIX2' ] freq0 = 0 for i in range ( 1 , hdr [ 'NAXIS' ] + 1 ) : if hdr [ 'CTYPE%d' % i ] . strip ( ) == 'FREQ' : freq0 = hdr [ 'CRVAL%d' % i ] break ndim = hdr [ "NAXIS" ] imslice = np . zeros ( ndim , dtype = int ) . tolist ( ) imslice [ - 2 : ] = slice ( None ) , slice ( None ) image = hdu [ 0 ] . data [ imslice ] wcs = WCS ( hdr , mode = 'pyfits' ) return { 'image' : image , 'wcs' : wcs , 'ra' : ra , 'dec' : dec , 'dra' : dra , 'ddec' : ddec , 'raPix' : raPix , 'decPix' : decPix , 'freq0' : freq0 }
Get fits info
328
3
26,109
def sky2px ( wcs , ra , dec , dra , ddec , cell , beam ) : dra = beam if dra < beam else dra # assume every source is at least as large as the psf ddec = beam if ddec < beam else ddec offsetDec = int ( ( ddec / 2. ) / cell ) offsetRA = int ( ( dra / 2. ) / cell ) if offsetDec % 2 == 1 : offsetDec += 1 if offsetRA % 2 == 1 : offsetRA += 1 raPix , decPix = map ( int , wcs . wcs2pix ( ra , dec ) ) return np . array ( [ raPix - offsetRA , raPix + offsetRA , decPix - offsetDec , decPix + offsetDec ] )
convert a sky region to pixel positions
170
8
26,110
def get_components ( self , root = 'C' , visible = False ) : root_val = note_to_val ( root ) components = [ v + root_val for v in self . components ] if visible : components = [ val_to_note ( c , scale = root ) for c in components ] return components
Get components of chord quality
71
5
26,111
def append_on_chord ( self , on_chord , root ) : root_val = note_to_val ( root ) on_chord_val = note_to_val ( on_chord ) - root_val list_ = list ( self . components ) for idx , val in enumerate ( list_ ) : if val % 12 == on_chord_val : self . components . remove ( val ) break if on_chord_val > root_val : on_chord_val -= 12 if on_chord_val not in self . components : self . components . insert ( 0 , on_chord_val )
Append on chord
143
4
26,112
def append_note ( self , note , root , scale = 0 ) : root_val = note_to_val ( root ) note_val = note_to_val ( note ) - root_val + scale * 12 if note_val not in self . components : self . components . append ( note_val ) self . components . sort ( )
Append a note to quality
75
6
26,113
def append_notes ( self , notes , root , scale = 0 ) : for note in notes : self . append_note ( note , root , scale )
Append notes to quality
33
5
26,114
def insert ( self , index , chord ) : self . _chords . insert ( index , as_chord ( chord ) )
Insert a chord to chord progressions
28
7
26,115
def as_chord ( chord ) : if isinstance ( chord , Chord ) : return chord elif isinstance ( chord , str ) : return Chord ( chord ) else : raise TypeError ( "input type should be str or Chord instance." )
convert from str to Chord instance if input is str
55
12
26,116
def transpose ( self , trans , scale = "C" ) : if not isinstance ( trans , int ) : raise TypeError ( "Expected integers, not {}" . format ( type ( trans ) ) ) self . _root = transpose_note ( self . _root , trans , scale ) if self . _on : self . _on = transpose_note ( self . _on , trans , scale ) self . _reconfigure_chord ( )
Transpose the chord
101
4
26,117
def components ( self , visible = True ) : if self . _on : self . _quality . append_on_chord ( self . on , self . root ) return self . _quality . get_components ( root = self . _root , visible = visible )
Return the component notes of chord
58
6
26,118
def _parse ( self , chord ) : root , quality , appended , on = parse ( chord ) self . _root = root self . _quality = quality self . _appended = appended self . _on = on
parse a chord
48
3
26,119
def transpose_note ( note , transpose , scale = "C" ) : val = note_to_val ( note ) val += transpose return val_to_note ( val , scale )
Transpose a note
43
4
26,120
def parse ( chord ) : if len ( chord ) > 1 and chord [ 1 ] in ( "b" , "#" ) : root = chord [ : 2 ] rest = chord [ 2 : ] else : root = chord [ : 1 ] rest = chord [ 1 : ] check_note ( root , chord ) on_chord_idx = rest . find ( "/" ) if on_chord_idx >= 0 : on = rest [ on_chord_idx + 1 : ] rest = rest [ : on_chord_idx ] check_note ( on , chord ) else : on = None if rest in QUALITY_DICT : quality = Quality ( rest ) else : raise ValueError ( "Invalid chord {}: Unknown quality {}" . format ( chord , rest ) ) # TODO: Implement parser for appended notes appended = [ ] return root , quality , appended , on
Parse a string to get chord component
196
8
26,121
def check_note ( note , chord ) : if note not in NOTE_VAL_DICT : raise ValueError ( "Invalid chord {}: Unknown note {}" . format ( chord , note ) ) return True
Return True if the note is valid .
44
8
26,122
def note_to_chord ( notes ) : if not notes : raise ValueError ( "Please specify notes which consist a chord." ) root = notes [ 0 ] root_and_positions = [ ] for rotated_notes in get_all_rotated_notes ( notes ) : rotated_root = rotated_notes [ 0 ] root_and_positions . append ( [ rotated_root , notes_to_positions ( rotated_notes , rotated_notes [ 0 ] ) ] ) chords = [ ] for temp_root , positions in root_and_positions : quality = find_quality ( positions ) if quality is None : continue if temp_root == root : chord = "{}{}" . format ( root , quality ) else : chord = "{}{}/{}" . format ( temp_root , quality , root ) chords . append ( Chord ( chord ) ) return chords
Convert note list to chord list
189
7
26,123
def notes_to_positions ( notes , root ) : root_pos = note_to_val ( root ) current_pos = root_pos positions = [ ] for note in notes : note_pos = note_to_val ( note ) if note_pos < current_pos : note_pos += 12 * ( ( current_pos - note_pos ) // 12 + 1 ) positions . append ( note_pos - root_pos ) current_pos = note_pos return positions
Get notes positions .
104
4
26,124
def get_all_rotated_notes ( notes ) : notes_list = [ ] for x in range ( len ( notes ) ) : notes_list . append ( notes [ x : ] + notes [ : x ] ) return notes_list
Get all rotated notes
52
4
26,125
def find_quality ( positions ) : for q , p in QUALITY_DICT . items ( ) : if positions == list ( p ) : return q return None
Find a quality consists of positions
36
6
26,126
def configure ( self , ns , mappings = None , * * kwargs ) : if mappings is None : mappings = dict ( ) mappings . update ( kwargs ) for operation , definition in mappings . items ( ) : try : configure_func = self . _find_func ( operation ) except AttributeError : pass else : configure_func ( ns , self . _make_definition ( definition ) )
Apply mappings to a namespace .
91
7
26,127
def _find_func ( self , operation ) : if isinstance ( operation , Operation ) : operation_name = operation . name . lower ( ) else : operation_name = operation . lower ( ) return getattr ( self , "configure_{}" . format ( operation_name ) )
Find the function to use to configure the given operation .
61
11
26,128
def _make_definition ( self , definition ) : if not definition : return EndpointDefinition ( ) if isinstance ( definition , EndpointDefinition ) : return definition elif len ( definition ) == 1 : return EndpointDefinition ( func = definition [ 0 ] , ) elif len ( definition ) == 2 : return EndpointDefinition ( func = definition [ 0 ] , response_schema = definition [ 1 ] , ) elif len ( definition ) == 3 : return EndpointDefinition ( func = definition [ 0 ] , request_schema = definition [ 1 ] , response_schema = definition [ 2 ] , ) elif len ( definition ) == 4 : return EndpointDefinition ( func = definition [ 0 ] , request_schema = definition [ 1 ] , response_schema = definition [ 2 ] , header_func = definition [ 3 ] , )
Generate a definition .
181
5
26,129
def iter_links ( operations , page ) : for operation , ns , rule , func in operations : yield Link . for_ ( operation = operation , ns = ns , type = ns . subject_name , qs = page . to_items ( ) , )
Generate links for an iterable of operations on a starting page .
55
14
26,130
def configure_discovery ( graph ) : ns = Namespace ( subject = graph . config . discovery_convention . name , ) convention = DiscoveryConvention ( graph ) convention . configure ( ns , discover = tuple ( ) ) return ns . subject
Build a singleton endpoint that provides a link to all search endpoints .
52
15
26,131
def configure_discover ( self , ns , definition ) : page_schema = OffsetLimitPageSchema ( ) @ self . add_route ( "/" , Operation . Discover , ns ) def discover ( ) : # accept pagination limit from request page = OffsetLimitPage . from_query_string ( page_schema ) page . offset = 0 response_data = dict ( _links = Links ( { "self" : Link . for_ ( Operation . Discover , ns , qs = page . to_items ( ) ) , "search" : [ link for link in iter_links ( self . find_matching_endpoints ( ns ) , page ) ] , } ) . to_dict ( ) ) return make_response ( response_data )
Register a discovery endpoint for a set of operations .
164
10
26,132
def nested ( * contexts ) : with ExitStack ( ) as stack : results = [ stack . enter_context ( context ) for context in contexts ] yield results
Reimplementation of nested in python 3 .
33
9
26,133
def temporary_upload ( name , fileobj ) : tempdir = mkdtemp ( ) filename = secure_filename ( fileobj . filename ) filepath = join ( tempdir , filename ) fileobj . save ( filepath ) try : yield name , filepath , fileobj . filename finally : rmtree ( tempdir )
Upload a file to a temporary location .
69
8
26,134
def configure_upload ( graph , ns , mappings , exclude_func = None ) : convention = UploadConvention ( graph , exclude_func ) convention . configure ( ns , mappings )
Register Upload endpoints for a resource object .
40
9
26,135
def configure_upload ( self , ns , definition ) : upload = self . create_upload_func ( ns , definition , ns . collection_path , Operation . Upload ) upload . __doc__ = "Upload a {}" . format ( ns . subject_name )
Register an upload endpoint .
56
5
26,136
def configure_uploadfor ( self , ns , definition ) : upload_for = self . create_upload_func ( ns , definition , ns . relation_path , Operation . UploadFor ) upload_for . __doc__ = "Upload a {} for a {}" . format ( ns . subject_name , ns . object_name )
Register an upload - for relation endpoint .
71
8
26,137
def build_etag ( self , response , include_etag = True , * * kwargs ) : if not include_etag : return if not spooky : # use built-in md5 response . add_etag ( ) return # use spooky response . headers [ "ETag" ] = quote_etag ( hexlify ( spooky . hash128 ( response . get_data ( ) , ) . to_bytes ( 16 , "little" ) , ) . decode ( "utf-8" ) , )
Add an etag to the response body .
115
9
26,138
def update_and_reencrypt ( self , * * kwargs ) : encrypted_field_name = self . store . model_class . __plaintext__ id_ = kwargs [ self . identifier_key ] current_model = self . store . retrieve ( id_ ) current_value = current_model . plaintext null_update = ( # Check if the update is for the encrypted field, and if it's explicitly set to null encrypted_field_name in kwargs and kwargs . get ( encrypted_field_name ) is None ) new_value = kwargs . pop ( self . store . model_class . __plaintext__ , None ) use_new_value = new_value is not None or null_update updated_value = new_value if use_new_value else current_value model_kwargs = { self . identifier_key : id_ , encrypted_field_name : updated_value , * * kwargs , } return super ( ) . update ( * * model_kwargs , )
Support re - encryption by enforcing that every update triggers a new encryption call even if the the original call does not update the encrypted field .
225
27
26,139
def unflatten ( self , obj ) : obj . substitutions = [ dict ( from_id = key , to_id = value ) for key , value in getattr ( obj , "substitutions" , { } ) . items ( ) ]
Translate substitutions dictionary into objects .
54
8
26,140
def clone ( self , substitutions , commit = True , * * kwargs ) : return self . store . clone ( substitutions , * * kwargs )
Clone a DAG optionally skipping the commit .
35
10
26,141
def configure_createfor ( self , ns , definition ) : @ self . add_route ( ns . relation_path , Operation . CreateFor , ns ) @ request ( definition . request_schema ) @ response ( definition . response_schema ) @ wraps ( definition . func ) def create ( * * path_data ) : request_data = load_request_data ( definition . request_schema ) response_data = require_response_data ( definition . func ( * * merge_data ( path_data , request_data ) ) ) headers = encode_id_header ( response_data ) definition . header_func ( headers , response_data ) response_format = self . negotiate_response_content ( definition . response_formats ) return dump_response_data ( definition . response_schema , response_data , Operation . CreateFor . value . default_code , headers = headers , response_format = response_format , ) create . __doc__ = "Create a new {} relative to a {}" . format ( pluralize ( ns . object_name ) , ns . subject_name )
Register a create - for relation endpoint .
237
8
26,142
def configure_deletefor ( self , ns , definition ) : @ self . add_route ( ns . relation_path , Operation . DeleteFor , ns ) @ wraps ( definition . func ) def delete ( * * path_data ) : headers = dict ( ) response_data = dict ( ) require_response_data ( definition . func ( * * path_data ) ) definition . header_func ( headers , response_data ) response_format = self . negotiate_response_content ( definition . response_formats ) return dump_response_data ( "" , None , status_code = Operation . DeleteFor . value . default_code , headers = headers , response_format = response_format , ) delete . __doc__ = "Delete a {} relative to a {}" . format ( pluralize ( ns . object_name ) , ns . subject_name )
Register a delete - for relation endpoint .
183
8
26,143
def configure_replacefor ( self , ns , definition ) : @ self . add_route ( ns . relation_path , Operation . ReplaceFor , ns ) @ request ( definition . request_schema ) @ response ( definition . response_schema ) @ wraps ( definition . func ) def replace ( * * path_data ) : headers = dict ( ) request_data = load_request_data ( definition . request_schema ) response_data = require_response_data ( definition . func ( * * merge_data ( path_data , request_data ) ) ) definition . header_func ( headers , response_data ) response_format = self . negotiate_response_content ( definition . response_formats ) return dump_response_data ( definition . response_schema , response_data , status_code = Operation . ReplaceFor . value . default_code , headers = headers , response_format = response_format , ) replace . __doc__ = "Replace a {} relative to a {}" . format ( pluralize ( ns . object_name ) , ns . subject_name )
Register a replace - for relation endpoint .
234
8
26,144
def build ( self , field : Field ) -> Mapping [ str , Any ] : builder_types = self . builder_types ( ) + [ # put default last self . default_builder_type ( ) ] builders : List [ ParameterBuilder ] = [ builder_type ( build_parameter = self . build , ) for builder_type in builder_types ] builder = next ( builder for builder in builders if builder . supports_field ( field ) ) return builder . build ( field )
Build a swagger parameter from a marshmallow field .
104
11
26,145
def builder_types ( cls ) -> List [ Type [ ParameterBuilder ] ] : return [ entry_point . load ( ) for entry_point in iter_entry_points ( ENTRY_POINT ) ]
Define the available builder types .
46
7
26,146
def configure_crud ( graph , ns , mappings ) : convention = CRUDConvention ( graph ) convention . configure ( ns , mappings )
Register CRUD endpoints for a resource object .
32
10
26,147
def configure_count ( self , ns , definition ) : @ self . add_route ( ns . collection_path , Operation . Count , ns ) @ qs ( definition . request_schema ) @ wraps ( definition . func ) def count ( * * path_data ) : request_data = load_query_string_data ( definition . request_schema ) response_data = dict ( ) count = definition . func ( * * merge_data ( path_data , request_data ) ) headers = encode_count_header ( count ) definition . header_func ( headers , response_data ) response_format = self . negotiate_response_content ( definition . response_formats ) return dump_response_data ( None , None , headers = headers , response_format = response_format , ) count . __doc__ = "Count the size of the collection of all {}" . format ( pluralize ( ns . subject_name ) )
Register a count endpoint .
201
5
26,148
def configure_create ( self , ns , definition ) : @ self . add_route ( ns . collection_path , Operation . Create , ns ) @ request ( definition . request_schema ) @ response ( definition . response_schema ) @ wraps ( definition . func ) def create ( * * path_data ) : request_data = load_request_data ( definition . request_schema ) response_data = definition . func ( * * merge_data ( path_data , request_data ) ) headers = encode_id_header ( response_data ) definition . header_func ( headers , response_data ) response_format = self . negotiate_response_content ( definition . response_formats ) return dump_response_data ( definition . response_schema , response_data , status_code = Operation . Create . value . default_code , headers = headers , response_format = response_format , ) create . __doc__ = "Create a new {}" . format ( ns . subject_name )
Register a create endpoint .
217
5
26,149
def configure_updatebatch ( self , ns , definition ) : operation = Operation . UpdateBatch @ self . add_route ( ns . collection_path , operation , ns ) @ request ( definition . request_schema ) @ response ( definition . response_schema ) @ wraps ( definition . func ) def update_batch ( * * path_data ) : headers = dict ( ) request_data = load_request_data ( definition . request_schema ) response_data = definition . func ( * * merge_data ( path_data , request_data ) ) definition . header_func ( headers , response_data ) response_format = self . negotiate_response_content ( definition . response_formats ) return dump_response_data ( definition . response_schema , response_data , status_code = operation . value . default_code , headers = headers , response_format = response_format , ) update_batch . __doc__ = "Update a batch of {}" . format ( ns . subject_name )
Register an update batch endpoint .
219
6
26,150
def configure_retrieve ( self , ns , definition ) : request_schema = definition . request_schema or Schema ( ) @ self . add_route ( ns . instance_path , Operation . Retrieve , ns ) @ qs ( request_schema ) @ response ( definition . response_schema ) @ wraps ( definition . func ) def retrieve ( * * path_data ) : headers = dict ( ) request_data = load_query_string_data ( request_schema ) response_data = require_response_data ( definition . func ( * * merge_data ( path_data , request_data ) ) ) definition . header_func ( headers , response_data ) response_format = self . negotiate_response_content ( definition . response_formats ) return dump_response_data ( definition . response_schema , response_data , headers = headers , response_format = response_format , ) retrieve . __doc__ = "Retrieve a {} by id" . format ( ns . subject_name )
Register a retrieve endpoint .
222
5
26,151
def configure_delete ( self , ns , definition ) : request_schema = definition . request_schema or Schema ( ) @ self . add_route ( ns . instance_path , Operation . Delete , ns ) @ qs ( request_schema ) @ wraps ( definition . func ) def delete ( * * path_data ) : headers = dict ( ) request_data = load_query_string_data ( request_schema ) response_data = require_response_data ( definition . func ( * * merge_data ( path_data , request_data ) ) ) definition . header_func ( headers , response_data ) response_format = self . negotiate_response_content ( definition . response_formats ) return dump_response_data ( "" , None , status_code = Operation . Delete . value . default_code , headers = headers , response_format = response_format , ) delete . __doc__ = "Delete a {} by id" . format ( ns . subject_name )
Register a delete endpoint .
216
5
26,152
def configure_replace ( self , ns , definition ) : @ self . add_route ( ns . instance_path , Operation . Replace , ns ) @ request ( definition . request_schema ) @ response ( definition . response_schema ) @ wraps ( definition . func ) def replace ( * * path_data ) : headers = dict ( ) request_data = load_request_data ( definition . request_schema ) # Replace/put should create a resource if not already present, but we do not # enforce these semantics at the HTTP layer. If `func` returns falsey, we # will raise a 404. response_data = require_response_data ( definition . func ( * * merge_data ( path_data , request_data ) ) ) definition . header_func ( headers , response_data ) response_format = self . negotiate_response_content ( definition . response_formats ) return dump_response_data ( definition . response_schema , response_data , headers = headers , response_format = response_format , ) replace . __doc__ = "Create or update a {} by id" . format ( ns . subject_name )
Register a replace endpoint .
247
5
26,153
def configure_update ( self , ns , definition ) : @ self . add_route ( ns . instance_path , Operation . Update , ns ) @ request ( definition . request_schema ) @ response ( definition . response_schema ) @ wraps ( definition . func ) def update ( * * path_data ) : headers = dict ( ) # NB: using partial here means that marshmallow will not validate required fields request_data = load_request_data ( definition . request_schema , partial = True ) response_data = require_response_data ( definition . func ( * * merge_data ( path_data , request_data ) ) ) definition . header_func ( headers , response_data ) response_format = self . negotiate_response_content ( definition . response_formats ) return dump_response_data ( definition . response_schema , response_data , headers = headers , response_format = response_format , ) update . __doc__ = "Update some or all of a {} by id" . format ( ns . subject_name )
Register an update endpoint .
227
5
26,154
def configure_createcollection ( self , ns , definition ) : paginated_list_schema = self . page_cls . make_paginated_list_schema_class ( ns , definition . response_schema , ) ( ) @ self . add_route ( ns . collection_path , Operation . CreateCollection , ns ) @ request ( definition . request_schema ) @ response ( paginated_list_schema ) @ wraps ( definition . func ) def create_collection ( * * path_data ) : request_data = load_request_data ( definition . request_schema ) # NB: if we don't filter the request body through an explicit page schema, # we will leak other request arguments into the pagination query strings page = self . page_cls . from_query_string ( self . page_schema ( ) , request_data ) result = definition . func ( * * merge_data ( path_data , merge_data ( request_data , page . to_dict ( func = identity ) , ) , ) ) response_data , headers = page . to_paginated_list ( result , ns , Operation . CreateCollection ) definition . header_func ( headers , response_data ) response_format = self . negotiate_response_content ( definition . response_formats ) return dump_response_data ( paginated_list_schema , response_data , headers = headers , response_format = response_format , ) create_collection . __doc__ = "Create the collection of {}" . format ( pluralize ( ns . subject_name ) )
Register create collection endpoint .
343
5
26,155
def parse_ref ( self , field : Field ) -> str : ref_name = type_name ( name_for ( field . schema ) ) return f"#/definitions/{ref_name}"
Parse the reference type for nested fields if any .
44
11
26,156
def configure_build_info ( graph ) : ns = Namespace ( subject = BuildInfo , ) convention = BuildInfoConvention ( graph ) convention . configure ( ns , retrieve = tuple ( ) ) return convention . build_info
Configure the build info endpoint .
48
7
26,157
def build_logger_tree ( ) : cache = { } tree = make_logger_node ( "" , root ) for name , logger in sorted ( root . manager . loggerDict . items ( ) ) : if "." in name : parent_name = "." . join ( name . split ( "." ) [ : - 1 ] ) parent = cache [ parent_name ] else : parent = tree cache [ name ] = make_logger_node ( name , logger , parent ) return tree
Build a DFS tree representing the logger layout .
108
10
26,158
def build ( self , field : Field ) -> Mapping [ str , Any ] : return dict ( self . iter_parsed_values ( field ) )
Build a parameter .
34
4
26,159
def iter_parsed_values ( self , field : Field ) -> Iterable [ Tuple [ str , Any ] ] : for key , func in self . parsers . items ( ) : value = func ( field ) if not value : continue yield key , value
Walk the dictionary of parsers and emit all non - null values .
57
14
26,160
def object_ns ( self ) : return Namespace ( subject = self . object_ , object_ = None , prefix = self . prefix , qualifier = self . qualifier , version = self . version , )
Create a new namespace for the current namespace s object value .
43
12
26,161
def url_for ( self , operation , _external = True , * * kwargs ) : return url_for ( self . endpoint_for ( operation ) , _external = _external , * * kwargs )
Construct a URL for an operation against a resource .
47
10
26,162
def href_for ( self , operation , qs = None , * * kwargs ) : url = urljoin ( request . url_root , self . url_for ( operation , * * kwargs ) ) qs_character = "?" if url . find ( "?" ) == - 1 else "&" return "{}{}" . format ( url , "{}{}" . format ( qs_character , urlencode ( qs ) ) if qs else "" , )
Construct an full href for an operation against a resource .
104
11
26,163
def configure_swagger ( graph ) : ns = Namespace ( subject = graph . config . swagger_convention . name , version = graph . config . swagger_convention . version , ) convention = SwaggerConvention ( graph ) convention . configure ( ns , discover = tuple ( ) ) return ns . subject
Build a singleton endpoint that provides swagger definitions for all operations .
68
14
26,164
def configure_discover ( self , ns , definition ) : @ self . add_route ( ns . singleton_path , Operation . Discover , ns ) def discover ( ) : swagger = build_swagger ( self . graph , ns , self . find_matching_endpoints ( ns ) ) g . hide_body = True return make_response ( swagger )
Register a swagger endpoint for a set of operations .
80
11
26,165
def parse_items ( self , field : Field ) -> Mapping [ str , Any ] : return self . build_parameter ( field . container )
Parse the child item type for list fields if any .
32
12
26,166
def for_ ( cls , operation , ns , qs = None , type = None , allow_templates = False , * * kwargs ) : assert isinstance ( ns , Namespace ) try : href , templated = ns . href_for ( operation , qs = qs , * * kwargs ) , False except BuildError as error : if not allow_templates : raise uri_templates = { argument : "{{{}}}" . format ( argument ) for argument in error . suggested . arguments } kwargs . update ( uri_templates ) href , templated = ns . href_for ( operation , qs = qs , * * kwargs ) , True return cls ( href = href , type = type , templated = templated , )
Create a link to an operation on a resource object .
176
11
26,167
def build_parameter ( field : Field ) -> Mapping [ str , Any ] : builder = Parameters ( ) return builder . build ( field )
Build JSON parameter from a marshmallow field .
31
9
26,168
def configure_savedsearch ( self , ns , definition ) : paginated_list_schema = self . page_cls . make_paginated_list_schema_class ( ns , definition . response_schema , ) ( ) @ self . add_route ( ns . collection_path , Operation . SavedSearch , ns ) @ request ( definition . request_schema ) @ response ( paginated_list_schema ) @ wraps ( definition . func ) def saved_search ( * * path_data ) : request_data = load_request_data ( definition . request_schema ) page = self . page_cls . from_dict ( request_data ) request_data . update ( page . to_dict ( func = identity ) ) result = definition . func ( * * merge_data ( path_data , request_data ) ) response_data , headers = page . to_paginated_list ( result , ns , Operation . SavedSearch ) definition . header_func ( headers , response_data ) response_format = self . negotiate_response_content ( definition . response_formats ) return dump_response_data ( paginated_list_schema , response_data , headers = headers , response_format = response_format , ) saved_search . __doc__ = "Persist and return the search results of {}" . format ( pluralize ( ns . subject_name ) )
Register a saved search endpoint .
308
6
26,169
def encode_basic_auth ( username , password ) : return "Basic {}" . format ( b64encode ( "{}:{}" . format ( username , password , ) . encode ( "utf-8" ) ) . decode ( "utf-8" ) )
Encode basic auth credentials .
57
6
26,170
def configure_basic_auth_decorator ( graph ) : # use the metadata name if no realm is defined graph . config . setdefault ( "BASIC_AUTH_REALM" , graph . metadata . name ) return ConfigBasicAuth ( app = graph . flask , # wrap in dict to allow lists of items as well as dictionaries credentials = dict ( graph . config . basic_auth . credentials ) , )
Configure a basic auth decorator .
91
8
26,171
def check_credentials ( self , username , password ) : return password is not None and self . credentials . get ( username , None ) == password
Override credential checking to use configured credentials .
32
8
26,172
def challenge ( self ) : response = super ( ConfigBasicAuth , self ) . challenge ( ) raise with_headers ( Unauthorized ( ) , response . headers )
Override challenge to raise an exception that will trigger regular error handling .
34
13
26,173
def iter_fields ( self , schema : Schema ) -> Iterable [ Tuple [ str , Field ] ] : for name in sorted ( schema . fields . keys ( ) ) : field = schema . fields [ name ] yield field . dump_to or name , field
Iterate through marshmallow schema fields .
57
8
26,174
def links ( self ) : links = Links ( ) links [ "self" ] = Link . for_ ( self . _operation , self . _ns , qs = self . _page . to_items ( ) , * * self . _context ) return links
Include a self link .
56
6
26,175
def links ( self ) : links = super ( OffsetLimitPaginatedList , self ) . links if self . _page . offset + self . _page . limit < self . count : links [ "next" ] = Link . for_ ( self . _operation , self . _ns , qs = self . _page . next_page . to_items ( ) , * * self . _context ) if self . offset > 0 : links [ "prev" ] = Link . for_ ( self . _operation , self . _ns , qs = self . _page . prev_page . to_items ( ) , * * self . _context ) return links
Include previous and next links .
144
7
26,176
def to_items ( self , func = str ) : return [ ( key , func ( self . kwargs [ key ] ) ) for key in sorted ( self . kwargs . keys ( ) ) ]
Contruct a list of dictionary items .
45
8
26,177
def to_paginated_list ( self , result , _ns , _operation , * * kwargs ) : items , context = self . parse_result ( result ) headers = dict ( ) paginated_list = PaginatedList ( items = items , _page = self , _ns = _ns , _operation = _operation , _context = context , ) return paginated_list , headers
Convert a controller result to a paginated list .
86
11
26,178
def parse_result ( cls , result ) : if isinstance ( result , tuple ) == 2 : items , context = result else : context = { } items = result return items , context
Parse a simple items result .
40
7
26,179
def from_query_string ( cls , schema , qs = None ) : dct = load_query_string_data ( schema , qs ) return cls . from_dict ( dct )
Extract a page from the current query string .
45
10
26,180
def make_paginated_list_schema_class ( cls , ns , item_schema ) : class PaginatedListSchema ( Schema ) : __alias__ = "{}_list" . format ( ns . subject_name ) items = fields . List ( fields . Nested ( item_schema ) , required = True ) _links = fields . Raw ( ) return PaginatedListSchema
Generate a schema class that represents a paginted list of items .
89
15
26,181
def parse_result ( cls , result ) : if len ( result ) == 3 : items , count , context = result else : context = { } items , count = result return items , count , context
Parse an items + count tuple result .
43
9
26,182
def name_for ( obj ) : if isinstance ( obj , str ) : return obj cls = obj if isclass ( obj ) else obj . __class__ if hasattr ( cls , "__alias__" ) : return underscore ( cls . __alias__ ) else : return underscore ( cls . __name__ )
Get a name for something .
71
6
26,183
def instance_path_for ( name , identifier_type , identifier_key = None ) : return "/{}/<{}:{}>" . format ( name_for ( name ) , identifier_type , identifier_key or "{}_id" . format ( name_for ( name ) ) , )
Get a path for thing .
66
6
26,184
def relation_path_for ( from_name , to_name , identifier_type , identifier_key = None ) : return "/{}/<{}:{}>/{}" . format ( name_for ( from_name ) , identifier_type , identifier_key or "{}_id" . format ( name_for ( from_name ) ) , name_for ( to_name ) , )
Get a path relating a thing to another .
88
9
26,185
def configure_alias ( graph , ns , mappings ) : convention = AliasConvention ( graph ) convention . configure ( ns , mappings )
Register Alias endpoints for a resource object .
31
10
26,186
def configure_alias ( self , ns , definition ) : @ self . add_route ( ns . alias_path , Operation . Alias , ns ) @ qs ( definition . request_schema ) @ wraps ( definition . func ) def retrieve ( * * path_data ) : # request_schema is optional for Alias request_data = ( load_query_string_data ( definition . request_schema ) if definition . request_schema else dict ( ) ) resource = definition . func ( * * merge_data ( path_data , request_data ) ) kwargs = dict ( ) identifier = "{}_id" . format ( name_for ( ns . subject ) ) kwargs [ identifier ] = resource . id url = ns . url_for ( Operation . Retrieve , * * kwargs ) return redirect ( url ) retrieve . __doc__ = "Alias a {} by name" . format ( ns . subject_name )
Register an alias endpoint which will redirect to a resource s retrieve endpoint .
205
14
26,187
def encode_id_header ( resource ) : if not hasattr ( resource , "id" ) : return { } return { "X-{}-Id" . format ( camelize ( name_for ( resource ) ) ) : str ( resource . id ) , }
Generate a header for a newly created resource .
58
10
26,188
def load_request_data ( request_schema , partial = False ) : try : json_data = request . get_json ( force = True ) or { } except Exception : # if `simplpejson` is installed, simplejson.scanner.JSONDecodeError will be raised # on malformed JSON, where as built-in `json` returns None json_data = { } request_data = request_schema . load ( json_data , partial = partial ) if request_data . errors : # pass the validation errors back in the context raise with_context ( UnprocessableEntity ( "Validation error" ) , [ { "message" : "Could not validate field: {}" . format ( field ) , "field" : field , "reasons" : reasons } for field , reasons in request_data . errors . items ( ) ] , ) return request_data . data
Load request data as JSON using the given schema .
193
10
26,189
def load_query_string_data ( request_schema , query_string_data = None ) : if query_string_data is None : query_string_data = request . args request_data = request_schema . load ( query_string_data ) if request_data . errors : # pass the validation errors back in the context raise with_context ( UnprocessableEntity ( "Validation error" ) , dict ( errors = request_data . errors ) ) return request_data . data
Load query string data using the given schema .
108
9
26,190
def dump_response_data ( response_schema , response_data , status_code = 200 , headers = None , response_format = None ) : if response_schema : response_data = response_schema . dump ( response_data ) . data return make_response ( response_data , response_schema , response_format , status_code , headers )
Dumps response data as JSON using the given schema .
80
11
26,191
def merge_data ( path_data , request_data ) : merged = request_data . copy ( ) if request_data else { } merged . update ( path_data or { } ) return merged
Merge data from the URI path and the request .
43
11
26,192
def find_response_format ( allowed_response_formats ) : # allowed formats default to [] before this if not allowed_response_formats : allowed_response_formats = [ ResponseFormats . JSON ] content_type = request . headers . get ( "Accept" ) if content_type is None : # Nothing specified, default to endpoint definition if allowed_response_formats : return allowed_response_formats [ 0 ] # Finally, default to JSON return ResponseFormats . JSON for response_format in ResponseFormats . prioritized ( ) : if response_format not in allowed_response_formats : continue if response_format . matches ( content_type ) : return response_format # fallback for previous behavior return ResponseFormats . JSON
Basic content negotiation logic .
161
5
26,193
def build_swagger ( graph , ns , operations ) : base_path = graph . build_route_path ( ns . path , ns . prefix ) schema = swagger . Swagger ( swagger = "2.0" , info = swagger . Info ( title = graph . metadata . name , version = ns . version , ) , consumes = swagger . MediaTypeList ( [ swagger . MimeType ( "application/json" ) , ] ) , produces = swagger . MediaTypeList ( [ swagger . MimeType ( "application/json" ) , ] ) , basePath = base_path , paths = swagger . Paths ( ) , definitions = swagger . Definitions ( ) , ) add_paths ( schema . paths , base_path , operations ) add_definitions ( schema . definitions , operations ) try : schema . validate ( ) except Exception : logger . exception ( "Swagger definition did not validate against swagger schema" ) raise return schema
Build out the top - level swagger definition .
210
10
26,194
def add_paths ( paths , base_path , operations ) : for operation , ns , rule , func in operations : path = build_path ( operation , ns ) if not path . startswith ( base_path ) : continue method = operation . value . method . lower ( ) # If there is no version number or prefix, we'd expect the base path to be "" # However, OpenAPI requires the minimal base path to be "/" # This means we need branching logic for that special case suffix_start = 0 if len ( base_path ) == 1 else len ( base_path ) paths . setdefault ( path [ suffix_start : ] , swagger . PathItem ( ) , ) [ method ] = build_operation ( operation , ns , rule , func )
Add paths to swagger .
164
6
26,195
def add_definitions ( definitions , operations ) : for definition_schema in iter_definitions ( definitions , operations ) : if definition_schema is None : continue if isinstance ( definition_schema , str ) : continue for name , schema in iter_schemas ( definition_schema ) : definitions . setdefault ( name , swagger . Schema ( schema ) )
Add definitions to swagger .
82
6
26,196
def iter_definitions ( definitions , operations ) : # general error schema per errors.py for error_schema_class in [ ErrorSchema , ErrorContextSchema , SubErrorSchema ] : yield error_schema_class ( ) # add all request and response schemas for operation , obj , rule , func in operations : yield get_request_schema ( func ) yield get_response_schema ( func )
Generate definitions to be converted to swagger schema .
91
11
26,197
def build_path ( operation , ns ) : try : return ns . url_for ( operation , _external = False ) except BuildError as error : # we are missing some URI path parameters uri_templates = { argument : "{{{}}}" . format ( argument ) for argument in error . suggested . arguments } # flask will sometimes try to quote '{' and '}' characters return unquote ( ns . url_for ( operation , _external = False , * * uri_templates ) )
Build a path URI for an operation .
109
8
26,198
def header_param ( name , required = False , param_type = "string" ) : return swagger . HeaderParameterSubSchema ( * * { "name" : name , "in" : "header" , "required" : required , "type" : param_type , } )
Build a header parameter definition .
63
6
26,199
def query_param ( name , field , required = False ) : parameter = build_parameter ( field ) parameter [ "name" ] = name parameter [ "in" ] = "query" parameter [ "required" ] = False return swagger . QueryParameterSubSchema ( * * parameter )
Build a query parameter definition .
63
6