idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
235,900 | def _detect_anomalies ( self ) : anom_scores = self . anom_scores max_anom_score = anom_scores . max ( ) anomalies = [ ] if max_anom_score : threshold = self . threshold or max_anom_score * self . score_percent_threshold intervals = [ ] start , end = None , None for timestamp , value in anom_scores . iteritems ( ) : if... | Detect anomalies using a threshold on anomaly scores . |
235,901 | def handle_response ( response ) : if response . status_code < 400 : return cls = _status_to_exception_type . get ( response . status_code , HttpError ) kwargs = { 'code' : response . status_code , 'method' : response . request . method , 'url' : response . request . url , 'details' : response . text , } if response . ... | Given a requests . Response object throw the appropriate exception if applicable . |
235,902 | def create ( self , data , ** kwargs ) : self . client . post ( self . url , data = data ) | Create classifitions for specific entity |
235,903 | def create ( self , ** kwargs ) : raise exceptions . MethodNotImplemented ( method = self . create , url = self . url , details = 'GUID cannot be duplicated, to create a new GUID use the relationship resource' ) | Raise error since guid cannot be duplicated |
235,904 | def normalize_underscore_case ( name ) : normalized = name . lower ( ) normalized = re . sub ( r'_(\w)' , lambda match : ' ' + match . group ( 1 ) . upper ( ) , normalized ) return normalized [ 0 ] . upper ( ) + normalized [ 1 : ] | Normalize an underscore - separated descriptor to something more readable . |
235,905 | def normalize_camel_case ( name ) : normalized = re . sub ( '([a-z])([A-Z])' , lambda match : ' ' . join ( [ match . group ( 1 ) , match . group ( 2 ) ] ) , name ) return normalized [ 0 ] . upper ( ) + normalized [ 1 : ] | Normalize a camelCase descriptor to something more readable . |
235,906 | def version_tuple ( version ) : if isinstance ( version , str ) : return tuple ( int ( x ) for x in version . split ( '.' ) ) elif isinstance ( version , tuple ) : return version else : raise ValueError ( "Invalid version: %s" % version ) | Convert a version string or tuple to a tuple . |
235,907 | def version_str ( version ) : if isinstance ( version , str ) : return version elif isinstance ( version , tuple ) : return '.' . join ( [ str ( int ( x ) ) for x in version ] ) else : raise ValueError ( "Invalid version: %s" % version ) | Convert a version tuple or string to a string . |
235,908 | def generate_http_basic_token ( username , password ) : token = base64 . b64encode ( '{}:{}' . format ( username , password ) . encode ( 'utf-8' ) ) . decode ( 'utf-8' ) return token | Generates a HTTP basic token from username and password |
235,909 | def identifier ( self ) : if self . primary_key not in self . _data : return 'Unknown' return str ( self . _data [ self . primary_key ] ) | These models have server - generated identifiers . |
235,910 | def url ( self ) : if self . parent is None : pieces = [ self . client . base_url , 'api' , 'atlas' , 'v2' ] else : pieces = [ self . parent . url ] pieces . append ( self . model_class . path ) return '/' . join ( pieces ) | The url for this collection . |
235,911 | def inflate ( self ) : if not self . _is_inflated : self . check_version ( ) for k , v in self . _filter . items ( ) : if '[' in v : self . _filter [ k ] = ast . literal_eval ( v ) self . load ( self . client . get ( self . url , params = self . _filter ) ) self . _is_inflated = True return self | Load the collection from the server if necessary . |
235,912 | def load ( self , response ) : self . _models = [ ] if isinstance ( response , dict ) : for key in response . keys ( ) : model = self . model_class ( self , href = '' ) model . load ( response [ key ] ) self . _models . append ( model ) else : for item in response : model = self . model_class ( self , href = item . get... | Parse the GET response for the collection . |
235,913 | def create ( self , * args , ** kwargs ) : href = self . url if len ( args ) == 1 : kwargs [ self . model_class . primary_key ] = args [ 0 ] href = '/' . join ( [ href , args [ 0 ] ] ) model = self . model_class ( self , href = href . replace ( 'classifications/' , 'classification/' ) , data = kwargs ) model . create (... | Add a resource to this collection . |
235,914 | def update ( self , ** kwargs ) : self . inflate ( ) for model in self . _models : model . update ( ** kwargs ) return self | Update all resources in this collection . |
235,915 | def delete ( self , ** kwargs ) : self . inflate ( ) for model in self . _models : model . delete ( ** kwargs ) return | Delete all resources in this collection . |
235,916 | def wait ( self , ** kwargs ) : if self . request : self . request . wait ( ** kwargs ) self . request = None return self . inflate ( ) | Wait until any pending asynchronous requests are finished for this collection . |
235,917 | def url ( self ) : if self . _href is not None : return self . _href if self . identifier : path = '/' . join ( [ self . parent . url . replace ( 'classifications/' , 'classficiation/' ) , self . identifier ] ) return path raise exceptions . ClientError ( "Not able to determine object URL" ) | Gets the url for the resource this model represents . |
235,918 | def inflate ( self ) : if not self . _is_inflated : if self . _is_inflating : msg = ( "There is not enough data to inflate this object. " "Need either an href: {} or a {}: {}" ) msg = msg . format ( self . _href , self . primary_key , self . _data . get ( self . primary_key ) ) raise exceptions . ClientError ( msg ) s... | Load the resource from the server if not already loaded . |
235,919 | def load ( self , response ) : if 'href' in response : self . _href = response . pop ( 'href' ) if self . data_key and self . data_key in response : self . _data . update ( response . pop ( self . data_key ) ) for rel in [ x for x in self . relationships if x in response and response [ x ] ] : rel_class = self . relati... | The load method parses the raw JSON response from the server . |
235,920 | def delete ( self , ** kwargs ) : self . method = 'delete' if len ( kwargs ) > 0 : self . load ( self . client . delete ( self . url , params = kwargs ) ) else : self . load ( self . client . delete ( self . url ) ) self . parent . remove ( self ) return | Delete a resource by issuing a DELETE http request against it . |
235,921 | def publish ( obj , event , event_state , ** kwargs ) : if len ( EVENT_HANDLERS ) == 0 : return if inspect . isclass ( obj ) : pub_cls = obj else : pub_cls = obj . __class__ potential = [ x . __name__ for x in inspect . getmro ( pub_cls ) ] fallbacks = None callbacks = [ ] for cls in potential : event_key = '.' . join ... | Publish an event from an object . |
235,922 | def subscribe ( obj , event , callback , event_state = None ) : if inspect . isclass ( obj ) : cls = obj . __name__ else : cls = obj . __class__ . __name__ if event_state is None : event_state = states . ANY event_key = '.' . join ( [ cls , event , event_state ] ) if event_key not in EVENT_HANDLERS : EVENT_HANDLERS [ e... | Subscribe an event from an class . |
235,923 | def clean_name ( self , suffix = True , prefix = False , middle = False , multi = False ) : "return cleared version of the business name" name = self . business_name name = self . string_stripper ( name ) loname = name . lower ( ) for item in suffix_sort : if suffix : if loname . endswith ( " " + item ) : start = lonam... | return cleared version of the business name |
235,924 | def _add_nodes ( self ) : for n , atom in enumerate ( self . ast . select ( 'atom' ) ) : self . add_node ( n , atom = atom ) self . _atom_indices [ id ( atom ) ] = n | Add all atoms in the SMARTS string as nodes in the graph . |
235,925 | def _add_edges ( self , ast_node , trunk = None ) : atom_indices = self . _atom_indices for atom in ast_node . tail : if atom . head == 'atom' : atom_idx = atom_indices [ id ( atom ) ] if atom . is_first_kid and atom . parent ( ) . head == 'branch' : trunk_idx = atom_indices [ id ( trunk ) ] self . add_edge ( atom_idx ... | Add all bonds in the SMARTS string as edges in the graph . |
235,926 | def _add_label_edges ( self ) : labels = self . ast . select ( 'atom_label' ) if not labels : return label_digits = defaultdict ( list ) for label in labels : digits = list ( label . tail [ 0 ] ) for digit in digits : label_digits [ digit ] . append ( label . parent ( ) ) for label , ( atom1 , atom2 ) in label_digits .... | Add edges between all atoms with the same atom_label in rings . |
235,927 | def find_matches ( self , topology ) : ring_tokens = [ 'ring_size' , 'ring_count' ] has_ring_rules = any ( self . ast . select ( token ) for token in ring_tokens ) _prepare_atoms ( topology , compute_cycles = has_ring_rules ) top_graph = nx . Graph ( ) top_graph . add_nodes_from ( ( ( a . index , { 'atom' : a } ) for a... | Return sets of atoms that match this SMARTS pattern in a topology . |
235,928 | def candidate_pairs_iter ( self ) : G2_nodes = self . G2_nodes T1_inout = set ( self . inout_1 . keys ( ) ) - set ( self . core_1 . keys ( ) ) T2_inout = set ( self . inout_2 . keys ( ) ) - set ( self . core_2 . keys ( ) ) if T1_inout and T2_inout : for node in T1_inout : yield node , min ( T2_inout ) else : other_node... | Iterator over candidate pairs of nodes in G1 and G2 . |
235,929 | def find_atomtypes ( topology , forcefield , max_iter = 10 ) : rules = _load_rules ( forcefield ) subrules = dict ( ) system_elements = { a . element . symbol for a in topology . atoms ( ) } for key , val in rules . items ( ) : atom = val . node [ 0 ] [ 'atom' ] if len ( atom . select ( 'atom_symbol' ) ) == 1 and not a... | Determine atomtypes for all atoms . |
235,930 | def _load_rules ( forcefield ) : rules = dict ( ) for rule_name , smarts in forcefield . atomTypeDefinitions . items ( ) : overrides = forcefield . atomTypeOverrides . get ( rule_name ) if overrides is not None : overrides = set ( overrides ) else : overrides = set ( ) rules [ rule_name ] = SMARTSGraph ( smarts_string ... | Load atomtyping rules from a forcefield into SMARTSGraphs . |
235,931 | def _iterate_rules ( rules , topology , max_iter ) : atoms = list ( topology . atoms ( ) ) for _ in range ( max_iter ) : max_iter -= 1 found_something = False for rule in rules . values ( ) : for match_index in rule . find_matches ( topology ) : atom = atoms [ match_index ] if rule . name not in atom . whitelist : atom... | Iteratively run all the rules until the white - and backlists converge . |
235,932 | def _resolve_atomtypes ( topology ) : for atom in topology . atoms ( ) : atomtype = [ rule_name for rule_name in atom . whitelist - atom . blacklist ] if len ( atomtype ) == 1 : atom . id = atomtype [ 0 ] elif len ( atomtype ) > 1 : raise FoyerError ( "Found multiple types for atom {} ({}): {}." . format ( atom . index... | Determine the final atomtypes from the white - and blacklists . |
235,933 | def generate_topology ( non_omm_topology , non_element_types = None , residues = None ) : if non_element_types is None : non_element_types = set ( ) if isinstance ( non_omm_topology , pmd . Structure ) : return _topology_from_parmed ( non_omm_topology , non_element_types ) elif has_mbuild : mb = import_ ( 'mbuild' ) if... | Create an OpenMM Topology from another supported topology structure . |
235,934 | def _topology_from_parmed ( structure , non_element_types ) : topology = app . Topology ( ) residues = dict ( ) for pmd_residue in structure . residues : chain = topology . addChain ( ) omm_residue = topology . addResidue ( pmd_residue . name , chain ) residues [ pmd_residue ] = omm_residue atoms = dict ( ) for pmd_ato... | Convert a ParmEd Structure to an OpenMM Topology . |
235,935 | def _topology_from_residue ( res ) : topology = app . Topology ( ) chain = topology . addChain ( ) new_res = topology . addResidue ( res . name , chain ) atoms = dict ( ) for res_atom in res . atoms ( ) : topology_atom = topology . addAtom ( name = res_atom . name , element = res_atom . element , residue = new_res ) at... | Converts a openmm . app . Topology . Residue to openmm . app . Topology . |
235,936 | def _check_independent_residues ( topology ) : for res in topology . residues ( ) : atoms_in_residue = set ( [ atom for atom in res . atoms ( ) ] ) bond_partners_in_residue = [ item for sublist in [ atom . bond_partners for atom in res . atoms ( ) ] for item in sublist ] if not bond_partners_in_residue : continue if se... | Check to see if residues will constitute independent graphs . |
235,937 | def _update_atomtypes ( unatomtyped_topology , res_name , prototype ) : for res in unatomtyped_topology . residues ( ) : if res . name == res_name : for old_atom , new_atom_id in zip ( [ atom for atom in res . atoms ( ) ] , [ atom . id for atom in prototype . atoms ( ) ] ) : old_atom . id = new_atom_id | Update atomtypes in residues in a topology using a prototype topology . |
235,938 | def registerAtomType ( self , parameters ) : name = parameters [ 'name' ] if name in self . _atomTypes : raise ValueError ( 'Found multiple definitions for atom type: ' + name ) atom_class = parameters [ 'class' ] mass = _convertParameterToNumber ( parameters [ 'mass' ] ) element = None if 'element' in parameters : ele... | Register a new atom type . |
235,939 | def run_atomtyping ( self , topology , use_residue_map = True ) : if use_residue_map : independent_residues = _check_independent_residues ( topology ) if independent_residues : residue_map = dict ( ) for res in topology . residues ( ) : if res . name not in residue_map . keys ( ) : residue = _topology_from_residue ( re... | Atomtype the topology |
235,940 | def cd ( directory ) : old_dir = os . getcwd ( ) try : os . chdir ( directory ) yield finally : os . chdir ( old_dir ) | Change the current working directory temporarily . |
235,941 | def mkdtemp ( hint = '' ) : dirname = tempfile . mkdtemp ( prefix = 'check-manifest-' , suffix = hint ) try : yield dirname finally : rmtree ( dirname ) | Create a temporary directory then clean it up . |
235,942 | def chmod_plus ( path , add_bits = stat . S_IWUSR ) : try : os . chmod ( path , stat . S_IMODE ( os . stat ( path ) . st_mode ) | add_bits ) except OSError : pass | Change a file s mode by adding a few bits . |
235,943 | def rmtree ( path ) : def onerror ( func , path , exc_info ) : if func is os . remove or func is os . unlink or func is os . rmdir : if sys . platform != 'win32' : chmod_plus ( os . path . dirname ( path ) , stat . S_IWUSR | stat . S_IXUSR ) chmod_plus ( path ) func ( path ) else : raise shutil . rmtree ( path , onerro... | A version of rmtree that can deal with read - only files and directories . |
235,944 | def copy_files ( filelist , destdir ) : for filename in filelist : destfile = os . path . join ( destdir , filename ) assert destfile . startswith ( destdir + os . path . sep ) destfiledir = os . path . dirname ( destfile ) if not os . path . isdir ( destfiledir ) : os . makedirs ( destfiledir ) if os . path . isdir ( ... | Copy a list of files to destdir preserving directory structure . |
235,945 | def get_one_file_in ( dirname ) : files = os . listdir ( dirname ) if len ( files ) > 1 : raise Failure ( 'More than one file exists in %s:\n%s' % ( dirname , '\n' . join ( sorted ( files ) ) ) ) elif not files : raise Failure ( 'No files found in %s' % dirname ) return os . path . join ( dirname , files [ 0 ] ) | Return the pathname of the one file in a directory . |
235,946 | def unicodify ( filename ) : if isinstance ( filename , bytes ) : return filename . decode ( locale . getpreferredencoding ( ) ) else : return filename | Make sure filename is Unicode . |
235,947 | 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_fil... | Return the list of files in an archive . |
235,948 | 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... | Strip toplevel name from a file list . |
235,949 | 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)" ) loc... | Detect the version control system used for the current directory . |
235,950 | def normalize_name ( name ) : name = os . path . normpath ( name ) name = unicodify ( name ) if sys . platform == 'darwin' : name = unicodedata . normalize ( 'NFC' , name ) return name | Some VCS print directory names with trailing slashes . Strip them . |
235,951 | def read_config ( ) : 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_IGNO... | Read configuration from file if possible . |
235,952 | 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 ( ... | Searches for config files reads them and returns a dictionary |
235,953 | def read_manifest ( ) : 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 . |
235,954 | 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? |
235,955 | 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? |
235,956 | 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 . |
235,957 | def find_suggestions ( filelist ) : suggestions = set ( ) unknowns = [ ] for filename in filelist : if os . path . isdir ( filename ) : continue for pattern , suggestion in SUGGESTIONS : m = pattern . match ( filename ) if m is not None : suggestions . add ( pattern . sub ( suggestion , filename ) ) break else : unknow... | Suggest MANIFEST . in patterns for missing files . |
235,958 | 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 . |
235,959 | def zest_releaser_check ( data ) : from zest . releaser . utils import ask source_tree = data [ 'workingdir' ] if not is_package ( source_tree ) : 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 ... | Check the completeness of MANIFEST . in before the release . |
235,960 | 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 . |
235,961 | 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 . |
235,962 | 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 . |
235,963 | 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 if status . get ( 'item' ) in ( 'unversioned' , 'external' )... | Is this entry interesting? |
235,964 | 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 ) : ... | Check if the formats of principals and actions are valid . |
235,965 | 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 ) strip... | Create a new application or new application version in SAR . |
235,966 | 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_dic... | Update the application metadata . |
235,967 | 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 . |
235,968 | 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... | Construct the request body to create application . |
235,969 | 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 } r... | Construct the request body to update application . |
235,970 | 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 } re... | Construct the request body to create application version . |
235,971 | 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 S3Permission... | Wrap botocore ClientError exception into ServerlessRepoClientError . |
235,972 | 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 . LABEL... | Get the changed application details after publishing . |
235,973 | 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 . |
235,974 | 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 . |
235,975 | def parse_template ( template_str ) : try : 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_const... | Parse the SAM template . |
235,976 | 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 = 'missin... | Get the application metadata from a SAM template . |
235,977 | 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 . |
235,978 | 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 . |
235,979 | 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 = Appli... | Share the application privately with given AWS account IDs . |
235,980 | 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 . |
235,981 | 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" ... | Register a crud . |
235,982 | 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 |
235,983 | 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... | Returns the keyword arguments for calling the formset factory |
235,984 | 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 |
235,985 | def get_model_class ( self ) : try : c = ContentType . objects . get ( app_label = self . app , model = self . model ) except ContentType . DoesNotExist : if django . VERSION >= ( 1 , 7 ) : return apps . get_model ( self . app , self . model ) else : return c . model_class ( ) | Returns model class |
235,986 | 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 . |
235,987 | 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 |
235,988 | 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 |
235,989 | 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' , ... | Generate class based view for ListView |
235,990 | 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 ... | Generate class based view for CreateView |
235,991 | 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... | Generate class based view for DetailView |
235,992 | 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 ... | Generate class based view for UpdateView |
235,993 | 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... | Generate class based view for DeleteView |
235,994 | 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 |
235,995 | 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 |
235,996 | 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 . |
235,997 | 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 =... | Gets Error by HTTP Status Code |
235,998 | 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 . |
235,999 | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.