idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
235,000
def get_archive_file_list ( archive_filename ) : if archive_filename . endswith ( '.zip' ) : with closing ( zipfile . ZipFile ( archive_filename ) ) as zf : return add_directories ( zf . namelist ( ) ) elif archive_filename . endswith ( ( '.tar.gz' , '.tar.bz2' , '.tar' ) ) : with closing ( tarfile . open ( archive_filename ) ) as tf : return add_directories ( list ( map ( unicodify , tf . getnames ( ) ) ) ) else : ext = os . path . splitext ( archive_filename ) [ - 1 ] raise Failure ( 'Unrecognized archive type: %s' % ext )
Return the list of files in an archive .
167
9
235,001
def strip_toplevel_name ( filelist ) : if not filelist : return filelist prefix = filelist [ 0 ] if '/' in prefix : prefix = prefix . partition ( '/' ) [ 0 ] + '/' names = filelist else : prefix = prefix + '/' names = filelist [ 1 : ] for name in names : if not name . startswith ( prefix ) : raise Failure ( "File doesn't have the common prefix (%s): %s" % ( name , prefix ) ) return [ name [ len ( prefix ) : ] for name in names ]
Strip toplevel name from a file list .
124
11
235,002
def detect_vcs ( ) : location = os . path . abspath ( '.' ) while True : for vcs in Git , Mercurial , Bazaar , Subversion : if vcs . detect ( location ) : return vcs parent = os . path . dirname ( location ) if parent == location : raise Failure ( "Couldn't find version control data" " (git/hg/bzr/svn supported)" ) location = parent
Detect the version control system used for the current directory .
98
11
235,003
def normalize_name ( name ) : name = os . path . normpath ( name ) name = unicodify ( name ) if sys . platform == 'darwin' : # Mac OSX may have problems comparing non-ascii filenames, so # we convert them. name = unicodedata . normalize ( 'NFC' , name ) return name
Some VCS print directory names with trailing slashes . Strip them .
79
14
235,004
def read_config ( ) : # XXX modifies global state, which is kind of evil config = _load_config ( ) if config . get ( CFG_IGNORE_DEFAULT_RULES [ 1 ] , False ) : del IGNORE [ : ] if CFG_IGNORE [ 1 ] in config : IGNORE . extend ( p for p in config [ CFG_IGNORE [ 1 ] ] if p ) if CFG_IGNORE_BAD_IDEAS [ 1 ] in config : IGNORE_BAD_IDEAS . extend ( p for p in config [ CFG_IGNORE_BAD_IDEAS [ 1 ] ] if p )
Read configuration from file if possible .
145
7
235,005
def _load_config ( ) : if os . path . exists ( "pyproject.toml" ) : config = toml . load ( "pyproject.toml" ) if CFG_SECTION_CHECK_MANIFEST in config . get ( "tool" , { } ) : return config [ "tool" ] [ CFG_SECTION_CHECK_MANIFEST ] search_files = [ 'setup.cfg' , 'tox.ini' ] config_parser = ConfigParser . ConfigParser ( ) for filename in search_files : if ( config_parser . read ( [ filename ] ) and config_parser . has_section ( CFG_SECTION_CHECK_MANIFEST ) ) : config = { } if config_parser . has_option ( * CFG_IGNORE_DEFAULT_RULES ) : ignore_defaults = config_parser . getboolean ( * CFG_IGNORE_DEFAULT_RULES ) config [ CFG_IGNORE_DEFAULT_RULES [ 1 ] ] = ignore_defaults if config_parser . has_option ( * CFG_IGNORE ) : patterns = [ p . strip ( ) for p in config_parser . get ( * CFG_IGNORE ) . splitlines ( ) ] config [ CFG_IGNORE [ 1 ] ] = patterns if config_parser . has_option ( * CFG_IGNORE_BAD_IDEAS ) : patterns = [ p . strip ( ) for p in config_parser . get ( * CFG_IGNORE_BAD_IDEAS ) . splitlines ( ) ] config [ CFG_IGNORE_BAD_IDEAS [ 1 ] ] = patterns return config return { }
Searches for config files reads them and returns a dictionary
376
12
235,006
def read_manifest ( ) : # XXX modifies global state, which is kind of evil if not os . path . isfile ( 'MANIFEST.in' ) : return ignore , ignore_regexps = _get_ignore_from_manifest ( 'MANIFEST.in' ) IGNORE . extend ( ignore ) IGNORE_REGEXPS . extend ( ignore_regexps )
Read existing configuration from MANIFEST . in .
87
10
235,007
def file_matches ( filename , patterns ) : return any ( fnmatch . fnmatch ( filename , pat ) or fnmatch . fnmatch ( os . path . basename ( filename ) , pat ) for pat in patterns )
Does this filename match any of the patterns?
48
9
235,008
def file_matches_regexps ( filename , patterns ) : return any ( re . match ( pat , filename ) for pat in patterns )
Does this filename match any of the regular expressions?
31
10
235,009
def strip_sdist_extras ( filelist ) : return [ name for name in filelist if not file_matches ( name , IGNORE ) and not file_matches_regexps ( name , IGNORE_REGEXPS ) ]
Strip generated files that are only present in source distributions .
54
12
235,010
def find_suggestions ( filelist ) : suggestions = set ( ) unknowns = [ ] for filename in filelist : if os . path . isdir ( filename ) : # it's impossible to add empty directories via MANIFEST.in anyway, # and non-empty directories will be added automatically when we # specify patterns for files inside them continue for pattern , suggestion in SUGGESTIONS : m = pattern . match ( filename ) if m is not None : suggestions . add ( pattern . sub ( suggestion , filename ) ) break else : unknowns . append ( filename ) return sorted ( suggestions ) , unknowns
Suggest MANIFEST . in patterns for missing files .
129
11
235,011
def extract_version_from_filename ( filename ) : filename = os . path . splitext ( os . path . basename ( filename ) ) [ 0 ] if filename . endswith ( '.tar' ) : filename = os . path . splitext ( filename ) [ 0 ] return filename . partition ( '-' ) [ 2 ]
Extract version number from sdist filename .
73
9
235,012
def zest_releaser_check ( data ) : from zest . releaser . utils import ask source_tree = data [ 'workingdir' ] if not is_package ( source_tree ) : # You can use zest.releaser on things that are not Python packages. # It's pointless to run check-manifest in those circumstances. # See https://github.com/mgedmin/check-manifest/issues/9 for details. return if not ask ( "Do you want to run check-manifest?" ) : return try : if not check_manifest ( source_tree ) : if not ask ( "MANIFEST.in has problems. " " Do you want to continue despite that?" , default = False ) : sys . exit ( 1 ) except Failure as e : error ( str ( e ) ) if not ask ( "Something bad happened. " " Do you want to continue despite that?" , default = False ) : sys . exit ( 2 )
Check the completeness of MANIFEST . in before the release .
212
14
235,013
def get_versioned_files ( cls ) : files = cls . _git_ls_files ( ) submodules = cls . _list_submodules ( ) for subdir in submodules : subdir = os . path . relpath ( subdir ) . replace ( os . path . sep , '/' ) files += add_prefix_to_each ( subdir , cls . _git_ls_files ( subdir ) ) return add_directories ( files )
List all files versioned by git in the current directory .
105
12
235,014
def get_versioned_files ( cls ) : encoding = cls . _get_terminal_encoding ( ) output = run ( [ 'bzr' , 'ls' , '-VR' ] , encoding = encoding ) return output . splitlines ( )
List all files versioned in Bazaar in the current directory .
59
13
235,015
def get_versioned_files ( cls ) : output = run ( [ 'svn' , 'st' , '-vq' , '--xml' ] , decode = False ) tree = ET . XML ( output ) return sorted ( entry . get ( 'path' ) for entry in tree . findall ( './/entry' ) if cls . is_interesting ( entry ) )
List all files under SVN control in the current directory .
85
12
235,016
def is_interesting ( entry ) : if entry . get ( 'path' ) == '.' : return False status = entry . find ( 'wc-status' ) if status is None : warning ( 'svn status --xml parse error: <entry path="%s"> without' ' <wc-status>' % entry . get ( 'path' ) ) return False # For SVN externals we get two entries: one mentioning the # existence of the external, and one about the status of the external. if status . get ( 'item' ) in ( 'unversioned' , 'external' ) : return False return True
Is this entry interesting?
137
5
235,017
def validate ( self ) : if not self . principals : raise InvalidApplicationPolicyError ( error_message = 'principals not provided' ) if not self . actions : raise InvalidApplicationPolicyError ( error_message = 'actions not provided' ) if any ( not self . _PRINCIPAL_PATTERN . match ( p ) for p in self . principals ) : raise InvalidApplicationPolicyError ( error_message = 'principal should be 12-digit AWS account ID or "*"' ) unsupported_actions = sorted ( set ( self . actions ) - set ( self . SUPPORTED_ACTIONS ) ) if unsupported_actions : raise InvalidApplicationPolicyError ( error_message = '{} not supported' . format ( ', ' . join ( unsupported_actions ) ) ) return True
Check if the formats of principals and actions are valid .
169
11
235,018
def publish_application ( template , sar_client = None ) : if not template : raise ValueError ( 'Require SAM template to publish the application' ) if not sar_client : sar_client = boto3 . client ( 'serverlessrepo' ) template_dict = _get_template_dict ( template ) app_metadata = get_app_metadata ( template_dict ) stripped_template_dict = strip_app_metadata ( template_dict ) stripped_template = yaml_dump ( stripped_template_dict ) try : request = _create_application_request ( app_metadata , stripped_template ) response = sar_client . create_application ( * * request ) application_id = response [ 'ApplicationId' ] actions = [ CREATE_APPLICATION ] except ClientError as e : if not _is_conflict_exception ( e ) : raise _wrap_client_error ( e ) # Update the application if it already exists error_message = e . response [ 'Error' ] [ 'Message' ] application_id = parse_application_id ( error_message ) try : request = _update_application_request ( app_metadata , application_id ) sar_client . update_application ( * * request ) actions = [ UPDATE_APPLICATION ] except ClientError as e : raise _wrap_client_error ( e ) # Create application version if semantic version is specified if app_metadata . semantic_version : try : request = _create_application_version_request ( app_metadata , application_id , stripped_template ) sar_client . create_application_version ( * * request ) actions . append ( CREATE_APPLICATION_VERSION ) except ClientError as e : if not _is_conflict_exception ( e ) : raise _wrap_client_error ( e ) return { 'application_id' : application_id , 'actions' : actions , 'details' : _get_publish_details ( actions , app_metadata . template_dict ) }
Create a new application or new application version in SAR .
434
11
235,019
def update_application_metadata ( template , application_id , sar_client = None ) : if not template or not application_id : raise ValueError ( 'Require SAM template and application ID to update application metadata' ) if not sar_client : sar_client = boto3 . client ( 'serverlessrepo' ) template_dict = _get_template_dict ( template ) app_metadata = get_app_metadata ( template_dict ) request = _update_application_request ( app_metadata , application_id ) sar_client . update_application ( * * request )
Update the application metadata .
126
5
235,020
def _get_template_dict ( template ) : if isinstance ( template , str ) : return parse_template ( template ) if isinstance ( template , dict ) : return copy . deepcopy ( template ) raise ValueError ( 'Input template should be a string or dictionary' )
Parse string template and or copy dictionary template .
59
10
235,021
def _create_application_request ( app_metadata , template ) : app_metadata . validate ( [ 'author' , 'description' , 'name' ] ) request = { 'Author' : app_metadata . author , 'Description' : app_metadata . description , 'HomePageUrl' : app_metadata . home_page_url , 'Labels' : app_metadata . labels , 'LicenseUrl' : app_metadata . license_url , 'Name' : app_metadata . name , 'ReadmeUrl' : app_metadata . readme_url , 'SemanticVersion' : app_metadata . semantic_version , 'SourceCodeUrl' : app_metadata . source_code_url , 'SpdxLicenseId' : app_metadata . spdx_license_id , 'TemplateBody' : template } # Remove None values return { k : v for k , v in request . items ( ) if v }
Construct the request body to create application .
200
8
235,022
def _update_application_request ( app_metadata , application_id ) : request = { 'ApplicationId' : application_id , 'Author' : app_metadata . author , 'Description' : app_metadata . description , 'HomePageUrl' : app_metadata . home_page_url , 'Labels' : app_metadata . labels , 'ReadmeUrl' : app_metadata . readme_url } return { k : v for k , v in request . items ( ) if v }
Construct the request body to update application .
109
8
235,023
def _create_application_version_request ( app_metadata , application_id , template ) : app_metadata . validate ( [ 'semantic_version' ] ) request = { 'ApplicationId' : application_id , 'SemanticVersion' : app_metadata . semantic_version , 'SourceCodeUrl' : app_metadata . source_code_url , 'TemplateBody' : template } return { k : v for k , v in request . items ( ) if v }
Construct the request body to create application version .
103
9
235,024
def _wrap_client_error ( e ) : error_code = e . response [ 'Error' ] [ 'Code' ] message = e . response [ 'Error' ] [ 'Message' ] if error_code == 'BadRequestException' : if "Failed to copy S3 object. Access denied:" in message : match = re . search ( 'bucket=(.+?), key=(.+?)$' , message ) if match : return S3PermissionsRequired ( bucket = match . group ( 1 ) , key = match . group ( 2 ) ) if "Invalid S3 URI" in message : return InvalidS3UriError ( message = message ) return ServerlessRepoClientError ( message = message )
Wrap botocore ClientError exception into ServerlessRepoClientError .
155
16
235,025
def _get_publish_details ( actions , app_metadata_template ) : if actions == [ CREATE_APPLICATION ] : return { k : v for k , v in app_metadata_template . items ( ) if v } include_keys = [ ApplicationMetadata . AUTHOR , ApplicationMetadata . DESCRIPTION , ApplicationMetadata . HOME_PAGE_URL , ApplicationMetadata . LABELS , ApplicationMetadata . README_URL ] if CREATE_APPLICATION_VERSION in actions : # SemanticVersion and SourceCodeUrl can only be updated by creating a new version additional_keys = [ ApplicationMetadata . SEMANTIC_VERSION , ApplicationMetadata . SOURCE_CODE_URL ] include_keys . extend ( additional_keys ) return { k : v for k , v in app_metadata_template . items ( ) if k in include_keys and v }
Get the changed application details after publishing .
192
8
235,026
def validate ( self , required_props ) : missing_props = [ p for p in required_props if not getattr ( self , p ) ] if missing_props : missing_props_str = ', ' . join ( sorted ( missing_props ) ) raise InvalidApplicationMetadataError ( properties = missing_props_str ) return True
Check if the required application metadata properties have been populated .
79
11
235,027
def yaml_dump ( dict_to_dump ) : yaml . SafeDumper . add_representer ( OrderedDict , _dict_representer ) return yaml . safe_dump ( dict_to_dump , default_flow_style = False )
Dump the dictionary as a YAML document .
58
11
235,028
def parse_template ( template_str ) : try : # PyYAML doesn't support json as well as it should, so if the input # is actually just json it is better to parse it with the standard # json parser. return json . loads ( template_str , object_pairs_hook = OrderedDict ) except ValueError : yaml . SafeLoader . add_constructor ( yaml . resolver . BaseResolver . DEFAULT_MAPPING_TAG , _dict_constructor ) yaml . SafeLoader . add_multi_constructor ( '!' , intrinsics_multi_constructor ) return yaml . safe_load ( template_str )
Parse the SAM template .
146
6
235,029
def get_app_metadata ( template_dict ) : if SERVERLESS_REPO_APPLICATION in template_dict . get ( METADATA , { } ) : app_metadata_dict = template_dict . get ( METADATA ) . get ( SERVERLESS_REPO_APPLICATION ) return ApplicationMetadata ( app_metadata_dict ) raise ApplicationMetadataNotFoundError ( error_message = 'missing {} section in template Metadata' . format ( SERVERLESS_REPO_APPLICATION ) )
Get the application metadata from a SAM template .
115
9
235,030
def parse_application_id ( text ) : result = re . search ( APPLICATION_ID_PATTERN , text ) return result . group ( 0 ) if result else None
Extract the application id from input text .
38
9
235,031
def make_application_private ( application_id , sar_client = None ) : if not application_id : raise ValueError ( 'Require application id to make the app private' ) if not sar_client : sar_client = boto3 . client ( 'serverlessrepo' ) sar_client . put_application_policy ( ApplicationId = application_id , Statements = [ ] )
Set the application to be private .
85
7
235,032
def share_application_with_accounts ( application_id , account_ids , sar_client = None ) : if not application_id or not account_ids : raise ValueError ( 'Require application id and list of AWS account IDs to share the app' ) if not sar_client : sar_client = boto3 . client ( 'serverlessrepo' ) application_policy = ApplicationPolicy ( account_ids , [ ApplicationPolicy . DEPLOY ] ) application_policy . validate ( ) sar_client . put_application_policy ( ApplicationId = application_id , Statements = [ application_policy . to_statement ( ) ] )
Share the application privately with given AWS account IDs .
138
10
235,033
def extract_args ( cls , * args ) : model = None crudbuilder = None for arg in args : if issubclass ( arg , models . Model ) : model = arg else : crudbuilder = arg return [ model , crudbuilder ]
Takes any arguments like a model and crud or just one of those in any order and return a model and crud .
55
26
235,034
def register ( self , * args , * * kwargs ) : assert len ( args ) <= 2 , 'register takes at most 2 args' assert len ( args ) > 0 , 'register takes at least 1 arg' model , crudbuilder = self . __class__ . extract_args ( * args ) if not issubclass ( model , models . Model ) : msg = "First argument should be Django Model" raise NotModelException ( msg ) key = self . _model_key ( model , crudbuilder ) if key in self : msg = "Key '{key}' has already been registered." . format ( key = key ) raise AlreadyRegistered ( msg ) self . __setitem__ ( key , crudbuilder ) return crudbuilder
Register a crud .
160
5
235,035
def construct_formset ( self ) : if not self . inline_model or not self . parent_model : msg = "Parent and Inline models are required in {}" . format ( self . __class__ . __name__ ) raise NotModelException ( msg ) return inlineformset_factory ( self . parent_model , self . inline_model , * * self . get_factory_kwargs ( ) )
Returns an instance of the inline formset
91
8
235,036
def get_factory_kwargs ( self ) : kwargs = { } kwargs . update ( { 'can_delete' : self . can_delete , 'extra' : self . extra , 'exclude' : self . exclude , 'fields' : self . fields , 'formfield_callback' : self . formfield_callback , 'fk_name' : self . fk_name , } ) if self . formset_class : kwargs [ 'formset' ] = self . formset_class if self . child_form : kwargs [ 'form' ] = self . child_form return kwargs
Returns the keyword arguments for calling the formset factory
141
10
235,037
def import_crud ( app ) : try : app_path = import_module ( app ) . __path__ except ( AttributeError , ImportError ) : return None try : imp . find_module ( 'crud' , app_path ) except ImportError : return None module = import_module ( "%s.crud" % app ) return module
Import crud module and register all model cruds which it contains
77
13
235,038
def get_model_class ( self ) : try : c = ContentType . objects . get ( app_label = self . app , model = self . model ) except ContentType . DoesNotExist : # try another kind of resolution # fixes a situation where a proxy model is defined in some external app. if django . VERSION >= ( 1 , 7 ) : return apps . get_model ( self . app , self . model ) else : return c . model_class ( )
Returns model class
103
3
235,039
def get_verbose_field_name ( instance , field_name ) : fields = [ field . name for field in instance . _meta . fields ] if field_name in fields : return instance . _meta . get_field ( field_name ) . verbose_name else : return field_name
Returns verbose_name for a field .
65
9
235,040
def generate_modelform ( self ) : model_class = self . get_model_class excludes = self . modelform_excludes if self . modelform_excludes else [ ] _ObjectForm = modelform_factory ( model_class , exclude = excludes ) return _ObjectForm
Generate modelform from Django modelform_factory
62
11
235,041
def get_template ( self , tname ) : if self . custom_templates and self . custom_templates . get ( tname , None ) : return self . custom_templates . get ( tname ) elif self . inlineformset : return 'crudbuilder/inline/{}.html' . format ( tname ) else : return 'crudbuilder/instance/{}.html' . format ( tname )
- Get custom template from CRUD class if it is defined in it - No custom template in CRUD class then use the default template
93
27
235,042
def generate_list_view ( self ) : name = model_class_form ( self . model + 'ListView' ) list_args = dict ( model = self . get_model_class , context_object_name = plural ( self . model ) , template_name = self . get_template ( 'list' ) , table_class = self . get_actual_table ( ) , context_table_name = 'table_objects' , crud = self . crud , permissions = self . view_permission ( 'list' ) , permission_required = self . check_permission_required , login_required = self . check_login_required , table_pagination = { 'per_page' : self . tables2_pagination or 10 } , custom_queryset = self . custom_queryset , custom_context = self . custom_context , custom_postfix_url = self . custom_postfix_url ) list_class = type ( name , ( BaseListViewMixin , SingleTableView ) , list_args ) self . classes [ name ] = list_class return list_class
Generate class based view for ListView
247
8
235,043
def generate_create_view ( self ) : name = model_class_form ( self . model + 'CreateView' ) create_args = dict ( form_class = self . get_actual_form ( 'create' ) , model = self . get_model_class , template_name = self . get_template ( 'create' ) , permissions = self . view_permission ( 'create' ) , permission_required = self . check_permission_required , login_required = self . check_login_required , inlineformset = self . inlineformset , success_url = reverse_lazy ( '{}-{}-list' . format ( self . app , self . custom_postfix_url ) ) , custom_form = self . createupdate_forms or self . custom_modelform , custom_postfix_url = self . custom_postfix_url ) parent_classes = [ self . get_createupdate_mixin ( ) , CreateView ] if self . custom_create_view_mixin : parent_classes . insert ( 0 , self . custom_create_view_mixin ) create_class = type ( name , tuple ( parent_classes ) , create_args ) self . classes [ name ] = create_class return create_class
Generate class based view for CreateView
278
8
235,044
def generate_detail_view ( self ) : name = model_class_form ( self . model + 'DetailView' ) detail_args = dict ( detailview_excludes = self . detailview_excludes , model = self . get_model_class , template_name = self . get_template ( 'detail' ) , login_required = self . check_login_required , permissions = self . view_permission ( 'detail' ) , inlineformset = self . inlineformset , permission_required = self . check_permission_required , custom_postfix_url = self . custom_postfix_url ) detail_class = type ( name , ( BaseDetailViewMixin , DetailView ) , detail_args ) self . classes [ name ] = detail_class return detail_class
Generate class based view for DetailView
176
8
235,045
def generate_update_view ( self ) : name = model_class_form ( self . model + 'UpdateView' ) update_args = dict ( form_class = self . get_actual_form ( 'update' ) , model = self . get_model_class , template_name = self . get_template ( 'update' ) , permissions = self . view_permission ( 'update' ) , permission_required = self . check_permission_required , login_required = self . check_login_required , inlineformset = self . inlineformset , custom_form = self . createupdate_forms or self . custom_modelform , success_url = reverse_lazy ( '{}-{}-list' . format ( self . app , self . custom_postfix_url ) ) , custom_postfix_url = self . custom_postfix_url ) parent_classes = [ self . get_createupdate_mixin ( ) , UpdateView ] if self . custom_update_view_mixin : parent_classes . insert ( 0 , self . custom_update_view_mixin ) update_class = type ( name , tuple ( parent_classes ) , update_args ) self . classes [ name ] = update_class return update_class
Generate class based view for UpdateView
278
8
235,046
def generate_delete_view ( self ) : name = model_class_form ( self . model + 'DeleteView' ) delete_args = dict ( model = self . get_model_class , template_name = self . get_template ( 'delete' ) , permissions = self . view_permission ( 'delete' ) , permission_required = self . check_permission_required , login_required = self . check_login_required , success_url = reverse_lazy ( '{}-{}-list' . format ( self . app , self . custom_postfix_url ) ) , custom_postfix_url = self . custom_postfix_url ) delete_class = type ( name , ( CrudBuilderMixin , DeleteView ) , delete_args ) self . classes [ name ] = delete_class return delete_class
Generate class based view for DeleteView
186
8
235,047
def incoming_references ( self , client = None , query = { } ) : if client is None : return False query . update ( { 'links_to_entry' : self . id } ) return client . entries ( query )
Fetches all entries referencing the entry
50
8
235,048
def build ( self ) : if self . json [ 'sys' ] [ 'type' ] == 'Array' : if any ( k in self . json for k in [ 'nextSyncUrl' , 'nextPageUrl' ] ) : return SyncPage ( self . json , default_locale = self . default_locale , localized = True ) return self . _build_array ( ) return self . _build_single ( )
Creates the objects from the JSON response
93
8
235,049
def get ( cls , content_type_id ) : for content_type in cls . __CACHE__ : if content_type . sys . get ( 'id' ) == content_type_id : return content_type return None
Fetches a Content Type from the Cache .
53
10
235,050
def get_error ( response ) : errors = { 400 : BadRequestError , 401 : UnauthorizedError , 403 : AccessDeniedError , 404 : NotFoundError , 429 : RateLimitExceededError , 500 : ServerError , 502 : BadGatewayError , 503 : ServiceUnavailableError } error_class = HTTPError if response . status_code in errors : error_class = errors [ response . status_code ] return error_class ( response )
Gets Error by HTTP Status Code
98
7
235,051
def field_for ( self , field_id ) : for field in self . fields : if field . id == field_id : return field return None
Fetches the field for the given Field ID .
32
11
235,052
def coerce ( self , value , * * kwargs ) : Location = namedtuple ( 'Location' , [ 'lat' , 'lon' ] ) return Location ( float ( value . get ( 'lat' ) ) , float ( value . get ( 'lon' ) ) )
Coerces value to Location object
62
7
235,053
def coerce ( self , value , * * kwargs ) : result = [ ] for v in value : result . append ( self . _coercion . coerce ( v , * * kwargs ) ) return result
Coerces array items with proper coercion .
49
9
235,054
def coerce ( self , value , includes = None , errors = None , resources = None , default_locale = 'en-US' , locale = None ) : if includes is None : includes = [ ] if errors is None : errors = [ ] return self . _coerce_block ( value , includes = includes , errors = errors , resources = resources , default_locale = default_locale , locale = locale )
Coerces Rich Text properly .
92
7
235,055
def coerce ( self , value , * * kwargs ) : if value is None : return None return self . _coercion . coerce ( value , * * kwargs )
Coerces the value to the proper type .
41
10
235,056
def content_type ( self , content_type_id , query = None ) : return self . _get ( self . environment_url ( '/content_types/{0}' . format ( content_type_id ) ) , query )
Fetches a Content Type by ID .
52
9
235,057
def entry ( self , entry_id , query = None ) : if query is None : query = { } self . _normalize_select ( query ) try : query . update ( { 'sys.id' : entry_id } ) return self . _get ( self . environment_url ( '/entries' ) , query ) [ 0 ] except IndexError : raise EntryNotFoundError ( "Entry not found for ID: '{0}'" . format ( entry_id ) )
Fetches an Entry by ID .
104
8
235,058
def asset ( self , asset_id , query = None ) : return self . _get ( self . environment_url ( '/assets/{0}' . format ( asset_id ) ) , query )
Fetches an Asset by ID .
44
8
235,059
def sync ( self , query = None ) : if query is None : query = { } self . _normalize_sync ( query ) return self . _get ( self . environment_url ( '/sync' ) , query )
Fetches content from the Sync API .
48
9
235,060
def _request_headers ( self ) : headers = { 'X-Contentful-User-Agent' : self . _contentful_user_agent ( ) , 'Content-Type' : 'application/vnd.contentful.delivery.v{0}+json' . format ( # noqa: E501 self . api_version ) } if self . authorization_as_header : headers [ 'Authorization' ] = 'Bearer {0}' . format ( self . access_token ) headers [ 'Accept-Encoding' ] = 'gzip' if self . gzip_encoded else 'identity' return headers
Sets the default Request Headers .
138
8
235,061
def _url ( self , url ) : protocol = 'https' if self . https else 'http' return '{0}://{1}/spaces/{2}{3}' . format ( protocol , self . api_url , self . space_id , url )
Creates the Request URL .
60
6
235,062
def _normalize_query ( self , query ) : for k , v in query . items ( ) : if isinstance ( v , list ) : query [ k ] = ',' . join ( [ str ( e ) for e in v ] )
Converts Arrays in the query to comma separaters lists for proper API handling .
53
17
235,063
def _http_get ( self , url , query ) : if not self . authorization_as_header : query . update ( { 'access_token' : self . access_token } ) response = None self . _normalize_query ( query ) kwargs = { 'params' : query , 'headers' : self . _request_headers ( ) } if self . _has_proxy ( ) : kwargs [ 'proxies' ] = self . _proxy_parameters ( ) response = requests . get ( self . _url ( url ) , * * kwargs ) if response . status_code == 429 : raise RateLimitExceededError ( response ) return response
Performs the HTTP GET Request .
149
7
235,064
def _get ( self , url , query = None ) : if query is None : query = { } response = retry_request ( self ) ( self . _http_get ) ( url , query = query ) if self . raw_mode : return response if response . status_code != 200 : error = get_error ( response ) if self . raise_errors : raise error return error localized = query . get ( 'locale' , '' ) == '*' return ResourceBuilder ( self . default_locale , localized , response . json ( ) , max_depth = self . max_include_resolution_depth , reuse_entries = self . reuse_entries ) . build ( )
Wrapper for the HTTP Request Rate Limit Backoff is handled here Responses are Processed with ResourceBuilder .
149
22
235,065
def _proxy_parameters ( self ) : proxy_protocol = '' if self . proxy_host . startswith ( 'https' ) : proxy_protocol = 'https' else : proxy_protocol = 'http' proxy = '{0}://' . format ( proxy_protocol ) if self . proxy_username and self . proxy_password : proxy += '{0}:{1}@' . format ( self . proxy_username , self . proxy_password ) proxy += sub ( r'https?(://)?' , '' , self . proxy_host ) if self . proxy_port : proxy += ':{0}' . format ( self . proxy_port ) return { 'http' : proxy , 'https' : proxy }
Builds Proxy parameters Dict from client options .
163
10
235,066
def url ( self , * * kwargs ) : url = self . file [ 'url' ] args = [ '{0}={1}' . format ( k , v ) for k , v in kwargs . items ( ) ] if args : url += '?{0}' . format ( '&' . join ( args ) ) return url
Returns a formatted URL for the Asset s File with serialized parameters .
78
14
235,067
def fields ( self , locale = None ) : if locale is None : locale = self . _locale ( ) return self . _fields . get ( locale , { } )
Get fields for a specific locale
37
6
235,068
def resolve ( self , client ) : resolve_method = getattr ( client , snake_case ( self . link_type ) ) if self . link_type == 'Space' : return resolve_method ( ) else : return resolve_method ( self . id )
Resolves Link to a specific Resource
56
7
235,069
def snake_case ( a_string ) : partial = re . sub ( '(.)([A-Z][a-z]+)' , r'\1_\2' , a_string ) return re . sub ( '([a-z0-9])([A-Z])' , r'\1_\2' , partial ) . lower ( )
Returns a snake cased version of a string .
80
10
235,070
def is_link_array ( value ) : if isinstance ( value , list ) and len ( value ) > 0 : return is_link ( value [ 0 ] ) return False
Checks if value is an array of links .
38
10
235,071
def resource_for_link ( link , includes , resources = None , locale = None ) : if resources is not None : cache_key = "{0}:{1}:{2}" . format ( link [ 'sys' ] [ 'linkType' ] , link [ 'sys' ] [ 'id' ] , locale ) if cache_key in resources : return resources [ cache_key ] for i in includes : if ( i [ 'sys' ] [ 'id' ] == link [ 'sys' ] [ 'id' ] and i [ 'sys' ] [ 'type' ] == link [ 'sys' ] [ 'linkType' ] ) : return i return None
Returns the resource that matches the link
144
7
235,072
def all_resource_urls ( query ) : urls = [ ] next = True while next : response = requests . get ( query ) json_data = json . loads ( response . content ) for resource in json_data [ 'results' ] : urls . append ( resource [ 'url' ] ) if bool ( json_data [ 'next' ] ) : query = json_data [ 'next' ] else : next = False return urls
Get all the URLs for every resource
97
7
235,073
def get_all ( resource ) : QUERYSETS = { settings . PEOPLE : PeopleQuerySet , settings . PLANETS : PlanetQuerySet , settings . STARSHIPS : StarshipQuerySet , settings . VEHICLES : VehicleQuerySet , settings . SPECIES : SpeciesQuerySet , settings . FILMS : FilmQuerySet } urls = all_resource_urls ( "{0}/{1}/" . format ( settings . BASE_URL , resource ) ) return QUERYSETS [ resource ] ( urls )
Return all of a single resource
112
6
235,074
def get_planet ( planet_id ) : result = _get ( planet_id , settings . PLANETS ) return Planet ( result . content )
Return a single planet
31
4
235,075
def get_starship ( starship_id ) : result = _get ( starship_id , settings . STARSHIPS ) return Starship ( result . content )
Return a single starship
33
4
235,076
def get_vehicle ( vehicle_id ) : result = _get ( vehicle_id , settings . VEHICLES ) return Vehicle ( result . content )
Return a single vehicle
34
4
235,077
def get_species ( species_id ) : result = _get ( species_id , settings . SPECIES ) return Species ( result . content )
Return a single species
31
4
235,078
def get_film ( film_id ) : result = _get ( film_id , settings . FILMS ) return Film ( result . content )
Return a single film
31
4
235,079
def order_by ( self , order_attribute ) : to_return = [ ] for f in sorted ( self . items , key = lambda i : getattr ( i , order_attribute ) ) : to_return . append ( f ) return to_return
Return the list of items in a certain order
55
9
235,080
def print_crawl ( self ) : print ( "Star Wars" ) time . sleep ( .5 ) print ( "Episode {0}" . format ( self . episode_id ) ) time . sleep ( .5 ) print ( "" ) time . sleep ( .5 ) print ( "{0}" . format ( self . title ) ) for line in self . gen_opening_crawl ( ) : time . sleep ( .5 ) print ( line )
Print the opening crawl one line at a time
96
9
235,081
def is_str ( string ) : if sys . version_info [ : 2 ] >= ( 3 , 0 ) : return isinstance ( string , str ) return isinstance ( string , basestring )
Python 2 and 3 compatible string checker .
43
9
235,082
def _create_logger_ ( name ) : logger = logging . getLogger ( name ) handler = logging . StreamHandler ( ) handler . setFormatter ( logging . Formatter ( '%(levelname)s %(message)s' ) ) logger . addHandler ( handler ) logger . setLevel ( logging . INFO ) return logger
Implementation detail creates a logger .
73
7
235,083
def remove_file_no_raise ( file_name , config ) : # The removal can be disabled by the config for debugging purposes. if config . keep_xml : return True try : if os . path . exists ( file_name ) : os . remove ( file_name ) except IOError as error : loggers . root . error ( "Error occurred while removing temporary created file('%s'): %s" , file_name , str ( error ) )
Removes file from disk if exception is raised .
99
10
235,084
def create_temp_file_name ( suffix , prefix = None , dir = None , directory = None ) : if dir is not None : warnings . warn ( "The dir argument is deprecated.\n" + "Please use the directory argument instead." , DeprecationWarning ) # Deprecated since 1.9.0, will be removed in 2.0.0 directory = dir if not prefix : prefix = tempfile . gettempprefix ( ) fd , name = tempfile . mkstemp ( suffix = suffix , prefix = prefix , dir = directory ) file_obj = os . fdopen ( fd ) file_obj . close ( ) return name
Small convenience function that creates temporary files .
143
8
235,085
def contains_parent_dir ( fpath , dirs ) : # Note: this function is used nowhere in pygccxml but is used # at least by pypluplus; so it should stay here. return bool ( [ x for x in dirs if _f ( fpath , x ) ] )
Returns true if paths in dirs start with fpath .
66
12
235,086
def create_decl_string ( return_type , arguments_types , with_defaults = True ) : return free_function_type_t . NAME_TEMPLATE % { 'return_type' : return_type . build_decl_string ( with_defaults ) , 'arguments' : ',' . join ( [ _f ( x , with_defaults ) for x in arguments_types ] ) }
Returns free function type
92
4
235,087
def create_typedef ( self , typedef_name , unused = None , with_defaults = True ) : return free_function_type_t . TYPEDEF_NAME_TEMPLATE % { 'typedef_name' : typedef_name , 'return_type' : self . return_type . build_decl_string ( with_defaults ) , 'arguments' : ',' . join ( [ _f ( x , with_defaults ) for x in self . arguments_types ] ) }
returns string that contains valid C ++ code that defines typedef to function type
117
16
235,088
def create_typedef ( self , typedef_name , class_alias = None , with_defaults = True ) : has_const_str = '' if self . has_const : has_const_str = 'const' if None is class_alias : if with_defaults : class_alias = self . class_inst . decl_string else : class_alias = self . class_inst . partial_decl_string return member_function_type_t . TYPEDEF_NAME_TEMPLATE % { 'typedef_name' : typedef_name , 'return_type' : self . return_type . build_decl_string ( with_defaults ) , 'class' : class_alias , 'arguments' : ',' . join ( [ _f ( x , with_defaults ) for x in self . arguments_types ] ) , 'has_const' : has_const_str }
creates typedef to the function type
205
8
235,089
def parse ( files , config = None , compilation_mode = COMPILATION_MODE . FILE_BY_FILE , cache = None ) : if not config : config = xml_generator_configuration_t ( ) parser = project_reader_t ( config = config , cache = cache ) declarations = parser . read_files ( files , compilation_mode ) config . xml_generator_from_xml_file = parser . xml_generator_from_xml_file return declarations
Parse header files .
104
5
235,090
def remove_alias ( type_ ) : if isinstance ( type_ , cpptypes . type_t ) : type_ref = type_ elif isinstance ( type_ , typedef . typedef_t ) : type_ref = type_ . decl_type else : # Not a valid input, just return it return type_ if type_ref . cache . remove_alias : return type_ref . cache . remove_alias no_alias = __remove_alias ( type_ref . clone ( ) ) type_ref . cache . remove_alias = no_alias return no_alias
Returns type_t without typedef
127
7
235,091
def is_pointer ( type_ ) : return does_match_definition ( type_ , cpptypes . pointer_t , ( cpptypes . const_t , cpptypes . volatile_t ) ) or does_match_definition ( type_ , cpptypes . pointer_t , ( cpptypes . volatile_t , cpptypes . const_t ) )
returns True if type represents C ++ pointer type False otherwise
81
12
235,092
def remove_pointer ( type_ ) : nake_type = remove_alias ( type_ ) if not is_pointer ( nake_type ) : return type_ elif isinstance ( nake_type , cpptypes . volatile_t ) and isinstance ( nake_type . base , cpptypes . pointer_t ) : return cpptypes . volatile_t ( nake_type . base . base ) elif isinstance ( nake_type , cpptypes . const_t ) and isinstance ( nake_type . base , cpptypes . pointer_t ) : return cpptypes . const_t ( nake_type . base . base ) elif isinstance ( nake_type , cpptypes . volatile_t ) and isinstance ( nake_type . base , cpptypes . const_t ) and isinstance ( nake_type . base . base , cpptypes . pointer_t ) : return ( cpptypes . volatile_t ( cpptypes . const_t ( nake_type . base . base . base ) ) ) return nake_type . base
removes pointer from the type definition
245
7
235,093
def is_array ( type_ ) : nake_type = remove_alias ( type_ ) nake_type = remove_reference ( nake_type ) nake_type = remove_cv ( nake_type ) return isinstance ( nake_type , cpptypes . array_t )
returns True if type represents C ++ array type False otherwise
66
12
235,094
def array_size ( type_ ) : nake_type = remove_alias ( type_ ) nake_type = remove_reference ( nake_type ) nake_type = remove_cv ( nake_type ) assert isinstance ( nake_type , cpptypes . array_t ) return nake_type . size
returns array size
73
4
235,095
def array_item_type ( type_ ) : if is_array ( type_ ) : type_ = remove_alias ( type_ ) type_ = remove_cv ( type_ ) return type_ . base elif is_pointer ( type_ ) : return remove_pointer ( type_ ) else : raise RuntimeError ( "array_item_type functions takes as argument array or pointer " + "types" )
returns array item type
88
5
235,096
def remove_reference ( type_ ) : nake_type = remove_alias ( type_ ) if not is_reference ( nake_type ) : return type_ return nake_type . base
removes reference from the type definition
43
7
235,097
def remove_const ( type_ ) : nake_type = remove_alias ( type_ ) if not is_const ( nake_type ) : return type_ else : # Handling for const and volatile qualified types. There is a # difference in behavior between GCCXML and CastXML for cv-qual arrays. # GCCXML produces the following nesting of types: # -> volatile_t(const_t(array_t)) # while CastXML produces the following nesting: # -> array_t(volatile_t(const_t)) # For both cases, we must unwrap the types, remove const_t, and add # back the outer layers if isinstance ( nake_type , cpptypes . array_t ) : is_v = is_volatile ( nake_type ) if is_v : result_type = nake_type . base . base . base else : result_type = nake_type . base . base if is_v : result_type = cpptypes . volatile_t ( result_type ) return cpptypes . array_t ( result_type , nake_type . size ) elif isinstance ( nake_type , cpptypes . volatile_t ) : return cpptypes . volatile_t ( nake_type . base . base ) return nake_type . base
removes const from the type definition
293
7
235,098
def is_same ( type1 , type2 ) : nake_type1 = remove_declarated ( type1 ) nake_type2 = remove_declarated ( type2 ) return nake_type1 == nake_type2
returns True if type1 and type2 are same types
54
12
235,099
def is_elaborated ( type_ ) : nake_type = remove_alias ( type_ ) if isinstance ( nake_type , cpptypes . elaborated_t ) : return True elif isinstance ( nake_type , cpptypes . reference_t ) : return is_elaborated ( nake_type . base ) elif isinstance ( nake_type , cpptypes . pointer_t ) : return is_elaborated ( nake_type . base ) elif isinstance ( nake_type , cpptypes . volatile_t ) : return is_elaborated ( nake_type . base ) elif isinstance ( nake_type , cpptypes . const_t ) : return is_elaborated ( nake_type . base ) return False
returns True if type represents C ++ elaborated type False otherwise
177
12