idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
30,000
def _example_from_definition ( self , prop_spec ) : definition_name = self . get_definition_name_from_ref ( prop_spec [ '$ref' ] ) if self . build_one_definition_example ( definition_name ) : example_dict = self . definitions_example [ definition_name ] if not isinstance ( example_dict , dict ) : return example_dict ex...
Get an example from a property specification linked to a definition .
30,001
def _example_from_complex_def ( self , prop_spec ) : if 'schema' not in prop_spec : return [ { } ] elif 'type' not in prop_spec [ 'schema' ] : definition_name = self . get_definition_name_from_ref ( prop_spec [ 'schema' ] [ '$ref' ] ) if self . build_one_definition_example ( definition_name ) : return self . definition...
Get an example from a property specification .
30,002
def _example_from_array_spec ( self , prop_spec ) : if isinstance ( prop_spec [ 'items' ] , list ) : return [ self . get_example_from_prop_spec ( item_prop_spec ) for item_prop_spec in prop_spec [ 'items' ] ] elif 'type' in prop_spec [ 'items' ] . keys ( ) : if 'format' in prop_spec [ 'items' ] . keys ( ) and prop_spec...
Get an example from a property specification of an array .
30,003
def get_dict_definition ( self , dict , get_list = False ) : list_def_candidate = [ ] for definition_name in self . specification [ 'definitions' ] . keys ( ) : if self . validate_definition ( definition_name , dict ) : if not get_list : return definition_name list_def_candidate . append ( definition_name ) if get_list...
Get the definition name of the given dict .
30,004
def validate_additional_properties ( self , valid_response , response ) : assert isinstance ( valid_response , dict ) assert isinstance ( response , dict ) first_value = valid_response [ list ( valid_response ) [ 0 ] ] if isinstance ( first_value , dict ) : definition = None definition_name = self . get_dict_definition...
Validates additional properties . In additional properties we only need to compare the values of the dict not the keys
30,005
def validate_definition ( self , definition_name , dict_to_test , definition = None ) : if ( definition_name not in self . specification [ 'definitions' ] . keys ( ) and definition is None ) : return False spec_def = definition or self . specification [ 'definitions' ] [ definition_name ] all_required_keys_present = al...
Validate the given dict according to the given definition .
30,006
def _validate_type ( self , properties_spec , value ) : if 'type' not in properties_spec . keys ( ) : def_name = self . get_definition_name_from_ref ( properties_spec [ '$ref' ] ) return self . validate_definition ( def_name , value ) elif properties_spec [ 'type' ] == 'array' : if not isinstance ( value , list ) : ret...
Validate the given value with the given property spec .
30,007
def get_paths_data ( self ) : for path , path_spec in self . specification [ 'paths' ] . items ( ) : path = u'{0}{1}' . format ( self . base_path , path ) self . paths [ path ] = { } default_parameters = { } if 'parameters' in path_spec : self . _add_parameters ( default_parameters , path_spec [ 'parameters' ] ) for ht...
Get data for each paths in the swagger specification .
30,008
def _add_parameters ( self , parameter_map , parameter_list ) : for parameter in parameter_list : if parameter . get ( '$ref' ) : parameter = self . specification [ 'parameters' ] . get ( parameter . get ( '$ref' ) . split ( '/' ) [ - 1 ] ) parameter_map [ parameter [ 'name' ] ] = parameter
Populates the given parameter map with the list of parameters provided resolving any reference objects encountered .
30,009
def get_path_spec ( self , path , action = None ) : path_spec = None path_name = None for base_path in self . paths . keys ( ) : if path == base_path : path_spec = self . paths [ base_path ] path_name = base_path if path_spec is None : for base_path in self . paths . keys ( ) : regex_from_path = re . compile ( re . sub...
Get the specification matching with the given path .
30,010
def validate_request ( self , path , action , body = None , query = None ) : path_name , path_spec = self . get_path_spec ( path ) if path_spec is None : logging . warn ( "there is no path" ) return False if action not in path_spec . keys ( ) : logging . warn ( "this http method is unknown '{0}'" . format ( action ) ) ...
Check if the given request is valid . Validates the body and the query
30,011
def _validate_query_parameters ( self , query , action_spec ) : processed_params = [ ] for param_name , param_value in query . items ( ) : if param_name in action_spec [ 'parameters' ] . keys ( ) : processed_params . append ( param_name ) if action_spec [ 'parameters' ] [ param_name ] [ 'type' ] == 'array' : if not isi...
Check the query parameter for the action specification .
30,012
def _validate_body_parameters ( self , body , action_spec ) : processed_params = [ ] for param_name , param_spec in action_spec [ 'parameters' ] . items ( ) : if param_spec [ 'in' ] == 'body' : processed_params . append ( param_name ) if 'type' in param_spec . keys ( ) and not self . check_type ( body , param_spec [ 't...
Check the body parameter for the action specification .
30,013
def get_response_example ( self , resp_spec ) : if 'schema' in resp_spec . keys ( ) : if '$ref' in resp_spec [ 'schema' ] : definition_name = self . get_definition_name_from_ref ( resp_spec [ 'schema' ] [ '$ref' ] ) return self . definitions_example [ definition_name ] elif 'items' in resp_spec [ 'schema' ] and resp_sp...
Get a response example from a response spec .
30,014
def get_request_data ( self , path , action , body = None ) : body = body or '' path_name , path_spec = self . get_path_spec ( path ) response = { } if path_spec is not None and action in path_spec . keys ( ) : for status_code in path_spec [ action ] [ 'responses' ] . keys ( ) : resp = path_spec [ action ] [ 'responses...
Get the default data and status code of the given path + action request .
30,015
def get_send_request_correct_body ( self , path , action ) : path_name , path_spec = self . get_path_spec ( path ) if path_spec is not None and action in path_spec . keys ( ) : for name , spec in path_spec [ action ] [ 'parameters' ] . items ( ) : if spec [ 'in' ] == 'body' : if 'type' in spec . keys ( ) : return self ...
Get an example body which is correct to send to the given path with the given action .
30,016
def normalize_hex ( hex_value ) : match = HEX_COLOR_RE . match ( hex_value ) if match is None : raise ValueError ( u"'{}' is not a valid hexadecimal color value." . format ( hex_value ) ) hex_digits = match . group ( 1 ) if len ( hex_digits ) == 3 : hex_digits = u'' . join ( 2 * s for s in hex_digits ) return u'#{}' . ...
Normalize a hexadecimal color value to 6 digits lowercase .
30,017
def html5_parse_simple_color ( input ) : if not isinstance ( input , unicode ) or len ( input ) != 7 : raise ValueError ( u"An HTML5 simple color must be a Unicode string " u"exactly seven characters long." ) if not input . startswith ( '#' ) : raise ValueError ( u"An HTML5 simple color must begin with the " u"characte...
Apply the simple color parsing algorithm from section 2 . 4 . 6 of HTML5 .
30,018
def html5_serialize_simple_color ( simple_color ) : red , green , blue = simple_color result = u'#' format_string = '{:02x}' result += format_string . format ( red ) result += format_string . format ( green ) result += format_string . format ( blue ) return result
Apply the serialization algorithm for a simple color from section 2 . 4 . 6 of HTML5 .
30,019
def html5_parse_legacy_color ( input ) : if not isinstance ( input , unicode ) : raise ValueError ( u"HTML5 legacy color parsing requires a Unicode string as input." ) if input == "" : raise ValueError ( u"HTML5 legacy color parsing forbids empty string as a value." ) input = input . strip ( ) if input . lower ( ) == u...
Apply the legacy color parsing algorithm from section 2 . 4 . 6 of HTML5 .
30,020
def create ( cls , data , id_ = None , ** kwargs ) : r from . models import RecordMetadata with db . session . begin_nested ( ) : record = cls ( data ) before_record_insert . send ( current_app . _get_current_object ( ) , record = record ) record . validate ( ** kwargs ) record . model = RecordMetadata ( id = id_ , jso...
r Create a new record instance and store it in the database .
30,021
def get_record ( cls , id_ , with_deleted = False ) : with db . session . no_autoflush : query = RecordMetadata . query . filter_by ( id = id_ ) if not with_deleted : query = query . filter ( RecordMetadata . json != None ) obj = query . one ( ) return cls ( obj . json , model = obj )
Retrieve the record by id .
30,022
def get_records ( cls , ids , with_deleted = False ) : with db . session . no_autoflush : query = RecordMetadata . query . filter ( RecordMetadata . id . in_ ( ids ) ) if not with_deleted : query = query . filter ( RecordMetadata . json != None ) return [ cls ( obj . json , model = obj ) for obj in query . all ( ) ]
Retrieve multiple records by id .
30,023
def patch ( self , patch ) : data = apply_patch ( dict ( self ) , patch ) return self . __class__ ( data , model = self . model )
Patch record metadata .
30,024
def commit ( self , ** kwargs ) : r if self . model is None or self . model . json is None : raise MissingModelError ( ) with db . session . begin_nested ( ) : before_record_update . send ( current_app . _get_current_object ( ) , record = self ) self . validate ( ** kwargs ) self . model . json = dict ( self ) flag_mod...
r Store changes of the current record instance in the database .
30,025
def revert ( self , revision_id ) : if self . model is None : raise MissingModelError ( ) revision = self . revisions [ revision_id ] with db . session . begin_nested ( ) : before_record_revert . send ( current_app . _get_current_object ( ) , record = self ) self . model . json = dict ( revision ) db . session . merge ...
Revert the record to a specific revision .
30,026
def validate ( self , data , schema , ** kwargs ) : if not isinstance ( schema , dict ) : schema = { '$ref' : schema } return validate ( data , schema , resolver = self . ref_resolver_cls . from_schema ( schema ) , types = self . app . config . get ( 'RECORDS_VALIDATION_TYPES' , { } ) , ** kwargs )
Validate data using schema with JSONResolver .
30,027
def to_filelink ( self ) : if self . status != 'completed' : return 'Audio/video conversion not complete!' response = utils . make_call ( self . url , 'get' ) if response . ok : response = response . json ( ) handle = re . match ( r'(?:https:\/\/cdn\.filestackcontent\.com\/)(\w+)' , response [ 'data' ] [ 'url' ] ) . gr...
Checks is the status of the conversion is complete and if so converts to a Filelink
30,028
def _return_tag_task ( self , task ) : if self . security is None : raise Exception ( 'Tags require security' ) tasks = [ task ] transform_url = get_transform_url ( tasks , handle = self . handle , security = self . security , apikey = self . apikey ) response = make_call ( CDN_URL , 'get' , handle = self . handle , se...
Runs both SFW and Tags tasks
30,029
def url ( self ) : return get_url ( CDN_URL , handle = self . handle , security = self . security )
Returns the URL for the instance which can be used to retrieve delete and overwrite the file . If security is enabled signature and policy parameters will be included
30,030
def zip ( self , store = False , store_params = None ) : params = locals ( ) params . pop ( 'store' ) params . pop ( 'store_params' ) new_transform = self . add_transform_task ( 'zip' , params ) if store : return new_transform . store ( ** store_params ) if store_params else new_transform . store ( ) return utils . mak...
Returns a zip file of the current transformation . This is different from the zip function that lives on the Filestack Client
30,031
def av_convert ( self , preset = None , force = None , title = None , extname = None , filename = None , width = None , height = None , upscale = None , aspect_mode = None , two_pass = None , video_bitrate = None , fps = None , keyframe_interval = None , location = None , watermark_url = None , watermark_top = None , w...
python from filestack import Client
30,032
def add_transform_task ( self , transformation , params ) : if not isinstance ( self , filestack . models . Transform ) : instance = filestack . models . Transform ( apikey = self . apikey , security = self . security , handle = self . handle ) else : instance = self params . pop ( 'self' ) params = { k : v for k , v i...
Adds a transform task to the current instance and returns it
30,033
def download ( self , destination_path , params = None ) : if params : CONTENT_DOWNLOAD_SCHEMA . check ( params ) with open ( destination_path , 'wb' ) as new_file : response = utils . make_call ( CDN_URL , 'get' , handle = self . handle , params = params , security = self . security , transform_url = ( self . url if i...
Downloads a file to the given local path and returns the size of the downloaded file if successful
30,034
def get_content ( self , params = None ) : if params : CONTENT_DOWNLOAD_SCHEMA . check ( params ) response = utils . make_call ( CDN_URL , 'get' , handle = self . handle , params = params , security = self . security , transform_url = ( self . url if isinstance ( self , filestack . models . Transform ) else None ) ) re...
Returns the raw byte content of a given Filelink
30,035
def get_metadata ( self , params = None ) : metadata_url = "{CDN_URL}/{handle}/metadata" . format ( CDN_URL = CDN_URL , handle = self . handle ) response = utils . make_call ( metadata_url , 'get' , params = params , security = self . security ) return response . json ( )
Metadata provides certain information about a Filehandle and you can specify which pieces of information you will receive back by passing in optional parameters .
30,036
def delete ( self , params = None ) : if params : params [ 'key' ] = self . apikey else : params = { 'key' : self . apikey } return utils . make_call ( API_URL , 'delete' , path = FILE_PATH , handle = self . handle , params = params , security = self . security , transform_url = self . url if isinstance ( self , filest...
You may delete any file you have uploaded either through a Filelink returned from the client or one you have initialized yourself . This returns a response of success or failure . This action requires security . abs
30,037
def overwrite ( self , url = None , filepath = None , params = None ) : if params : OVERWRITE_SCHEMA . check ( params ) data , files = None , None if url : data = { 'url' : url } elif filepath : filename = os . path . basename ( filepath ) mimetype = mimetypes . guess_type ( filepath ) [ 0 ] files = { 'fileUpload' : ( ...
You may overwrite any Filelink by supplying a new file . The Filehandle will remain the same .
30,038
def validate ( policy ) : for param , value in policy . items ( ) : if param not in ACCEPTED_SECURITY_TYPES . keys ( ) : raise SecurityError ( 'Invalid Security Parameter: {}' . format ( param ) ) if type ( value ) != ACCEPTED_SECURITY_TYPES [ param ] : raise SecurityError ( 'Invalid Parameter Data Type for {}, ' 'Expe...
Validates a policy and its parameters and raises an error if invalid
30,039
def security ( policy , app_secret ) : validate ( policy ) policy_enc = base64 . urlsafe_b64encode ( json . dumps ( policy ) . encode ( 'utf-8' ) ) signature = hmac . new ( app_secret . encode ( 'utf-8' ) , policy_enc , hashlib . sha256 ) . hexdigest ( ) return { 'policy' : policy_enc , 'signature' : signature }
Creates a valid signature and policy based on provided app secret and parameters python from filestack import Client security
30,040
def transform_external ( self , external_url ) : return filestack . models . Transform ( apikey = self . apikey , security = self . security , external_url = external_url )
Turns an external URL into a Filestack Transform object
30,041
def urlscreenshot ( self , external_url , agent = None , mode = None , width = None , height = None , delay = None ) : params = locals ( ) params . pop ( 'self' ) params . pop ( 'external_url' ) params = { k : v for k , v in params . items ( ) if v is not None } url_task = utils . return_transform_task ( 'urlscreenshot...
Takes a screenshot of the given URL
30,042
def zip ( self , destination_path , files ) : zip_url = "{}/{}/zip/[{}]" . format ( CDN_URL , self . apikey , ',' . join ( files ) ) with open ( destination_path , 'wb' ) as new_file : response = utils . make_call ( zip_url , 'get' ) if response . ok : for chunk in response . iter_content ( 1024 ) : if not chunk : brea...
Takes array of files and downloads a compressed ZIP archive to provided path
30,043
def url ( self ) : return utils . get_transform_url ( self . _transformation_tasks , external_url = self . external_url , handle = self . handle , security = self . security , apikey = self . apikey )
Returns the URL for the current transformation which can be used to retrieve the file . If security is enabled signature and policy parameters will be included
30,044
def store ( self , filename = None , location = None , path = None , container = None , region = None , access = None , base64decode = None ) : if path : path = '"{}"' . format ( path ) filelink_obj = self . add_transform_task ( 'store' , locals ( ) ) response = utils . make_call ( filelink_obj . url , 'get' ) if respo...
Uploads and stores the current transformation as a Fileink
30,045
def debug ( self ) : debug_instance = self . add_transform_task ( 'debug' , locals ( ) ) response = utils . make_call ( debug_instance . url , 'get' ) return response . json ( )
Returns a JSON object with inforamtion regarding the current transformation
30,046
def real_python3 ( python , version_dict ) : args = [ python , '-c' , 'import sys; print(sys.real_prefix)' ] try : output = subprocess . check_output ( args , stderr = subprocess . STDOUT ) prefix = output . decode ( 'UTF-8' ) . strip ( ) except subprocess . CalledProcessError : return python if os . name == 'nt' : pat...
Determine the path of the real python executable which is then used for venv creation . This is necessary because an active virtualenv environment will cause venv creation to malfunction . By getting the path of the real executable this issue is bypassed .
30,047
def today ( year = None ) : return datetime . date ( int ( year ) , _date . month , _date . day ) if year else _date
this day last year
30,048
def tomorrow ( date = None ) : if not date : return _date + datetime . timedelta ( days = 1 ) else : current_date = parse ( date ) return current_date + datetime . timedelta ( days = 1 )
tomorrow is another day
30,049
def yesterday ( date = None ) : if not date : return _date - datetime . timedelta ( days = 1 ) else : current_date = parse ( date ) return current_date - datetime . timedelta ( days = 1 )
yesterday once more
30,050
def days_range ( first = None , second = None , wipe = False ) : _first , _second = parse ( first ) , parse ( second ) ( _start , _end ) = ( _second , _first ) if _first > _second else ( _first , _second ) days_between = ( _end - _start ) . days date_list = [ _end - datetime . timedelta ( days = x ) for x in range ( 0 ...
get all days between first and second
30,051
def is_installed ( self , bug : Bug ) -> bool : r = self . __api . get ( 'bugs/{}/installed' . format ( bug . name ) ) if r . status_code == 200 : answer = r . json ( ) assert isinstance ( answer , bool ) return answer if r . status_code == 404 : raise KeyError ( "no bug found with given name: {}" . format ( bug . name...
Determines whether the Docker image for a given bug has been installed on the server .
30,052
def uninstall ( self , bug : Bug ) -> bool : r = self . __api . post ( 'bugs/{}/uninstall' . format ( bug . name ) ) raise NotImplementedError
Uninstalls the Docker image associated with a given bug .
30,053
def build ( self , bug : Bug ) : r = self . __api . post ( 'bugs/{}/build' . format ( bug . name ) ) if r . status_code == 204 : return if r . status_code == 200 : raise Exception ( "bug already built: {}" . format ( bug . name ) ) if r . status_code == 400 : raise Exception ( "build failure" ) if r . status_code == 40...
Instructs the server to build the Docker image associated with a given bug .
30,054
def refresh ( self ) -> None : logger . info ( 'refreshing sources' ) for source in list ( self ) : self . unload ( source ) if not os . path . exists ( self . __registry_fn ) : return with open ( self . __registry_fn , 'r' ) as f : registry = yaml . load ( f ) assert isinstance ( registry , list ) for source_descripti...
Reloads all sources that are registered with this server .
30,055
def update ( self ) -> None : for source_old in self : if isinstance ( source_old , RemoteSource ) : repo = git . Repo ( source_old . location ) origin = repo . remotes . origin origin . pull ( ) sha = repo . head . object . hexsha version = repo . git . rev_parse ( sha , short = 8 ) if version != source_old . version ...
Ensures that all remote sources are up - to - date .
30,056
def save ( self ) -> None : logger . info ( 'saving registry to: %s' , self . __registry_fn ) d = [ s . to_dict ( ) for s in self ] os . makedirs ( self . __path , exist_ok = True ) with open ( self . __registry_fn , 'w' ) as f : yaml . dump ( d , f , indent = 2 , default_flow_style = False ) logger . info ( 'saved reg...
Saves the contents of the source manager to disk .
30,057
def unload ( self , source : Source ) -> None : logger . info ( 'unloading source: %s' , source . name ) try : contents = self . contents ( source ) del self . __contents [ source . name ] del self . __sources [ source . name ] for name in contents . bugs : bug = self . __installation . bugs [ name ] self . __installat...
Unloads a registered source causing all of its associated bugs tools and blueprints to also be unloaded . If the given source is not loaded this function will do nothing .
30,058
def add ( self , name : str , path_or_url : str ) -> Source : logger . info ( "adding source: %s -> %s" , name , path_or_url ) if name in self . __sources : logger . info ( "name already used by existing source: %s" , name ) raise NameInUseError ( name ) is_url = False try : scheme = urllib . parse . urlparse ( path_or...
Attempts to register a source provided by a given URL or local path under a given name .
30,059
def remove ( self , source : Source ) -> None : self . unload ( source ) if isinstance ( source , RemoteSource ) : shutil . rmtree ( source . location , ignore_errors = True ) self . save ( )
Unregisters a given source with this server . If the given source is a remote source then its local copy will be removed from disk .
30,060
def is_installed ( self , bug : Bug ) -> bool : return self . __installation . build . is_installed ( bug . image )
Determines whether or not the Docker image for a given bug has been installed onto this server .
30,061
def build ( self , bug : Bug , force : bool = True , quiet : bool = False ) -> None : self . __installation . build . build ( bug . image , force = force , quiet = quiet )
Builds the Docker image associated with a given bug .
30,062
def uninstall ( self , bug : Bug , force : bool = False , noprune : bool = False ) -> None : self . __installation . build . uninstall ( bug . image , force = force , noprune = noprune )
Uninstalls all Docker images associated with this bug .
30,063
def validate ( self , bug : Bug , verbose : bool = True ) -> bool : try : self . build ( bug , force = True , quiet = True ) except docker . errors . BuildError : print ( "failed to build bug: {}" . format ( self . identifier ) ) return False validated = True try : c = None c = self . __installation . containers . prov...
Checks that a given bug successfully builds and that it produces an expected set of test suite outcomes .
30,064
def coverage ( self , bug : Bug ) -> TestSuiteCoverage : fn = os . path . join ( self . __installation . coverage_path , "{}.coverage.yml" . format ( bug . name ) ) if os . path . exists ( fn ) : return TestSuiteCoverage . from_file ( fn ) mgr_ctr = self . __installation . containers container = None try : container = ...
Provides coverage information for each test within the test suite for the program associated with this bug .
30,065
def clear ( self ) -> None : logger . debug ( "clearing all running containers" ) all_uids = [ uid for uid in self . __containers . keys ( ) ] for uid in all_uids : try : del self [ uid ] except KeyError : pass logger . debug ( "cleared all running containers" )
Closes all running containers .
30,066
def bug ( self , container : Container ) -> Bug : name = container . bug return self . __installation . bugs [ name ]
Returns a description of the bug inside a given container .
30,067
def mktemp ( self , container : Container ) -> str : logger . debug ( "creating a temporary file inside container %s" , container . uid ) response = self . command ( container , "mktemp" ) if response . code != 0 : msg = "failed to create temporary file for container {}: [{}] {}" msg = msg . format ( uid , response . c...
Creates a named temporary file within a given container .
30,068
def is_alive ( self , container : Container ) -> bool : uid = container . uid return uid in self . __dockerc and self . __dockerc [ uid ] . status == 'running'
Determines whether a given container is still alive .
30,069
def coverage_extractor ( self , container : Container ) -> CoverageExtractor : return CoverageExtractor . build ( self . __installation , container )
Retrieves the coverage extractor for a given container .
30,070
def coverage ( self , container : Container , tests : Optional [ Iterable [ TestCase ] ] = None , * , instrument : bool = True ) -> TestSuiteCoverage : extractor = self . coverage_extractor ( container ) if tests is None : bugs = self . __installation . bugs bug = bugs [ container . bug ] tests = bug . tests return ext...
Computes line coverage information over a provided set of tests for the program inside a given container .
30,071
def execute ( self , container : Container , test : TestCase , verbose : bool = False ) -> TestOutcome : bug = self . __installation . bugs [ container . bug ] response = self . command ( container , cmd = test . command , context = test . context , stderr = True , time_limit = test . time_limit , kill_after = test . k...
Runs a specified test inside a given container .
30,072
def compile_with_instrumentation ( self , container : Container , verbose : bool = False ) -> CompilationOutcome : bug = self . __installation . bugs [ container . bug ] bug . compiler . clean ( self , container , verbose = verbose ) return bug . compiler . compile_with_coverage_instrumentation ( self , container , ver...
Attempts to compile the program inside a given container with instrumentation enabled .
30,073
def copy_to ( self , container : Container , fn_host : str , fn_container : str ) -> None : logger . debug ( "Copying file to container, %s: %s -> %s" , container . uid , fn_host , fn_container ) if not os . path . exists ( fn_host ) : logger . error ( "Failed to copy file [%s] to [%s] in container [%s]: not found." , ...
Copies a file from the host machine to a specified location inside a container .
30,074
def copy_from ( self , container : Container , fn_container : str , fn_host : str ) -> None : logger . debug ( "Copying file from container, %s: %s -> %s" , container . uid , fn_container , fn_host ) cmd = "docker cp '{}:{}' '{}'" . format ( container . id , fn_container , fn_host ) try : subprocess . check_output ( cm...
Copies a given file from the container to a specified location on the host machine .
30,075
def command ( self , container : Container , cmd : str , context : Optional [ str ] = None , stdout : bool = True , stderr : bool = False , block : bool = True , verbose : bool = False , time_limit : Optional [ int ] = None , kill_after : Optional [ int ] = 1 ) -> Union [ ExecResponse , PendingExecResponse ] : cmd_orig...
Executes a provided shell command inside a given container .
30,076
def persist ( self , container : Container , image : str ) -> None : logger_c = logger . getChild ( container . uid ) logger_c . debug ( "Persisting container as a Docker image: %s" , image ) try : docker_container = self . __dockerc [ container . uid ] except KeyError : logger_c . exception ( "Failed to persist contai...
Persists the state of a given container to a BugZoo image on this server .
30,077
def ephemeral ( * , port : int = 6060 , timeout_connection : int = 30 , verbose : bool = False ) -> Iterator [ Client ] : url = "http://127.0.0.1:{}" . format ( port ) cmd = [ "bugzood" , "--debug" , "-p" , str ( port ) ] try : stdout = None if verbose else subprocess . DEVNULL stderr = None if verbose else subprocess ...
Launches an ephemeral server instance that will be immediately close when no longer in context .
30,078
def register ( name : str ) : def decorator ( cls : Type [ 'CoverageExtractor' ] ) : cls . register ( name ) return cls return decorator
Registers a coverage extractor class under a given name .
30,079
def register_as_default ( language : Language ) : def decorator ( cls : Type [ 'CoverageExtractor' ] ) : cls . register_as_default ( language ) return cls return decorator
Registers a coverage extractor class as the default coverage extractor for a given language . Requires that the coverage extractor class has already been registered with a given name .
30,080
def build ( installation : 'BugZoo' , container : Container ) -> 'CoverageExtractor' : bug = installation . bugs [ container . bug ] instructions = bug . instructions_coverage if instructions is None : raise exceptions . NoCoverageInstructions name = instructions . __class__ . registered_under_name ( ) extractor_cls = ...
Constructs a CoverageExtractor for a given container using the coverage instructions provided by its accompanying bug description .
30,081
def run ( self , tests : Iterable [ TestCase ] , * , instrument : bool = True ) -> TestSuiteCoverage : container = self . container logger . debug ( "computing coverage for container: %s" , container . uid ) try : if instrument : logger . debug ( "instrumenting container" ) self . prepare ( ) else : logger . debug ( "n...
Computes line coverage information for a given set of tests .
30,082
def from_dict ( d : Dict [ str , Any ] ) -> 'BugZooException' : assert 'error' in d d = d [ 'error' ] cls = getattr ( sys . modules [ __name__ ] , d [ 'kind' ] ) assert issubclass ( cls , BugZooException ) return cls . from_message_and_data ( d [ 'message' ] , d . get ( 'data' , { } ) )
Reconstructs a BugZoo exception from a dictionary - based description .
30,083
def from_message_and_data ( cls , message : str , data : Dict [ str , Any ] ) -> 'BugZooException' : return cls ( message )
Reproduces an exception from the message and data contained in its dictionary - based description .
30,084
def to_dict ( self ) -> Dict [ str , Any ] : jsn = { 'kind' : self . __class__ . __name__ , 'message' : self . message } data = self . data if data : jsn [ 'data' ] = data jsn = { 'error' : jsn } return jsn
Creates a dictionary - based description of this exception ready to be serialised as JSON or YAML .
30,085
def _read_next ( cls , lines : List [ str ] ) -> 'Hunk' : header = lines [ 0 ] assert header . startswith ( '@@ -' ) end_header_at = header . index ( ' @@' ) bonus_line = header [ end_header_at + 3 : ] if bonus_line != "" : lines . insert ( 1 , bonus_line ) header = header [ 4 : end_header_at ] left , _ , right = heade...
Constructs a hunk from a supplied fragment of a unified format diff .
30,086
def _read_next ( cls , lines : List [ str ] ) -> 'FilePatch' : while True : if not lines : raise Exception ( "illegal file patch format: couldn't find line starting with '---'" ) line = lines [ 0 ] if line . startswith ( '---' ) : break lines . pop ( 0 ) assert lines [ 0 ] . startswith ( '---' ) assert lines [ 1 ] . st...
Destructively extracts the next file patch from the line buffer .
30,087
def from_unidiff ( cls , diff : str ) -> 'Patch' : lines = diff . split ( '\n' ) file_patches = [ ] while lines : if lines [ 0 ] == '' or lines [ 0 ] . isspace ( ) : lines . pop ( 0 ) continue file_patches . append ( FilePatch . _read_next ( lines ) ) return Patch ( file_patches )
Constructs a Patch from a provided unified format diff .
30,088
def clear ( self ) -> None : r = self . __api . delete ( 'containers' ) if r . status_code != 204 : self . __api . handle_erroneous_response ( r )
Destroys all running containers .
30,089
def provision ( self , bug : Bug , * , plugins : Optional [ List [ Tool ] ] = None ) -> Container : if plugins is None : plugins = [ ] logger . info ( "provisioning container for bug: %s" , bug . name ) endpoint = 'bugs/{}/provision' . format ( bug . name ) payload = { 'plugins' : [ p . to_dict ( ) for p in plugins ] }...
Provisions a container for a given bug .
30,090
def mktemp ( self , container : Container ) -> str : r = self . __api . post ( 'containers/{}/tempfile' . format ( container . uid ) ) if r . status_code == 200 : return r . json ( ) self . __api . handle_erroneous_response ( r )
Generates a temporary file for a given container .
30,091
def is_alive ( self , container : Container ) -> bool : uid = container . uid r = self . __api . get ( 'containers/{}/alive' . format ( uid ) ) if r . status_code == 200 : return r . json ( ) if r . status_code == 404 : raise KeyError ( "no container found with given UID: {}" . format ( uid ) ) self . __api . handle_er...
Determines whether or not a given container is still alive .
30,092
def extract_coverage ( self , container : Container ) -> FileLineSet : uid = container . uid r = self . __api . post ( 'containers/{}/read-coverage' . format ( uid ) ) if r . status_code == 200 : return FileLineSet . from_dict ( r . json ( ) ) self . __api . handle_erroneous_response ( r )
Extracts a report of the lines that have been executed since the last time that a coverage report was extracted .
30,093
def instrument ( self , container : Container ) -> None : path = "containers/{}/instrument" . format ( container . uid ) r = self . __api . post ( path ) if r . status_code != 204 : logger . info ( "failed to instrument container: %s" , container . uid ) self . __api . handle_erroneous_response ( r )
Instruments the program inside the container for computing test suite coverage .
30,094
def coverage ( self , container : Container , * , instrument : bool = True ) -> TestSuiteCoverage : uid = container . uid logger . info ( "Fetching coverage information for container: %s" , uid ) uri = 'containers/{}/coverage' . format ( uid ) r = self . __api . post ( uri , params = { 'instrument' : 'yes' if instrumen...
Computes complete test suite coverage for a given container .
30,095
def exec ( self , container : Container , command : str , context : Optional [ str ] = None , stdout : bool = True , stderr : bool = False , time_limit : Optional [ int ] = None ) -> ExecResponse : payload = { 'command' : command , 'context' : context , 'stdout' : stdout , 'stderr' : stderr , 'time-limit' : time_limit ...
Executes a given command inside a provided container .
30,096
def persist ( self , container : Container , image_name : str ) -> None : logger . debug ( "attempting to persist container (%s) to image (%s)." , container . id , image_name ) path = "containers/{}/persist/{}" . format ( container . id , image_name ) r = self . __api . put ( path ) if r . status_code == 204 : logger ....
Persists the state of a given container as a Docker image on the server .
30,097
def from_dict ( d : dict ) -> 'SimpleCompiler' : cmd = d [ 'command' ] cmd_with_instrumentation = d . get ( 'command_with_instrumentation' , None ) time_limit = d [ 'time-limit' ] context = d [ 'context' ] cmd_clean = d . get ( 'command_clean' , 'exit 0' ) return SimpleCompiler ( command = cmd , command_clean = cmd_cle...
Loads a SimpleCompiler from its dictionary - based description .
30,098
def get_tags ( doc ) : tags = list ( ) for el in doc . getroot ( ) . iter ( ) : if isinstance ( el , lxml . html . HtmlElement ) : tags . append ( el . tag ) elif isinstance ( el , lxml . html . HtmlComment ) : tags . append ( 'comment' ) else : raise ValueError ( 'Don\'t know what to do with element: {}' . format ( el...
Get tags from a DOM tree
30,099
def _url ( self , path : str ) -> str : url = "{}/{}" . format ( self . __base_url , path ) logger . debug ( "transformed path [%s] into url: %s" , path , url ) return url
Computes the URL for a resource located at a given path on the server .