idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
13,700 | async def wait_tasks ( tasks , flatten = True ) : rets = await asyncio . gather ( * tasks ) if flatten and all ( map ( lambda x : hasattr ( x , '__iter__' ) , rets ) ) : rets = list ( itertools . chain ( * rets ) ) return rets | Gather a list of asynchronous tasks and wait their completion . | 75 | 12 |
13,701 | def split_addrs ( addrs ) : splitted = { } for addr in addrs : host , port , _ = _addr_key ( addr ) if host not in splitted : splitted [ host ] = { } if port not in splitted [ host ] : splitted [ host ] [ port ] = [ ] splitted [ host ] [ port ] . append ( addr ) return splitted | Split addresses into dictionaries by hosts and ports . | 86 | 10 |
13,702 | def addrs2managers ( addrs ) : mgrs = { } for addr in addrs : mgr_addr = get_manager ( addr ) if mgr_addr not in mgrs : mgrs [ mgr_addr ] = [ ] mgrs [ mgr_addr ] . append ( addr ) return mgrs | Map agent addresses to their assumed managers . | 75 | 8 |
13,703 | def create_jinja_env ( template_path ) : jinja_env = jinja2 . Environment ( loader = jinja2 . FileSystemLoader ( template_path ) , block_start_string = '{%' , block_end_string = '%}' , variable_start_string = '${' , variable_end_string = '}' , comment_start_string = '{#' , comment_end_string = '#}' , line_statement_prefix = None , line_comment_prefix = None , trim_blocks = True , lstrip_blocks = True , newline_sequence = '\n' ) jinja_env . filters [ 'regexreplace' ] = regex_replace jinja_env . globals . update ( uuidgen = uuidgen ) return jinja_env | Creates a Jinja2 environment with a specific template path . | 188 | 13 |
13,704 | def _debug_info ( self ) : self . _msg ( 'DEBUG' ) self . _msg2 ( 'WorkDir: {0}' . format ( self . _curdir ) ) self . _msg2 ( 'Cookies: {0}' . format ( self . _session . cookies ) ) self . _msg2 ( 'Headers: {0}' . format ( self . _session . headers ) ) self . _msg2 ( 'Configs: {0}' . format ( self . _config ) ) self . _msg2 ( 'Customs: {0}' . format ( self . _custom ) ) self . _msg2 ( 'Account: {0}' . format ( self . _account ) ) | Show a list of recently variables info . | 161 | 8 |
13,705 | def register ( self , argtypes = r'M' , help_msg = None ) : def format_args ( method ) : def wrapped_method ( * args , * * kwargs ) : args_count = len ( args ) # + len(kwargs) argtypes_count = len ( argtypes ) placeholder_count = argtypes . count ( 'H' ) + argtypes . count ( 'h' ) # We check the placeholder count to select a way to # format the args. If placeholder is not equals zero # then we calculate the minimum args count at first. if placeholder_count : min_args_count = ( argtypes_count - placeholder_count ) # If args_count less than minimum args count or bigger # than argtypes count then we raise a Exception to exit. if args_count < min_args_count or args_count > argtypes_count : raise KngetError ( "args count is invalid." , reason = 'args count is {0}' . format ( args_count ) ) # Otherwise, we just check if args count equals argtypes count elif args_count != argtypes_count : raise KngetError ( "args count is invalid" , reason = 'args count is {0}' . format ( args_count ) ) argv = [ ] # NOTE: We cannot modify the args. for i in range ( args_count ) : if argtypes [ i ] in ( 'm' , 'M' ) : argv . append ( args [ i ] ) elif argtypes [ i ] in ( 'i' , 'I' ) : argv . append ( int ( args [ i ] ) ) elif argtypes [ i ] in ( 's' , 'S' ) : argv . append ( str ( args [ i ] ) ) elif argtypes [ i ] in ( 'h' , 'H' ) : argv . append ( args [ i ] ) else : raise KngetError ( 'argtype {0} is invalid!' . format ( argtypes [ i ] ) ) return method ( * argv , * * kwargs ) # Keep the docs. wrapped_method . __doc__ = method . __doc__ self . _commands [ method . __name__ ] = ( wrapped_method , help_msg ) return wrapped_method # only format_args touched the method return format_args | Register a method to a command . | 513 | 7 |
13,706 | def run ( self , tags , begin , end = False ) : if not end : end = begin # Type `H` doesn't cast anything, so we # manually cast the strings end to integer. super ( KngetShell , self ) . run ( tags , begin , int ( end ) ) | Override method of class Knget | 63 | 7 |
13,707 | def write ( models , out = None , base = None , propertybase = None , shorteners = None , logger = logging ) : assert out is not None #Output stream required if not isinstance ( models , list ) : models = [ models ] shorteners = shorteners or { } all_propertybase = [ propertybase ] if propertybase else [ ] all_propertybase . append ( VERSA_BASEIRI ) if any ( ( base , propertybase , shorteners ) ) : out . write ( '# @docheader\n\n* @iri:\n' ) if base : out . write ( ' * @base: {0}' . format ( base ) ) #for k, v in shorteners: # out.write(' * @base: {0}'.format(base)) out . write ( '\n\n' ) origin_space = set ( ) #base_out = models[0].base for m in models : origin_space . update ( all_origins ( m ) ) for o in origin_space : out . write ( '# {0}\n\n' . format ( o ) ) for o_ , r , t , a in m . match ( o ) : abbr_r = abbreviate ( r , all_propertybase ) value_format ( t ) out . write ( '* {0}: {1}\n' . format ( abbr_r , value_format ( t ) ) ) for k , v in a . items ( ) : abbr_k = abbreviate ( k , all_propertybase ) out . write ( ' * {0}: {1}\n' . format ( k , value_format ( v ) ) ) out . write ( '\n' ) return | models - input Versa models from which output is generated . Must be a sequence object not an iterator | 376 | 20 |
13,708 | def register_routes ( self ) : routes = self . flatten_urls ( self . urls ) self . controllers = { } controller_names = set ( ) for route in routes : cname = route [ 'endpoint' ] . split ( '.' ) [ 0 ] controller_names . add ( cname ) for cname in controller_names : attr = getattr ( self . mcontrollers , cname ) instance = attr ( request , response ) self . controllers [ cname ] = instance for route in routes : cname , aname = route [ 'endpoint' ] . split ( '.' ) action = getattr ( self . controllers [ cname ] , aname ) self . wsgi . route ( route [ 'url' ] , route [ 'methods' ] , action ) | Function creates instances of controllers adds into bottle routes | 177 | 9 |
13,709 | def register_extensions ( self ) : try : for extension , config in self . config [ 'extensions' ] . items ( ) : extension_bstr = '' # gather package name if exists extension_pieces = extension . split ( '.' ) # if the extensions is not in glim_extensions package if len ( extension_pieces ) > 1 : extension_bstr = '.' . join ( extension_pieces ) else : # if the extension is in glim_extensions package extension_bstr = 'glim_extensions.%s' % extension_pieces [ 0 ] extension_module = import_module ( extension_bstr ) if extension_module : extension_startstr = '%s.%s' % ( extension_bstr , 'start' ) extension_start = import_module ( extension_startstr , pass_errors = True ) extension_cmdsstr = '%s.%s' % ( extension_bstr , 'commands' ) extension_cmds = import_module ( extension_cmdsstr , pass_errors = True ) if extension_start is not None : before = extension_start . before before ( config ) if extension_cmds is not None : if self . commandadapter is not None : self . commandadapter . register_extension ( extension_cmds , extension_pieces [ 0 ] ) else : GlimLog . error ( 'Extension %s could not be loaded' % extension ) except Exception as e : GlimLog . error ( traceback . format_exc ( ) ) | Function registers extensions given extensions list | 332 | 6 |
13,710 | def register_ssl_context ( self ) : if not empty ( 'ssl' , self . config [ 'app' ] ) : self . ssl_context = self . config [ 'app' ] [ 'ssl' ] else : self . ssl_context = None | Function detects ssl context | 58 | 5 |
13,711 | def flatten_urls ( self , urls ) : available_methods = [ 'POST' , 'PUT' , 'OPTIONS' , 'GET' , 'DELETE' , 'TRACE' , 'COPY' ] ruleset = [ ] for route , endpoint in urls . items ( ) : route_pieces = route . split ( ' ' ) try : methods = url = None if len ( route_pieces ) > 1 : methods = [ route_pieces [ 0 ] ] url = route_pieces [ 1 ] else : methods = available_methods url = route_pieces [ 0 ] endpoint_pieces = endpoint . split ( '.' ) if len ( endpoint_pieces ) > 1 : rule = { 'url' : url , 'endpoint' : endpoint , 'methods' : methods } ruleset . append ( rule ) else : for method in available_methods : rule = { 'url' : url , 'endpoint' : '%s.%s' % ( endpoint , method . lower ( ) ) , 'methods' : [ method ] } ruleset . append ( rule ) except Exception as e : raise InvalidRouteDefinitionError ( ) return ruleset | Function flatten urls for route grouping feature of glim . | 257 | 12 |
13,712 | def _info ( self , args , * * extra_args ) : if not isinstance ( args , argparse . Namespace ) : raise logger . error ( Exception ( "args should of an instance of argparse.Namespace" ) ) logger . info ( "Freight Forwarder: {0}" . format ( VERSION ) ) logger . info ( "docker-py: {0}" . format ( docker_py_version ) ) logger . info ( "Docker Api: {0}" . format ( DOCKER_API_VERSION ) ) logger . info ( "{0} version: {1}" . format ( platform . python_implementation ( ) , platform . python_version ( ) ) ) | Print freight forwarder info to the user . | 151 | 9 |
13,713 | def register ( self , typ ) : # should be able to combine class/instance namespace, and inherit from either # would need to store meta or rely on copy ctor def _func ( cls ) : if typ in self . _class : raise ValueError ( "duplicated type name '%s'" % typ ) cls . plugin_type = typ self . _class [ typ ] = cls return cls return _func | register a plugin | 92 | 3 |
13,714 | def get_plugin_class ( self , typ ) : if typ in self . _class : return self . _class [ typ ] # try to import by same name try : importlib . import_module ( "%s.%s" % ( self . namespace , typ ) ) if typ in self . _class : return self . _class [ typ ] except ImportError as e : self . log . debug ( "ImportError " + str ( e ) ) raise ValueError ( "unknown plugin '%s'" % typ ) | get class by name | 111 | 4 |
13,715 | def register_error_handler ( app , handler = None ) : if not handler : handler = default_error_handler for code in exceptions . default_exceptions . keys ( ) : app . register_error_handler ( code , handler ) | Register error handler Registers an exception handler on the app instance for every type of exception code werkzeug is aware about . | 51 | 26 |
13,716 | def default_error_handler ( exception ) : http_exception = isinstance ( exception , exceptions . HTTPException ) code = exception . code if http_exception else 500 # log exceptions only (app debug should be off) if code == 500 : current_app . logger . error ( exception ) # jsonify error if json requested via accept header if has_app_context ( ) and has_request_context ( ) : headers = request . headers if 'Accept' in headers and headers [ 'Accept' ] == 'application/json' : return json_error_handler ( exception ) # otherwise render template return template_error_handler ( exception ) | Default error handler Will display an error page with the corresponding error code from template directory for example a not found will load a 404 . html etc . Will first look in userland app templates and if not found fallback to boiler templates to display a default page . | 137 | 52 |
13,717 | def _make_nonce ( self ) : chars = string . digits + string . ascii_letters nonce = '' . join ( random . choice ( chars ) for i in range ( 25 ) ) if self . _logging : utils . log ( 'nonce created: %s' % nonce ) return nonce | Generate a unique ID for the request 25 chars in length | 71 | 12 |
13,718 | def _make_auth ( self , method , date , nonce , path , query = { } , ctype = 'application/json' ) : query = urlencode ( query ) hmac_str = ( method + '\n' + nonce + '\n' + date + '\n' + ctype + '\n' + path + '\n' + query + '\n' ) . lower ( ) . encode ( 'utf-8' ) signature = base64 . b64encode ( hmac . new ( self . _secret_key , hmac_str , digestmod = hashlib . sha256 ) . digest ( ) ) auth = 'On ' + self . _access_key . decode ( 'utf-8' ) + ':HmacSHA256:' + signature . decode ( 'utf-8' ) if self . _logging : utils . log ( { 'query' : query , 'hmac_str' : hmac_str , 'signature' : signature , 'auth' : auth } ) return auth | Create the request signature to authenticate | 232 | 7 |
13,719 | def _make_headers ( self , method , path , query = { } , headers = { } ) : date = datetime . datetime . utcnow ( ) . strftime ( '%a, %d %b %Y %H:%M:%S GMT' ) nonce = self . _make_nonce ( ) ctype = headers . get ( 'Content-Type' ) if headers . get ( 'Content-Type' ) else 'application/json' auth = self . _make_auth ( method , date , nonce , path , query = query , ctype = ctype ) req_headers = { 'Content-Type' : 'application/json' , 'Date' : date , 'On-Nonce' : nonce , 'Authorization' : auth , 'User-Agent' : 'Onshape Python Sample App' , 'Accept' : 'application/json' } # add in user-defined headers for h in headers : req_headers [ h ] = headers [ h ] return req_headers | Creates a headers object to sign the request | 222 | 9 |
13,720 | def request ( self , method , path , query = { } , headers = { } , body = { } , base_url = None ) : req_headers = self . _make_headers ( method , path , query , headers ) if base_url is None : base_url = self . _url url = base_url + path + '?' + urlencode ( query ) if self . _logging : utils . log ( body ) utils . log ( req_headers ) utils . log ( 'request url: ' + url ) # only parse as json string if we have to body = json . dumps ( body ) if type ( body ) == dict else body res = requests . request ( method , url , headers = req_headers , data = body , allow_redirects = False , stream = True ) if res . status_code == 307 : location = urlparse ( res . headers [ "Location" ] ) querystring = parse_qs ( location . query ) if self . _logging : utils . log ( 'request redirected to: ' + location . geturl ( ) ) new_query = { } new_base_url = location . scheme + '://' + location . netloc for key in querystring : new_query [ key ] = querystring [ key ] [ 0 ] # won't work for repeated query params return self . request ( method , location . path , query = new_query , headers = headers , base_url = new_base_url ) elif not 200 <= res . status_code <= 206 : if self . _logging : utils . log ( 'request failed, details: ' + res . text , level = 1 ) else : if self . _logging : utils . log ( 'request succeeded, details: ' + res . text ) return res | Issues a request to Onshape | 390 | 7 |
13,721 | def gen_sentences ( self , tokens , aliases = None ) : if aliases is None : aliases = { } for sentence in self . _gen_sentences ( tokens ) : try : alias = aliases [ str ( sentence [ 0 ] ) ] except KeyError : # do nothing if no alias is found pass except IndexError : pass else : sentence [ 0 : 1 ] = list ( Program ( alias ) . gen_tokens ( ) ) yield transform ( Sentence ( sentence ) , self . transforms ) | Generate a sequence of sentences from stream of tokens . | 107 | 11 |
13,722 | def set_timezone ( new_tz = None ) : global tz if new_tz : tz = pytz . timezone ( new_tz ) else : tz = tzlocal . get_localzone ( ) | Set the timezone for datetime fields . By default is your machine s time . If it s called without parameter sets the local time again . | 49 | 29 |
13,723 | def fetch_and_parse ( method , uri , params_prefix = None , * * params ) : response = fetch ( method , uri , params_prefix , * * params ) return _parse ( json . loads ( response . text ) ) | Fetch the given uri and return python dictionary with parsed data - types . | 53 | 16 |
13,724 | def _parse ( data ) : if not data : return [ ] elif isinstance ( data , ( tuple , list ) ) : return [ _parse ( subdata ) for subdata in data ] # extract the nested dict. ex. {"tournament": {"url": "7k1safq" ...}} d = { ik : v for k in data . keys ( ) for ik , v in data [ k ] . items ( ) } # convert datetime strings to datetime objects # and float number strings to float to_parse = dict ( d ) for k , v in to_parse . items ( ) : if k in { "name" , "display_name" , "display_name_with_invitation_email_address" , "username" , "challonge_username" } : continue # do not test type of fields which are always strings if isinstance ( v , TEXT_TYPE ) : try : dt = iso8601 . parse_date ( v ) d [ k ] = dt . astimezone ( tz ) except iso8601 . ParseError : try : d [ k ] = float ( v ) except ValueError : pass return d | Recursively convert a json into python data types | 254 | 10 |
13,725 | def get_departments_by_college ( college ) : url = "{}?{}" . format ( dept_search_url_prefix , urlencode ( { "college_abbreviation" : college . label } ) ) return _json_to_departments ( get_resource ( url ) , college ) | Returns a list of restclients . Department models for the passed College model . | 69 | 16 |
13,726 | def scoped_session_decorator ( func ) : @ wraps ( func ) def wrapper ( * args , * * kwargs ) : from wallace . db import session as wallace_session with sessions_scope ( wallace_session ) as session : from psiturk . db import db_session as psi_session with sessions_scope ( psi_session ) as session_psiturk : # The sessions used in func come from the funcs globals, but # they will be proxied thread locals vars from the session # registry, and will therefore be identical to those returned # by the context managers above. logger . debug ( 'Running worker %s in scoped DB sessions' , func . __name__ ) return func ( * args , * * kwargs ) return wrapper | Manage contexts and add debugging to psiTurk sessions . | 170 | 12 |
13,727 | def readline ( self , continuation = False ) : prompt = ( self . secondary_prompt_string if continuation else self . primary_prompt_string ) try : line = raw_input ( prompt ) while line . endswith ( "\\" ) : line = line [ : - 1 ] + raw_input ( self . secondary_prompt_string ) except EOFError : raise SystemExit ( ) else : return line | Read a line from the terminal . | 92 | 7 |
13,728 | def readlines ( self ) : continuation = False while True : yield self . readline ( continuation ) continuation = True | Read a command from the terminal . | 24 | 7 |
13,729 | def sequence ( pdb_filepath ) : return '\n' . join ( [ '{0}\n{1}' . format ( chain_id , str ( seq ) ) for chain_id , seq in sorted ( PDB . from_filepath ( pdb_filepath ) . atom_sequences . iteritems ( ) ) ] ) | A convenience method for printing PDB sequences in command - line execution . | 76 | 14 |
13,730 | def fix_pdb ( self ) : if self . strict : return # Get the list of chains chains = set ( ) for l in self . lines : if l . startswith ( 'ATOM ' ) or l . startswith ( 'HETATM' ) : chains . add ( l [ 21 ] ) # If there is a chain with a blank ID, change that ID to a valid unused ID if ' ' in chains : fresh_id = None allowed_chain_ids = list ( string . uppercase ) + list ( string . lowercase ) + map ( str , range ( 10 ) ) for c in chains : try : allowed_chain_ids . remove ( c ) except : pass if allowed_chain_ids : fresh_id = allowed_chain_ids [ 0 ] # Rewrite the lines new_lines = [ ] if fresh_id : for l in self . lines : if ( l . startswith ( 'ATOM ' ) or l . startswith ( 'HETATM' ) ) and l [ 21 ] == ' ' : new_lines . append ( '%s%s%s' % ( l [ : 21 ] , fresh_id , l [ 22 : ] ) ) else : new_lines . append ( l ) self . lines = new_lines | A function to fix fatal errors in PDB files when they can be automatically fixed . At present this only runs if self . strict is False . We may want a separate property for this since we may want to keep strict mode but still allow PDBs to be fixed . | 280 | 55 |
13,731 | def replace_headers ( source_pdb_content , target_pdb_content ) : s = PDB ( source_pdb_content ) t = PDB ( target_pdb_content ) source_headers = [ ] for l in s . lines : if l [ : 6 ] . strip ( ) in non_header_records : break else : source_headers . append ( l ) target_body = [ ] in_header = True for l in t . lines : if l [ : 6 ] . strip ( ) in non_header_records : in_header = False if not in_header : target_body . append ( l ) return '\n' . join ( source_headers + target_body ) | Takes the headers from source_pdb_content and adds them to target_pdb_content removing any headers that target_pdb_content had . Only the content up to the first structural line are taken from source_pdb_content and only the content from the first structural line in target_pdb_content are taken . | 157 | 70 |
13,732 | def from_lines ( pdb_file_lines , strict = True , parse_ligands = False ) : return PDB ( "\n" . join ( pdb_file_lines ) , strict = strict , parse_ligands = parse_ligands ) | A function to replace the old constructor call where a list of the file s lines was passed in . | 56 | 20 |
13,733 | def _split_lines ( self ) : parsed_lines = { } for rt in all_record_types : parsed_lines [ rt ] = [ ] parsed_lines [ 0 ] = [ ] for line in self . lines : linetype = line [ 0 : 6 ] if linetype in all_record_types : parsed_lines [ linetype ] . append ( line ) else : parsed_lines [ 0 ] . append ( line ) self . parsed_lines = parsed_lines self . _update_structure_lines ( ) | Creates the parsed_lines dict which keeps all record data in document order indexed by the record type . | 118 | 21 |
13,734 | def _update_structure_lines ( self ) : structure_lines = [ ] atom_chain_order = [ ] chain_atoms = { } for line in self . lines : linetype = line [ 0 : 6 ] if linetype == 'ATOM ' or linetype == 'HETATM' or linetype == 'TER ' : chain_id = line [ 21 ] self . residue_types . add ( line [ 17 : 20 ] . strip ( ) ) if missing_chain_ids . get ( self . pdb_id ) : chain_id = missing_chain_ids [ self . pdb_id ] structure_lines . append ( line ) if ( chain_id not in atom_chain_order ) and ( chain_id != ' ' ) : atom_chain_order . append ( chain_id ) if linetype == 'ATOM ' : atom_type = line [ 12 : 16 ] . strip ( ) if atom_type : chain_atoms [ chain_id ] = chain_atoms . get ( chain_id , set ( ) ) chain_atoms [ chain_id ] . add ( atom_type ) if linetype == 'ENDMDL' : colortext . warning ( "ENDMDL detected: Breaking out early. We do not currently handle NMR structures properly." ) break self . structure_lines = structure_lines self . atom_chain_order = atom_chain_order self . chain_atoms = chain_atoms | ATOM and HETATM lines may be altered by function calls . When this happens this function should be called to keep self . structure_lines up to date . | 325 | 34 |
13,735 | def clone ( self , parse_ligands = False ) : return PDB ( "\n" . join ( self . lines ) , pdb_id = self . pdb_id , strict = self . strict , parse_ligands = parse_ligands ) | A function to replace the old constructor call where a PDB object was passed in and cloned . | 56 | 20 |
13,736 | def get_pdb_id ( self ) : if self . pdb_id : return self . pdb_id else : header = self . parsed_lines [ "HEADER" ] assert ( len ( header ) <= 1 ) if header : self . pdb_id = header [ 0 ] [ 62 : 66 ] return self . pdb_id return None | Return the PDB ID . If one was passed in to the constructor this takes precedence otherwise the header is parsed to try to find an ID . The header does not always contain a PDB ID in regular PDB files and appears to always have an ID of XXXX in biological units so the constructor override is useful . | 78 | 64 |
13,737 | def get_annotated_chain_sequence_string ( self , chain_id , use_seqres_sequences_if_possible , raise_Exception_if_not_found = True ) : if use_seqres_sequences_if_possible and self . seqres_sequences and self . seqres_sequences . get ( chain_id ) : return ( 'SEQRES' , self . seqres_sequences [ chain_id ] ) elif self . atom_sequences . get ( chain_id ) : return ( 'ATOM' , self . atom_sequences [ chain_id ] ) elif raise_Exception_if_not_found : raise Exception ( 'Error: Chain %s expected but not found.' % ( str ( chain_id ) ) ) else : return None | A helper function to return the Sequence for a chain . If use_seqres_sequences_if_possible then we return the SEQRES Sequence if it exists . We return a tuple of values the first identifying which sequence was returned . | 177 | 50 |
13,738 | def get_chain_sequence_string ( self , chain_id , use_seqres_sequences_if_possible , raise_Exception_if_not_found = True ) : chain_pair = self . get_annotated_chain_sequence_string ( chain_id , use_seqres_sequences_if_possible , raise_Exception_if_not_found = raise_Exception_if_not_found ) if chain_pair : return chain_pair [ 1 ] return None | Similar to get_annotated_chain_sequence_string except that we only return the Sequence and do not state which sequence it was . | 109 | 28 |
13,739 | def strip_HETATMs ( self , only_strip_these_chains = [ ] ) : if only_strip_these_chains : self . lines = [ l for l in self . lines if not ( l . startswith ( 'HETATM' ) ) or l [ 21 ] not in only_strip_these_chains ] else : self . lines = [ l for l in self . lines if not ( l . startswith ( 'HETATM' ) ) ] self . _update_structure_lines ( ) | Throw away all HETATM lines . If only_strip_these_chains is specified then only strip HETATMs lines for those chains . | 118 | 31 |
13,740 | def _get_pdb_format_version ( self ) : if not self . format_version : version = None version_lines = None try : version_lines = [ line for line in self . parsed_lines [ 'REMARK' ] if int ( line [ 7 : 10 ] ) == 4 and line [ 10 : ] . strip ( ) ] except : pass if version_lines : assert ( len ( version_lines ) == 1 ) version_line = version_lines [ 0 ] version_regex = re . compile ( '.*?FORMAT V.(.*),' ) mtch = version_regex . match ( version_line ) if mtch and mtch . groups ( 0 ) : try : version = float ( mtch . groups ( 0 ) [ 0 ] ) except : pass self . format_version = version | Remark 4 indicates the version of the PDB File Format used to generate the file . | 177 | 18 |
13,741 | def get_atom_sequence_to_rosetta_json_map ( self ) : import json d = { } atom_sequence_to_rosetta_mapping = self . get_atom_sequence_to_rosetta_map ( ) for c , sm in atom_sequence_to_rosetta_mapping . iteritems ( ) : for k , v in sm . map . iteritems ( ) : d [ k ] = v return json . dumps ( d , indent = 4 , sort_keys = True ) | Returns the mapping from PDB ATOM residue IDs to Rosetta residue IDs in JSON format . | 116 | 19 |
13,742 | def get_rosetta_sequence_to_atom_json_map ( self ) : import json if not self . rosetta_to_atom_sequence_maps and self . rosetta_sequences : raise Exception ( 'The PDB to Rosetta mapping has not been determined. Please call construct_pdb_to_rosetta_residue_map first.' ) d = { } for c , sm in self . rosetta_to_atom_sequence_maps . iteritems ( ) : for k , v in sm . map . iteritems ( ) : d [ k ] = v #d[c] = sm.map return json . dumps ( d , indent = 4 , sort_keys = True ) | Returns the mapping from Rosetta residue IDs to PDB ATOM residue IDs in JSON format . | 158 | 19 |
13,743 | def assert_wildtype_matches ( self , mutation ) : readwt = self . getAminoAcid ( self . getAtomLine ( mutation . Chain , mutation . ResidueID ) ) assert ( mutation . WildTypeAA == residue_type_3to1_map [ readwt ] ) | Check that the wildtype of the Mutation object matches the PDB sequence . | 67 | 16 |
13,744 | def get_B_factors ( self , force = False ) : # Read in the list of bfactors for each ATOM line. if ( not self . bfactors ) or ( force == True ) : bfactors = { } old_chain_residue_id = None for line in self . lines : if line [ 0 : 4 ] == "ATOM" : chain_residue_id = line [ 21 : 27 ] if chain_residue_id != old_chain_residue_id : bfactors [ chain_residue_id ] = [ ] old_chain_residue_id = chain_residue_id bfactors [ chain_residue_id ] . append ( float ( line [ 60 : 66 ] ) ) # Compute the mean and standard deviation for the list of B-factors of each residue B_factor_per_residue = { } mean_per_residue = [ ] for chain_residue_id , bfactor_list in bfactors . iteritems ( ) : mean , stddev , variance = get_mean_and_standard_deviation ( bfactor_list ) B_factor_per_residue [ chain_residue_id ] = dict ( mean = mean , stddev = stddev ) mean_per_residue . append ( mean ) total_average , total_standard_deviation , variance = get_mean_and_standard_deviation ( mean_per_residue ) self . bfactors = dict ( Overall = dict ( mean = total_average , stddev = total_standard_deviation ) , PerResidue = B_factor_per_residue , ) return self . bfactors | This reads in all ATOM lines and compute the mean and standard deviation of each residue s B - factors . It returns a table of the mean and standard deviation per residue as well as the mean and standard deviation over all residues with each residue having equal weighting . | 390 | 53 |
13,745 | def validate_mutations ( self , mutations ) : # Chain, ResidueID, WildTypeAA, MutantAA resID2AA = self . get_residue_id_to_type_map ( ) badmutations = [ ] for m in mutations : wildtype = resID2AA . get ( PDB . ChainResidueID2String ( m . Chain , m . ResidueID ) , "" ) if m . WildTypeAA != wildtype : badmutations . append ( m ) if badmutations : raise PDBValidationException ( "The mutation(s) %s could not be matched against the PDB %s." % ( ", " . join ( map ( str , badmutations ) ) , self . pdb_id ) ) | This function has been refactored to use the SimpleMutation class . The parameter is a list of Mutation objects . The function has no return value but raises a PDBValidationException if the wildtype in the Mutation m does not match the residue type corresponding to residue m . ResidueID in the PDB file . | 167 | 69 |
13,746 | def fix_chain_id ( self ) : for i in xrange ( len ( self . lines ) ) : line = self . lines [ i ] if line . startswith ( "ATOM" ) and line [ 21 ] == ' ' : self . lines [ i ] = line [ : 21 ] + 'A' + line [ 22 : ] | fill in missing chain identifier | 75 | 5 |
13,747 | def getAtomLine ( self , chain , resid ) : for line in self . lines : fieldtype = line [ 0 : 6 ] . strip ( ) assert ( fieldtype == "ATOM" or fieldtype == "HETATM" ) if line [ 21 : 22 ] == chain and resid == line [ 22 : 27 ] : return line raise Exception ( "Could not find the ATOM/HETATM line corresponding to chain '%(chain)s' and residue '%(resid)s'." % vars ( ) ) | This function assumes that all lines are ATOM or HETATM lines . resid should have the proper PDB format i . e . an integer left - padded to length 4 followed by the insertion code which may be a blank space . | 116 | 48 |
13,748 | def getAtomLinesForResidueInRosettaStructure ( self , resid ) : lines = [ line for line in self . lines if line [ 0 : 4 ] == "ATOM" and resid == int ( line [ 22 : 27 ] ) ] if not lines : #print('Failed searching for residue %d.' % resid) #print("".join([line for line in self.lines if line[0:4] == "ATOM"])) raise Exception ( "Could not find the ATOM/HETATM line corresponding to residue '%(resid)s'." % vars ( ) ) return lines | We assume a Rosetta - generated structure where residues are uniquely identified by number . | 135 | 16 |
13,749 | def stripForDDG ( self , chains = True , keepHETATM = False , numberOfModels = None , raise_exception = True ) : if raise_exception : raise Exception ( 'This code is deprecated.' ) from Bio . PDB import PDBParser resmap = { } iresmap = { } newlines = [ ] residx = 0 oldres = None model_number = 1 for line in self . lines : fieldtype = line [ 0 : 6 ] . strip ( ) if fieldtype == "ENDMDL" : model_number += 1 if numberOfModels and ( model_number > numberOfModels ) : break if not numberOfModels : raise Exception ( "The logic here does not handle multiple models yet." ) if ( fieldtype == "ATOM" or ( fieldtype == "HETATM" and keepHETATM ) ) and ( float ( line [ 54 : 60 ] ) != 0 ) : chain = line [ 21 : 22 ] if ( chains == True ) or ( chain in chains ) : resid = line [ 21 : 27 ] # Chain, residue sequence number, insertion code iCode = line [ 26 : 27 ] if resid != oldres : residx += 1 newnumbering = "%s%4.i " % ( chain , residx ) assert ( len ( newnumbering ) == 6 ) id = fieldtype + "-" + resid resmap [ id ] = residx iresmap [ residx ] = id oldres = resid oldlength = len ( line ) # Add the original line back including the chain [21] and inserting a blank for the insertion code line = "%s%4.i %s" % ( line [ 0 : 22 ] , resmap [ fieldtype + "-" + resid ] , line [ 27 : ] ) assert ( len ( line ) == oldlength ) newlines . append ( line ) self . lines = newlines self . ddGresmap = resmap self . ddGiresmap = iresmap # Sanity check against a known library tmpfile = "/tmp/ddgtemp.pdb" self . lines = self . lines or [ "\n" ] # necessary to avoid a crash in the Bio Python module F = open ( tmpfile , 'w' ) F . write ( string . join ( self . lines , "\n" ) ) F . close ( ) parser = PDBParser ( ) structure = parser . get_structure ( 'tmp' , tmpfile ) os . remove ( tmpfile ) count = 0 for residue in structure . get_residues ( ) : count += 1 assert ( count == residx ) assert ( len ( resmap ) == len ( iresmap ) ) | Strips a PDB to ATOM lines . If keepHETATM is True then also retain HETATM lines . By default all PDB chains are kept . The chains parameter should be True or a list . In the latter case only those chains in the list are kept . Unoccupied ATOM lines are discarded . This function also builds maps from PDB numbering to Rosetta numbering and vice versa . | 579 | 85 |
13,750 | def CheckForPresenceOf ( self , reslist ) : if type ( reslist ) == type ( "" ) : reslist = [ reslist ] foundRes = { } for line in self . lines : resname = line [ 17 : 20 ] if line [ 0 : 4 ] == "ATOM" : if resname in reslist : foundRes [ resname ] = True return foundRes . keys ( ) | This checks whether residues in reslist exist in the ATOM lines . It returns a list of the residues in reslist which did exist . | 88 | 28 |
13,751 | def fix_residue_numbering ( self ) : resid_list = self . aa_resids ( ) resid_set = set ( resid_list ) resid_lst1 = list ( resid_set ) resid_lst1 . sort ( ) map_res_id = { } x = 1 old_chain = resid_lst1 [ 0 ] [ 0 ] for resid in resid_lst1 : map_res_id [ resid ] = resid [ 0 ] + '%4.i' % x if resid [ 0 ] == old_chain : x += 1 else : x = 1 old_chain = resid [ 0 ] atomlines = [ ] for line in self . lines : if line [ 0 : 4 ] == "ATOM" and line [ 21 : 26 ] in resid_set and line [ 26 ] == ' ' : lst = [ char for char in line ] #lst.remove('\n') lst [ 21 : 26 ] = map_res_id [ line [ 21 : 26 ] ] atomlines . append ( string . join ( lst , '' ) ) #print string.join(lst,'') else : atomlines . append ( line ) self . lines = atomlines return map_res_id | this function renumbers the res ids in order to avoid strange behaviour of Rosetta | 270 | 17 |
13,752 | def neighbors2 ( self , distance , chain_residue , atom = None , resid_list = None ) : #atom = " CA " if atom == None : # consider all atoms lines = [ line for line in self . atomlines ( resid_list ) if line [ 17 : 20 ] in allowed_PDB_residues_types ] else : # consider only given atoms lines = [ line for line in self . atomlines ( resid_list ) if line [ 17 : 20 ] in allowed_PDB_residues_types and line [ 12 : 16 ] == atom ] shash = spatialhash . SpatialHash ( distance ) for line in lines : pos = ( float ( line [ 30 : 38 ] ) , float ( line [ 38 : 46 ] ) , float ( line [ 46 : 54 ] ) ) shash . insert ( pos , line [ 21 : 26 ] ) neighbor_list = [ ] for line in lines : resid = line [ 21 : 26 ] if resid == chain_residue : pos = ( float ( line [ 30 : 38 ] ) , float ( line [ 38 : 46 ] ) , float ( line [ 46 : 54 ] ) ) for data in shash . nearby ( pos , distance ) : if data [ 1 ] not in neighbor_list : neighbor_list . append ( data [ 1 ] ) neighbor_list . sort ( ) return neighbor_list | this one is more precise since it uses the chain identifier also | 297 | 12 |
13,753 | def extract_xyz_matrix_from_chain ( self , chain_id , atoms_of_interest = [ ] ) : chains = [ l [ 21 ] for l in self . structure_lines if len ( l ) > 21 ] chain_lines = [ l for l in self . structure_lines if len ( l ) > 21 and l [ 21 ] == chain_id ] return PDB . extract_xyz_matrix_from_pdb ( chain_lines , atoms_of_interest = atoms_of_interest , include_all_columns = True ) | Create a pandas coordinates dataframe from the lines in the specified chain . | 125 | 15 |
13,754 | def create_token_file ( username = id_generator ( ) , password = id_generator ( ) ) : cozy_ds_uid = helpers . get_uid ( 'cozy-data-system' ) if not os . path . isfile ( LOGIN_FILENAME ) : with open ( LOGIN_FILENAME , 'w+' ) as token_file : token_file . write ( "{0}\n{1}" . format ( username , password ) ) helpers . file_rights ( LOGIN_FILENAME , mode = 0400 , uid = cozy_ds_uid , gid = 0 ) | Store the admins password for further retrieve | 137 | 7 |
13,755 | def get_admin ( ) : if os . path . isfile ( LOGIN_FILENAME ) : with open ( LOGIN_FILENAME , 'r' ) as token_file : old_login , old_password = token_file . read ( ) . splitlines ( ) [ : 2 ] return old_login , old_password else : return None , None | Return the actual admin from token file | 80 | 7 |
13,756 | def curl_couchdb ( url , method = 'GET' , base_url = BASE_URL , data = None ) : ( username , password ) = get_admin ( ) if username is None : auth = None else : auth = ( username , password ) if method == 'PUT' : req = requests . put ( '{}{}' . format ( base_url , url ) , auth = auth , data = data ) elif method == 'DELETE' : req = requests . delete ( '{}{}' . format ( base_url , url ) , auth = auth ) else : req = requests . get ( '{}{}' . format ( base_url , url ) , auth = auth ) if req . status_code not in [ 200 , 201 ] : raise HTTPError ( '{}: {}' . format ( req . status_code , req . text ) ) return req | Launch a curl on CouchDB instance | 193 | 7 |
13,757 | def get_couchdb_admins ( ) : user_list = [ ] req = curl_couchdb ( '/_config/admins/' ) for user in req . json ( ) . keys ( ) : user_list . append ( user ) return user_list | Return the actual CouchDB admins | 60 | 6 |
13,758 | def create_couchdb_admin ( username , password ) : curl_couchdb ( '/_config/admins/{}' . format ( username ) , method = 'PUT' , data = '"{}"' . format ( password ) ) | Create a CouchDB user | 55 | 5 |
13,759 | def is_cozy_registered ( ) : req = curl_couchdb ( '/cozy/_design/user/_view/all' ) users = req . json ( ) [ 'rows' ] if len ( users ) > 0 : return True else : return False | Check if a Cozy is registered | 57 | 7 |
13,760 | def unregister_cozy ( ) : req = curl_couchdb ( '/cozy/_design/user/_view/all' ) users = req . json ( ) [ 'rows' ] if len ( users ) > 0 : user = users [ 0 ] [ 'value' ] user_id = user [ '_id' ] user_rev = user [ '_rev' ] print 'Delete cozy user: {}' . format ( user_id ) req = curl_couchdb ( '/cozy/{}?rev={}' . format ( user_id , user_rev ) , method = 'DELETE' ) return req . json ( ) else : print 'Cozy not registered' return None | Unregister a cozy | 154 | 4 |
13,761 | def delete_all_couchdb_admins ( ) : # Get current cozy token username = get_admin ( ) [ 0 ] # Get CouchDB admin list admins = get_couchdb_admins ( ) # Delete all admin user excluding current for admin in admins : if admin == username : print "Delete {} later..." . format ( admin ) else : print "Delete {}" . format ( admin ) delete_couchdb_admin ( admin ) # Delete current CouchDB admin admin = username print "Delete {}" . format ( admin ) delete_couchdb_admin ( admin ) | Delete all CouchDB users | 126 | 5 |
13,762 | def delete_token ( ) : username = get_admin ( ) [ 0 ] admins = get_couchdb_admins ( ) # Delete current admin if exist if username in admins : print 'I delete {} CouchDB user' . format ( username ) delete_couchdb_admin ( username ) # Delete token file if exist if os . path . isfile ( LOGIN_FILENAME ) : print 'I delete {} token file' . format ( LOGIN_FILENAME ) os . remove ( LOGIN_FILENAME ) | Delete current token file & CouchDB admin user | 115 | 9 |
13,763 | def create_token ( ) : username = id_generator ( ) password = id_generator ( ) create_couchdb_admin ( username , password ) create_token_file ( username , password ) return 'Token {} created' . format ( username ) | Create token file & create user | 56 | 6 |
13,764 | def ping ( ) : try : curl_couchdb ( '/cozy/' ) ping = True except requests . exceptions . ConnectionError , error : print error ping = False return ping | Ping CozyDB with existing credentials | 39 | 7 |
13,765 | def get_cozy_param ( param ) : try : req = curl_couchdb ( '/cozy/_design/cozyinstance/_view/all' ) rows = req . json ( ) [ 'rows' ] if len ( rows ) == 0 : return None else : return rows [ 0 ] . get ( 'value' , { } ) . get ( param , None ) except : return None | Get parameter in Cozy configuration | 86 | 6 |
13,766 | def str2type ( value ) : if not isinstance ( value , str ) : return value try : return json . loads ( value ) except JSONDecodeError : return value | Take a string and convert it to a value of proper type . | 37 | 13 |
13,767 | def get_authorisation_url ( self , reset = False ) : if reset : self . auth_url = None if not self . auth_url : try : oauth = OAuth2Session ( self . client_id , redirect_uri = self . redirect_url ) self . auth_url , self . state = oauth . authorization_url ( self . auth_base_url ) except Exception : #print("Unexpected error:", sys.exc_info()[0]) #print("Could not get Authorisation Url!") return None return self . auth_url | Initialises the OAuth2 Process by asking the auth server for a login URL . Once called the user can login by being redirected to the url returned by this function . If there is an error during authorisation None is returned . | 124 | 46 |
13,768 | def on_callback ( self , auth_resp ) : try : oauth = OAuth2Session ( self . client_id , state = self . state , redirect_uri = self . redirect_url ) self . token = oauth . fetch_token ( self . token_url , authorization_response = auth_resp , client_secret = self . client_secret , verify = self . verifySSL ) if not self . api_key and self . API_KEY_DEFAULT : self . get_api_key ( ) if not self . api_key : self . API_KEY_DEFAULT = False except Exception : #print("Unexpected error:", sys.exc_info()[0]) #print("Could not fetch token from OAuth Callback!") return False return True | Must be called once the authorisation server has responded after redirecting to the url provided by get_authorisation_url and completing the login there . Returns True if a token was successfully retrieved False otherwise . | 168 | 41 |
13,769 | def validate ( self ) : try : resp = self . request ( ) . get ( self . validate_url , verify = self . verifySSL ) . json ( ) except TokenExpiredError : return False except AttributeError : return False if 'error' in resp : return False return True | Confirms the current token is still valid . Returns True if it is valid False otherwise . | 61 | 18 |
13,770 | def refresh_token ( self ) : try : if self . token : self . token = self . request ( ) . refresh_token ( self . refresh_url , self . token [ 'refresh_token' ] ) return True except Exception as e : # TODO: what might go wrong here - handle this error properly #print("Unexpected error:\t\t", str(e)) #traceback.print_exc() pass return False | Refreshes access token using refresh token . Returns true if successful false otherwise . | 94 | 16 |
13,771 | def revoke_access ( self ) : if self . token is None : return True #Don't try to revoke if token is invalid anyway, will cause an error response anyway. if self . validate ( ) : data = { } data [ 'token' ] = self . token [ 'access_token' ] self . request ( ) . post ( self . revoke_url , data = data , json = None , verify = self . verifySSL ) return True | Requests that the currently used token becomes invalid . Call this should a user logout . | 95 | 18 |
13,772 | def request ( self ) : headers = { 'Accept' : 'application/json' } # Use API Key if possible if self . api_key : headers [ 'X-API-KEY' ] = self . api_key return requests , headers else : # Try to use OAuth if self . token : return OAuth2Session ( self . client_id , token = self . token ) , headers else : raise APIError ( "No API key and no OAuth session available" ) | Returns an OAuth2 Session to be used to make requests . Returns None if a token hasn t yet been received . | 103 | 24 |
13,773 | def to_json ( self ) : data = dict ( self . __dict__ ) data . pop ( 'context' , None ) data [ 'oauth' ] = self . oauth . to_dict ( ) data [ 'cache' ] = self . cache . to_dict ( ) return json . dumps ( data ) | Returns a json string containing all relevant data to recreate this pyalveo . Client . | 69 | 18 |
13,774 | def api_request ( self , url , data = None , method = 'GET' , raw = False , file = None ) : if method is 'GET' : response = self . oauth . get ( url ) elif method is 'POST' : if file is not None : response = self . oauth . post ( url , data = data , file = file ) else : response = self . oauth . post ( url , data = data ) elif method is 'PUT' : response = self . oauth . put ( url , data = data ) elif method is 'DELETE' : response = self . oauth . delete ( url ) else : raise APIError ( "Unknown request method: %s" % ( method , ) ) # check for error responses if response . status_code >= 400 : raise APIError ( response . status_code , '' , "Error accessing API (url: %s, method: %s)\nData: %s\nMessage: %s" % ( url , method , data , response . text ) ) if raw : return response . content else : return response . json ( ) | Perform an API request to the given URL optionally including the specified data | 241 | 14 |
13,775 | def get_collections ( self ) : result = self . api_request ( '/catalog' ) # get the collection name from the url return [ ( os . path . split ( x ) [ 1 ] , x ) for x in result [ 'collections' ] ] | Retrieve a list of the collection URLs for all collections hosted on the server . | 58 | 16 |
13,776 | def get_item ( self , item_url , force_download = False ) : item_url = str ( item_url ) if ( self . use_cache and not force_download and self . cache . has_item ( item_url ) ) : item_json = self . cache . get_item ( item_url ) else : item_json = self . api_request ( item_url , raw = True ) if self . update_cache : self . cache . add_item ( item_url , item_json ) return Item ( json . loads ( item_json . decode ( 'utf-8' ) ) , self ) | Retrieve the item metadata from the server as an Item object | 137 | 12 |
13,777 | def get_document ( self , doc_url , force_download = False ) : doc_url = str ( doc_url ) if ( self . use_cache and not force_download and self . cache . has_document ( doc_url ) ) : doc_data = self . cache . get_document ( doc_url ) else : doc_data = self . api_request ( doc_url , raw = True ) if self . update_cache : self . cache . add_document ( doc_url , doc_data ) return doc_data | Retrieve the data for the given document from the server | 118 | 11 |
13,778 | def get_primary_text ( self , item_url , force_download = False ) : item_url = str ( item_url ) metadata = self . get_item ( item_url ) . metadata ( ) try : primary_text_url = metadata [ 'alveo:primary_text_url' ] except KeyError : return None if primary_text_url == 'No primary text found' : return None if ( self . use_cache and not force_download and self . cache . has_primary_text ( item_url ) ) : primary_text = self . cache . get_primary_text ( item_url ) else : primary_text = self . api_request ( primary_text_url , raw = True ) if self . update_cache : self . cache . add_primary_text ( item_url , primary_text ) return primary_text | Retrieve the primary text for an item from the server | 188 | 11 |
13,779 | def get_item_annotations ( self , item_url , annotation_type = None , label = None ) : # get the annotation URL from the item metadata, if not present then there are no annotations item_url = str ( item_url ) metadata = self . get_item ( item_url ) . metadata ( ) try : annotation_url = metadata [ 'alveo:annotations_url' ] except KeyError : return None req_url = annotation_url if annotation_type is not None : req_url += '?' req_url += urlencode ( ( ( 'type' , annotation_type ) , ) ) if label is not None : if annotation_type is None : req_url += '?' else : req_url += '&' req_url += urlencode ( ( ( 'label' , label ) , ) ) try : return self . api_request ( req_url ) except KeyError : return None | Retrieve the annotations for an item from the server | 202 | 10 |
13,780 | def get_annotation_types ( self , item_url ) : req_url = item_url + "/annotations/types" resp = self . api_request ( req_url ) return resp [ 'annotation_types' ] | Retrieve the annotation types for the given item from the server | 51 | 12 |
13,781 | def add_annotations ( self , item_url , annotations ) : adict = { '@context' : "https://alveo-staging1.intersect.org.au/schema/json-ld" } for ann in annotations : # verify that we have the required properties for key in ( '@type' , 'label' , 'start' , 'end' , 'type' ) : if key not in ann . keys ( ) : raise Exception ( "required key '%s' not present in annotation" % key ) adict [ '@graph' ] = annotations resp = self . api_request ( str ( item_url ) + '/annotations' , method = 'POST' , data = json . dumps ( adict ) ) return self . __check_success ( resp ) | Add annotations to the given item | 173 | 6 |
13,782 | def create_collection ( self , name , metadata ) : payload = { 'collection_metadata' : metadata , 'name' : name } response = self . api_request ( '/catalog' , method = 'POST' , data = json . dumps ( payload ) ) return self . __check_success ( response ) | Create a new collection with the given name and attach the metadata . | 67 | 13 |
13,783 | def modify_collection_metadata ( self , collection_uri , metadata , replace = None , name = '' ) : payload = { 'collection_metadata' : metadata , 'name' : name } if replace is not None : payload [ 'replace' ] = replace response = self . api_request ( collection_uri , method = 'PUT' , data = json . dumps ( payload ) ) return self . __check_success ( response ) | Modify the metadata for the given collection . | 92 | 9 |
13,784 | def get_items ( self , collection_uri ) : cname = os . path . split ( collection_uri ) [ 1 ] return self . search_metadata ( "collection_name:%s" % cname ) | Return all items in this collection . | 47 | 7 |
13,785 | def add_text_item ( self , collection_uri , name , metadata , text , title = None ) : docname = name + ".txt" if title is None : title = name metadata [ 'dcterms:identifier' ] = name metadata [ '@type' ] = 'ausnc:AusNCObject' metadata [ 'hcsvlab:display_document' ] = { '@id' : docname } metadata [ 'hcsvlab:indexable_document' ] = { '@id' : docname } metadata [ 'ausnc:document' ] = [ { '@id' : 'document1.txt' , '@type' : 'foaf:Document' , 'dcterms:extent' : len ( text ) , 'dcterms:identifier' : docname , 'dcterms:title' : title , 'dcterms:type' : 'Text' } ] meta = { 'items' : [ { 'metadata' : { '@context' : self . context , '@graph' : [ metadata ] } , 'documents' : [ { 'content' : text , 'identifier' : docname } ] } ] } response = self . api_request ( collection_uri , method = 'POST' , data = json . dumps ( meta ) ) # this will raise an exception if the request fails self . __check_success ( response ) item_uri = collection_uri + "/" + response [ 'success' ] [ 0 ] return item_uri | Add a new item to a collection containing a single text document . | 335 | 13 |
13,786 | def add_item ( self , collection_uri , name , metadata ) : metadata [ 'dcterms:identifier' ] = name metadata [ 'dc:identifier' ] = name # for backward compatability in Alveo SOLR store until bug fix metadata [ '@type' ] = 'ausnc:AusNCObject' meta = { 'items' : [ { 'metadata' : { '@context' : self . context , '@graph' : [ metadata ] } } ] } response = self . api_request ( collection_uri , method = 'POST' , data = json . dumps ( meta ) ) # this will raise an exception if the request fails self . __check_success ( response ) item_uri = collection_uri + "/" + response [ 'success' ] [ 0 ] return item_uri | Add a new item to a collection | 178 | 7 |
13,787 | def modify_item ( self , item_uri , metadata ) : md = json . dumps ( { 'metadata' : metadata } ) response = self . api_request ( item_uri , method = 'PUT' , data = md ) return self . __check_success ( response ) | Modify the metadata on an item | 60 | 7 |
13,788 | def delete_item ( self , item_uri ) : response = self . api_request ( item_uri , method = 'DELETE' ) return self . __check_success ( response ) | Delete an item from a collection | 42 | 6 |
13,789 | def add_document ( self , item_uri , name , metadata , content = None , docurl = None , file = None , displaydoc = False , preferName = False , contrib_id = None ) : if not preferName and file is not None : docid = os . path . basename ( file ) else : docid = name docmeta = { "metadata" : { "@context" : self . context , "@type" : "foaf:Document" , "dcterms:identifier" : docid , } } # add in metadata we are passed docmeta [ "metadata" ] . update ( metadata ) if contrib_id : docmeta [ 'contribution_id' ] = contrib_id if content is not None : docmeta [ 'document_content' ] = content elif docurl is not None : docmeta [ "metadata" ] [ "dcterms:source" ] = { "@id" : docurl } elif file is not None : # we only pass the metadata part of the dictionary docmeta = docmeta [ 'metadata' ] else : raise Exception ( "One of content, docurl or file must be specified in add_document" ) if file is not None : result = self . api_request ( item_uri , method = 'POST' , data = { 'metadata' : json . dumps ( docmeta ) } , file = file ) else : result = self . api_request ( item_uri , method = 'POST' , data = json . dumps ( docmeta ) ) self . __check_success ( result ) if displaydoc : itemmeta = { "http://alveo.edu.org/vocabulary/display_document" : docid } self . modify_item ( item_uri , itemmeta ) doc_uri = item_uri + "/document/" + name return doc_uri | Add a document to an existing item | 401 | 7 |
13,790 | def delete_document ( self , doc_uri ) : result = self . api_request ( doc_uri , method = 'DELETE' ) return self . __check_success ( result ) | Delete a document from an item | 42 | 6 |
13,791 | def __check_success ( resp ) : if "success" not in resp . keys ( ) : try : raise APIError ( '200' , 'Operation Failed' , resp [ "error" ] ) except KeyError : raise APIError ( '200' , 'Operation Failed' , str ( resp ) ) return resp [ "success" ] | Check a JSON server response to see if it was successful | 72 | 11 |
13,792 | def download_items ( self , items , file_path , file_format = 'zip' ) : download_url = '/catalog/download_items' download_url += '?' + urlencode ( ( ( 'format' , file_format ) , ) ) item_data = { 'items' : list ( items ) } data = self . api_request ( download_url , method = 'POST' , data = json . dumps ( item_data ) , raw = True ) with open ( file_path , 'w' ) as f : f . write ( data ) return file_path | Retrieve a file from the server containing the metadata and documents for the speficied items | 129 | 19 |
13,793 | def search_metadata ( self , query ) : query_url = ( '/catalog/search?' + urlencode ( ( ( 'metadata' , query ) , ) ) ) resp = self . api_request ( query_url ) return ItemGroup ( resp [ 'items' ] , self ) | Submit a search query to the server and retrieve the results | 63 | 11 |
13,794 | def add_to_item_list ( self , item_urls , item_list_url ) : item_list_url = str ( item_list_url ) name = self . get_item_list ( item_list_url ) . name ( ) return self . add_to_item_list_by_name ( item_urls , name ) | Instruct the server to add the given items to the specified Item List | 79 | 13 |
13,795 | def rename_item_list ( self , item_list_url , new_name ) : data = json . dumps ( { 'name' : new_name } ) resp = self . api_request ( str ( item_list_url ) , data , method = "PUT" ) try : return ItemList ( resp [ 'items' ] , self , item_list_url , resp [ 'name' ] ) except KeyError : try : raise APIError ( '200' , 'Rename operation failed' , resp [ 'error' ] ) except KeyError : raise APIError ( '200' , 'Rename operation failed' , resp ) | Rename an Item List on the server | 138 | 8 |
13,796 | def delete_item_list ( self , item_list_url ) : try : resp = self . api_request ( str ( item_list_url ) , method = "DELETE" ) # all good if it says success if 'success' in resp : return True else : raise APIError ( '200' , 'Operation Failed' , 'Delete operation failed' ) except APIError as e : if e . http_status_code == 302 : return True else : raise e | Delete an Item List on the server | 103 | 7 |
13,797 | def get_speakers ( self , collection_name ) : speakers_url = "/speakers/" + collection_name resp = self . api_request ( speakers_url ) if 'speakers' in resp : return resp [ 'speakers' ] else : return [ ] | Get a list of speaker URLs for this collection | 58 | 9 |
13,798 | def add_speaker ( self , collection_name , metadata ) : if 'dcterms:identifier' not in metadata : raise APIError ( msg = "No identifier in speaker metadata" ) if '@context' not in metadata : metadata [ '@context' ] = CONTEXT speakers_url = "/speakers/" + collection_name + "/" resp = self . api_request ( speakers_url , data = json . dumps ( metadata ) , method = "POST" ) if 'success' in resp : return resp [ 'success' ] [ 'URI' ] else : return None | Add a new speaker to this collection . | 127 | 8 |
13,799 | def delete_speaker ( self , speaker_uri ) : response = self . api_request ( speaker_uri , method = 'DELETE' ) return self . __check_success ( response ) | Delete an speaker from a collection | 43 | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.