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,000 | def get_complex ( self ) : d = dict ( LName = self . lname , LShortName = self . lshortname , LHTMLName = self . lhtmlname , RName = self . rname , RShortName = self . rshortname , RHTMLName = self . rhtmlname , FunctionalClassID = self . functional_class_id , PPDBMFunctionalClassID = self . functional_class_id_ppdbm , PPDBMDifficulty = self . difficulty_ppdbm , IsWildType = self . is_wildtype , WildTypeComplexID = self . wildtype_complex , Notes = self . notes , Warnings = self . warnings , ) if self . id : d [ 'ID' ] = self . id return d | Returns the record for the complex definition to be used for database storage . | 169 | 14 |
13,001 | def get_pdb_sets ( self ) : assert ( self . id != None ) data = [ ] for pdb_set in self . pdb_sets : pdb_set_record = dict ( PPComplexID = self . id , SetNumber = pdb_set [ 'set_number' ] , IsComplex = pdb_set [ 'is_complex' ] , Notes = pdb_set [ 'notes' ] , ) chain_records = [ ] for side , chain_details in sorted ( pdb_set [ 'chains' ] . iteritems ( ) ) : chain_records . append ( dict ( PPComplexID = self . id , SetNumber = pdb_set [ 'set_number' ] , Side = side , ChainIndex = chain_details [ 'chain_index' ] , PDBFileID = chain_details [ 'pdb_file_id' ] , Chain = chain_details [ 'chain_id' ] , NMRModel = chain_details [ 'nmr_model' ] , ) ) data . append ( dict ( pdb_set = pdb_set_record , chain_records = chain_records ) ) return data | Return a record to be used for database storage . This only makes sense if self . id is set . See usage example above . | 262 | 26 |
13,002 | def parse_singular_float ( t , tag_name ) : pos = t . getElementsByTagName ( tag_name ) assert ( len ( pos ) == 1 ) pos = pos [ 0 ] assert ( len ( pos . childNodes ) == 1 ) return float ( pos . childNodes [ 0 ] . data ) | Parses the sole floating point value with name tag_name in tag t . Heavy - handed with the asserts . | 72 | 24 |
13,003 | def parse_singular_int ( t , tag_name ) : pos = t . getElementsByTagName ( tag_name ) assert ( len ( pos ) == 1 ) pos = pos [ 0 ] assert ( len ( pos . childNodes ) == 1 ) v = pos . childNodes [ 0 ] . data assert ( v . isdigit ( ) ) # no floats allowed return int ( v ) | Parses the sole integer value with name tag_name in tag t . Heavy - handed with the asserts . | 88 | 23 |
13,004 | def parse_singular_alphabetic_character ( t , tag_name ) : pos = t . getElementsByTagName ( tag_name ) assert ( len ( pos ) == 1 ) pos = pos [ 0 ] assert ( len ( pos . childNodes ) == 1 ) v = pos . childNodes [ 0 ] . data assert ( len ( v ) == 1 and v >= 'A' and 'v' <= 'z' ) # no floats allowed return v | Parses the sole alphabetic character value with name tag_name in tag t . Heavy - handed with the asserts . | 102 | 26 |
13,005 | def parse_singular_string ( t , tag_name ) : pos = t . getElementsByTagName ( tag_name ) assert ( len ( pos ) == 1 ) pos = pos [ 0 ] assert ( len ( pos . childNodes ) == 1 ) return pos . childNodes [ 0 ] . data | Parses the sole string value with name tag_name in tag t . Heavy - handed with the asserts . | 69 | 23 |
13,006 | def timer ( ) : if sys . platform == "win32" : default_timer = time . clock else : default_timer = time . time return default_timer ( ) | Timer used for calculate time elapsed | 37 | 6 |
13,007 | def roulette ( weights , n ) : if n > len ( weights ) : raise Exception ( "Can't choose {} samples from {} items" . format ( n , len ( weights ) ) ) if any ( map ( lambda w : w <= 0 , weights . values ( ) ) ) : raise Exception ( "The weight can't be a non-positive number." ) items = weights . items ( ) chosen = set ( ) for i in range ( n ) : total = sum ( list ( zip ( * items ) ) [ 1 ] ) dice = random . random ( ) * total running_weight = 0 chosen_item = None for item , weight in items : if dice < running_weight + weight : chosen_item = item break running_weight += weight chosen . add ( chosen_item ) items = [ ( i , w ) for ( i , w ) in items if i != chosen_item ] return list ( chosen ) | Choose randomly the given number of items . The probability the item is chosen is proportionate to its weight . | 195 | 21 |
13,008 | def as_dict ( self ) : d = { k : v for ( k , v ) in self . __dict__ . items ( ) } return d | Return the URI object as a dictionary | 33 | 7 |
13,009 | def get_title ( self , group = None ) : title = super ( CommentsPlugin , self ) . get_title ( ) if group is not None : count = GroupComments . objects . filter ( group = group ) . count ( ) else : count = None if count : title = u'%s (%d)' % ( title , count ) return title | Adds number of comments to title . | 75 | 7 |
13,010 | def view ( self , request , group , * * kwargs ) : if request . method == 'POST' : message = request . POST . get ( 'message' ) if message is not None and message . strip ( ) : comment = GroupComments ( group = group , author = request . user , message = message . strip ( ) ) comment . save ( ) msg = _ ( u'Comment added.' ) if request . POST . get ( 'sendmail' , '' ) : self . _send_mail ( comment , group ) if 'postresolve' in request . POST : self . _resolve_group ( request , group ) msg = _ ( u'Comment added and event marked as resolved.' ) messages . success ( request , msg ) return HttpResponseRedirect ( request . path ) query = GroupComments . objects . filter ( group = group ) . order_by ( '-created' ) return self . render ( 'sentry_comments/index.html' , { 'comments' : query , 'group' : group , } ) | Display and store comments . | 224 | 5 |
13,011 | def generate_graphs ( data , name , results_dir ) : graphs . resp_graph_raw ( data [ 'raw' ] , name + '_response_times.svg' , results_dir ) graphs . resp_graph ( data [ 'compiled' ] , name + '_response_times_intervals.svg' , results_dir ) graphs . tp_graph ( data [ 'compiled' ] , name + '_throughput.svg' , results_dir ) | Generate all reports from original dataframe | 109 | 8 |
13,012 | def print_infos ( results ) : print ( 'transactions: %i' % results . total_transactions ) print ( 'timers: %i' % results . total_timers ) print ( 'errors: %i' % results . total_errors ) print ( 'test start: %s' % results . start_datetime ) print ( 'test finish: %s\n' % results . finish_datetime ) | Print informations in standard output | 94 | 6 |
13,013 | def write_template ( data , results_dir , parent ) : print ( "Generating html report..." ) partial = time . time ( ) j_env = Environment ( loader = FileSystemLoader ( os . path . join ( results_dir , parent , 'templates' ) ) ) template = j_env . get_template ( 'report.html' ) report_writer = ReportWriter ( results_dir , parent ) report_writer . write_report ( template . render ( data ) ) print ( "HTML report generated in {} seconds\n" . format ( time . time ( ) - partial ) ) | Write the html template | 129 | 4 |
13,014 | def output ( results_dir , config , parent = '../../' ) : start = time . time ( ) print ( "Compiling results..." ) results_dir = os . path . abspath ( results_dir ) results = ReportResults ( config [ 'run_time' ] , config [ 'results_ts_interval' ] ) results . compile_results ( ) print ( "Results compiled in {} seconds\n" . format ( time . time ( ) - start ) ) if results . total_transactions == 0 : print ( "No results, cannot create report" ) return False print_infos ( results ) data = { 'report' : results , 'run_time' : config [ 'run_time' ] , 'ts_interval' : config [ 'results_ts_interval' ] , 'turrets_config' : results . turrets , 'results' : { "all" : results . main_results , "timers" : results . timers_results } } print ( "Generating graphs..." ) partial = time . time ( ) generate_graphs ( results . main_results , 'All_Transactions' , results_dir ) for key , value in results . timers_results . items ( ) : generate_graphs ( value , key , results_dir ) print ( "All graphs generated in {} seconds\n" . format ( time . time ( ) - partial ) ) write_template ( data , results_dir , parent ) print ( "Full report generated in {} seconds" . format ( time . time ( ) - start ) ) return True | Write the results output for the given test | 339 | 8 |
13,015 | def safeMkdir ( p , permissions = permissions755 ) : try : os . mkdir ( p ) except OSError : pass os . chmod ( p , permissions ) | Wrapper around os . mkdir which does not raise an error if the directory exists . | 39 | 18 |
13,016 | def install_dependencies ( feature = None ) : import subprocess echo ( green ( '\nInstall dependencies:' ) ) echo ( green ( '-' * 40 ) ) req_path = os . path . realpath ( os . path . dirname ( __file__ ) + '/../_requirements' ) # list all features if no feature name if not feature : echo ( yellow ( 'Please specify a feature to install. \n' ) ) for index , item in enumerate ( os . listdir ( req_path ) ) : item = item . replace ( '.txt' , '' ) echo ( green ( '{}. {}' . format ( index + 1 , item ) ) ) echo ( ) return # install if got feature name feature_file = feature . lower ( ) + '.txt' feature_reqs = os . path . join ( req_path , feature_file ) # check existence if not os . path . isfile ( feature_reqs ) : msg = 'Unable to locate feature requirements file [{}]' echo ( red ( msg . format ( feature_file ) ) + '\n' ) return msg = 'Now installing dependencies for "{}" feature...' . format ( feature ) echo ( yellow ( msg ) ) subprocess . check_call ( [ sys . executable , '-m' , 'pip' , 'install' , '-r' , feature_reqs ] ) # update requirements file with dependencies reqs = os . path . join ( os . getcwd ( ) , 'requirements.txt' ) if os . path . exists ( reqs ) : with open ( reqs ) as file : existing = [ x . strip ( ) . split ( '==' ) [ 0 ] for x in file . readlines ( ) if x ] lines = [ '\n' ] with open ( feature_reqs ) as file : incoming = file . readlines ( ) for line in incoming : if not ( len ( line ) ) or line . startswith ( '#' ) : lines . append ( line ) continue package = line . strip ( ) . split ( '==' ) [ 0 ] if package not in existing : lines . append ( line ) with open ( reqs , 'a' ) as file : file . writelines ( lines ) echo ( green ( 'DONE\n' ) ) | Install dependencies for a feature | 501 | 5 |
13,017 | def _post ( self , xml_query ) : req = urllib2 . Request ( url = 'http://www.rcsb.org/pdb/rest/search' , data = xml_query ) f = urllib2 . urlopen ( req ) return f . read ( ) . strip ( ) | POST the request . | 68 | 4 |
13,018 | def simple_hashstring ( obj , bits = 64 ) : #Useful discussion of techniques here: http://stackoverflow.com/questions/1303021/shortest-hash-in-python-to-name-cache-files #Use MurmurHash3 #Get a 64-bit integer, the first half of the 128-bit tuple from mmh and then bit shift it to get the desired bit length basis = mmh3 . hash64 ( str ( obj ) ) [ 0 ] >> ( 64 - bits ) if bits == 64 : raw_hash = struct . pack ( '!q' , basis ) else : raw_hash = struct . pack ( '!q' , basis ) [ : - int ( ( 64 - bits ) / 8 ) ] hashstr = base64 . urlsafe_b64encode ( raw_hash ) . rstrip ( b"=" ) return hashstr . decode ( 'ascii' ) | Creates a simple hash in brief string form from obj bits is an optional bit width defaulting to 64 and should be in multiples of 8 with a maximum of 64 | 202 | 34 |
13,019 | def create_slug ( title , plain_len = None ) : if plain_len : title = title [ : plain_len ] pass1 = OMIT_FROM_SLUG_PAT . sub ( '_' , title ) . lower ( ) return NORMALIZE_UNDERSCORES_PAT . sub ( '_' , pass1 ) | Tries to create a slug from a title trading off collision risk with readability and minimized cruft | 79 | 20 |
13,020 | def profiling_query_formatter ( view , context , query_document , name ) : return Markup ( '' . join ( [ '<div class="pymongo-query row">' , '<div class="col-md-1">' , '<a href="{}">' . format ( query_document . get_admin_url ( _external = True ) ) , mongo_command_name_formatter ( view , context , query_document , 'command_name' ) , # '<span class="label {}">{}</span>'.format( # command_name_map.get(query_document.command_name, 'label-default'), # query_document.command_name, # ), '</div>' , '<div class="col-md-10">' , profiling_pure_query_formatter ( None , None , query_document , 'command' , tag = 'pre' ) , '</div>' , '<div class="col-md-1">' , '<small>{} ms</small>' . format ( query_document . duration ) , '</a>' , '</div>' , '</div>' , ] ) ) | Format a ProfilingQuery entry for a ProfilingRequest detail field | 267 | 13 |
13,021 | def make_response ( obj ) : if obj is None : raise TypeError ( "Handler return value cannot be None." ) if isinstance ( obj , Response ) : return obj return Response ( 200 , body = obj ) | Try to coerce an object into a Response object . | 46 | 11 |
13,022 | def resolve_handler ( request , view_handlers ) : view = None if request . _context : # Allow context to be missing for easier testing route_name = request . _context [ - 1 ] . route . name if route_name and VIEW_SEPARATOR in route_name : view = route_name . split ( VIEW_SEPARATOR , 1 ) [ 1 ] or None if view not in view_handlers : raise NotFound method_handlers = view_handlers [ view ] verb = request . method if verb not in method_handlers : if verb == 'HEAD' and 'GET' in method_handlers : verb = 'GET' else : allowed_methods = set ( method_handlers . keys ( ) ) if 'HEAD' not in allowed_methods and 'GET' in allowed_methods : allowed_methods . add ( 'HEAD' ) allow = ', ' . join ( sorted ( allowed_methods ) ) raise MethodNotAllowed ( allow = allow ) handlers = method_handlers [ verb ] vary = set ( ) if len ( set ( h . provides for h in handlers if h . provides is not None ) ) > 1 : vary . add ( 'Accept' ) if len ( set ( h . accepts for h in handlers ) ) > 1 : vary . add ( 'Content-Type' ) content_type = request . content_type if content_type : handlers = negotiate_content_type ( content_type , handlers ) if not handlers : raise UnsupportedMediaType accept = request . headers . get ( 'Accept' ) if accept : handlers = negotiate_accept ( accept , handlers ) if not handlers : raise NotAcceptable return handlers [ 0 ] , vary | Select a suitable handler to handle the request . | 366 | 9 |
13,023 | def negotiate_content_type ( content_type , handlers ) : accepted = [ h . accepts for h in handlers ] scored_ranges = [ ( mimeparse . fitness_and_quality_parsed ( content_type , [ mimeparse . parse_media_range ( mr ) ] ) , mr ) for mr in accepted ] # Sort by fitness, then quality parsed (higher is better) scored_ranges . sort ( reverse = True ) best_score = scored_ranges [ 0 ] [ 0 ] # (fitness, quality) if best_score == MIMEPARSE_NO_MATCH or not best_score [ 1 ] : return [ ] media_ranges = [ pair [ 1 ] for pair in scored_ranges if pair [ 0 ] == best_score ] best_range = media_ranges [ 0 ] return [ h for h in handlers if h . accepts == best_range ] | Filter handlers that accept a given content - type . | 202 | 10 |
13,024 | def negotiate_accept ( accept , handlers ) : provided = [ h . provides for h in handlers ] if None in provided : # Not all handlers are annotated - disable content-negotiation # for Accept. # TODO: We could implement an "optimistic mode": If a fully qualified # mime-type was requested and we have a specific handler that provides # it, choose that handler instead of the default handler (depending on # 'q' value). return [ h for h in handlers if h . provides is None ] else : # All handlers are annotated with the mime-type they # provide: find the best match. # # mimeparse.best_match expects the supported mime-types to be sorted # in order of increasing desirability. By default, we use the order in # which handlers were added (earlier means better). # TODO: add "priority" parameter for user-defined priorities. best_match = mimeparse . best_match ( reversed ( provided ) , accept ) return [ h for h in handlers if h . provides == best_match ] | Filter handlers that provide an acceptable mime - type . | 229 | 11 |
13,025 | def get ( self , key , default = None , type = None ) : try : value = self [ key ] if type is not None : return type ( value ) return value except ( KeyError , ValueError ) : return default | Returns the first value for a key . | 48 | 8 |
13,026 | def getall ( self , key , type = None ) : values = [ ] for k , v in self . _items : if k == key : if type is not None : try : values . append ( type ( v ) ) except ValueError : pass else : values . append ( v ) return values | Return a list of values for the given key . | 64 | 10 |
13,027 | def url_for ( * args , * * kw ) : # Allow passing 'self' as named parameter self , target , args = args [ 0 ] , args [ 1 ] , list ( args [ 2 : ] ) query = kw . pop ( '_query' , None ) relative = kw . pop ( '_relative' , False ) url = build_url ( self . _context , target , args , kw ) if query : if isinstance ( query , dict ) : query = sorted ( query . items ( ) ) query_part = urllib . urlencode ( query ) query_sep = '&' if '?' in url else '?' url = url + query_sep + query_part if relative : return url else : return urlparse . urljoin ( self . application_uri , url ) | Build the URL for a target route . | 179 | 8 |
13,028 | def input ( self ) : if self . _input is None : input_file = self . environ [ 'wsgi.input' ] content_length = self . content_length or 0 self . _input = WsgiInput ( input_file , self . content_length ) return self . _input | Returns a file - like object representing the request body . | 66 | 11 |
13,029 | def body ( self ) : if self . _body is None : if self . _body_reader is None : self . _body = self . input . read ( self . content_length or 0 ) else : self . _body = self . _body_reader ( self . input ) return self . _body | Reads and returns the entire request body . | 66 | 9 |
13,030 | def form ( self ) : if self . _form is None : # Make sure FieldStorage always parses the form content, # and never the query string. environ = self . environ . copy ( ) environ [ 'QUERY_STRING' ] = '' environ [ 'REQUEST_METHOD' ] = 'POST' fs = cgi . FieldStorage ( fp = self . input , environ = environ , keep_blank_values = True ) # File upload field handling copied from WebOb fields = [ ] for f in fs . list or [ ] : if f . filename : f . filename = f . filename . decode ( 'utf-8' ) fields . append ( ( f . name . decode ( 'utf-8' ) , f ) ) else : fields . append ( ( f . name . decode ( 'utf-8' ) , f . value . decode ( 'utf-8' ) ) ) self . _form = QueryDict ( fields ) return self . _form | Reads the request body and tries to parse it as a web form . | 215 | 15 |
13,031 | def cookies ( self ) : if self . _cookies is None : c = SimpleCookie ( self . environ . get ( 'HTTP_COOKIE' ) ) self . _cookies = dict ( [ ( k . decode ( 'utf-8' ) , v . value . decode ( 'utf-8' ) ) for k , v in c . items ( ) ] ) return self . _cookies | Returns a dictionary mapping cookie names to their values . | 89 | 10 |
13,032 | def _format_parameter_error_message ( name : str , sig : Signature , num_params : int ) -> str : if num_params == 0 : plural = 's' missing = 2 arguments = "'slack' and 'event'" else : plural = '' missing = 1 arguments = "'event'" return ( f"{name}{sig} missing {missing} required positional " f"argument{plural}: {arguments}" ) | Format an error message for missing positional arguments . | 95 | 9 |
13,033 | def connect_with_retry ( self ) -> None : if self . is_connected ( ) : log . debug ( 'Already connected to the Slack API' ) return for retry in range ( 1 , self . retries + 1 ) : self . connect ( ) if self . is_connected ( ) : log . debug ( 'Connected to the Slack API' ) return else : interval = self . backoff ( retry ) log . debug ( "Waiting %.3fs before retrying" , interval ) time . sleep ( interval ) raise FailedConnection ( 'Failed to connect to the Slack API' ) | Attempt to connect to the Slack API . Retry on failures . | 131 | 13 |
13,034 | def fetch_events ( self ) -> List [ dict ] : try : return self . inner . rtm_read ( ) # TODO: The TimeoutError could be more elegantly resolved by making # a PR to the websocket-client library and letting them coerce that # exception to a WebSocketTimeoutException that could be caught by # the slackclient library and then we could just use auto_reconnect. except TimeoutError : log . debug ( 'Lost connection to the Slack API, attempting to ' 'reconnect' ) self . connect_with_retry ( ) return [ ] | Fetch new RTM events from the API . | 125 | 10 |
13,035 | def _ensure_slack ( self , connector : Any , retries : int , backoff : Callable [ [ int ] , float ] ) -> None : connector = self . _env_var if connector is None else connector slack : SlackClient = _create_slack ( connector ) self . _slack = _SlackClientWrapper ( slack = slack , retries = retries , backoff = backoff ) | Ensure we have a SlackClient . | 91 | 8 |
13,036 | def run ( self , * , connector : Union [ EnvVar , Token , SlackClient , None ] = None , interval : float = 0.5 , retries : int = 16 , backoff : Callable [ [ int ] , float ] = None , until : Callable [ [ List [ dict ] ] , bool ] = None ) -> None : backoff = backoff or _truncated_exponential until = until or _forever self . _ensure_slack ( connector = connector , retries = retries , backoff = backoff ) assert self . _slack is not None while True : events = self . _slack . fetch_events ( ) if not until ( events ) : log . debug ( 'Exiting event loop' ) break # Handle events! for event in events : type_ = event . get ( 'type' , '' ) for handler in self . _handlers [ type_ ] + self . _handlers [ '*' ] : fn , kwargs = handler fn ( self . _slack . inner , event , * * kwargs ) # Maybe don't pester the Slack API too much. time . sleep ( interval ) | Connect to the Slack API and run the event handler loop . | 253 | 12 |
13,037 | def install ( ) : tmp_weboob_dir = '/tmp/weboob' # Check that the directory does not already exists while ( os . path . exists ( tmp_weboob_dir ) ) : tmp_weboob_dir += '1' # Clone the repository print 'Fetching sources in temporary dir {}' . format ( tmp_weboob_dir ) result = cmd_exec ( 'git clone {} {}' . format ( WEBOOB_REPO , tmp_weboob_dir ) ) if ( result [ 'error' ] ) : print result [ 'stderr' ] print 'Weboob installation failed: could not clone repository' exit ( ) print 'Sources fetched, will now process to installation' # Launch the installation result = cmd_exec ( 'cd {} && ./setup.py install' . format ( tmp_weboob_dir ) ) # Remove the weboob directory shutil . rmtree ( tmp_weboob_dir ) if ( result [ 'error' ] ) : print result [ 'stderr' ] print 'Weboob installation failed: setup failed' exit ( ) print result [ 'stdout' ] # Check weboob version weboob_version = get_weboob_version ( ) if ( not weboob_version ) : print 'Weboob installation failed: version not detected' exit ( ) print 'Weboob (version: {}) installation succeeded' . format ( weboob_version ) update ( ) | Install weboob system - wide | 329 | 7 |
13,038 | def add_many ( self , rels ) : for curr_rel in rels : attrs = self . _attr_cls ( ) if len ( curr_rel ) == 2 : # handle __iter__ output for copy() origin , rel , target , attrs = curr_rel [ 1 ] elif len ( curr_rel ) == 3 : origin , rel , target = curr_rel elif len ( curr_rel ) == 4 : origin , rel , target , attrs = curr_rel else : raise ValueError assert rel self . add ( origin , rel , target , attrs ) return | Add a list of relationships to the extent | 136 | 8 |
13,039 | def call_repeatedly ( func , interval , * args , * * kwargs ) : main_thead = threading . current_thread ( ) stopped = threading . Event ( ) def loop ( ) : while not stopped . wait ( interval ) and main_thead . is_alive ( ) : # the first call is in `interval` secs func ( * args , * * kwargs ) return timer_thread = threading . Thread ( target = loop , daemon = True ) timer_thread . start ( ) atexit . register ( stopped . set ) return timer_thread , stopped . set | Call a function at interval Returns both the thread object and the loop stopper Event . | 133 | 17 |
13,040 | def save ( self , role , commit = True ) : self . is_instance ( role ) schema = RoleSchema ( ) valid = schema . process ( role ) if not valid : return valid db . session . add ( role ) if commit : db . session . commit ( ) events . role_saved_event . send ( role ) return role | Persist role model | 74 | 4 |
13,041 | def update_phase ( self , environment , data , prediction , user , item , correct , time , answer_id , * * kwargs ) : pass | After the prediction update the environment and persist some information for the predictive model . | 33 | 15 |
13,042 | def append_flanking_markers ( qtls_mk_file , flanking_markers ) : matrix = read_input_file ( qtls_mk_file , sep = ',' ) output = [ ] cnt = 0 for row in matrix : if cnt == 0 : markers = [ 'LOD2 interval start' , 'LOD2 interval end' ] elif row [ 3 ] in flanking_markers : markers = flanking_markers [ row [ 3 ] ] else : markers = [ 'NA' , 'NA' ] cnt += 1 row . extend ( markers ) output . append ( row ) write_matrix ( qtls_mk_file , output ) | Append the flanking markers extracted in the process of generating the MapChart to the QTL list file . | 151 | 22 |
13,043 | def get_info ( self ) : escaped_doi = urllib2 . quote ( self . doi , '' ) html = get_resource ( "www.crossref.org" , '/guestquery?queryType=doi&restype=unixref&doi=%s&doi_search=Search' % escaped_doi ) xml_matches = [ ] for m in re . finditer ( '(<doi_records>.*?</doi_records>)' , html , re . DOTALL ) : xml_matches . append ( m . group ( 0 ) ) if len ( xml_matches ) == 0 : raise DOIRetrievalException ( 'No matches found for the DOI "%s".' % self . doi ) elif len ( xml_matches ) == 1 : return xml_matches [ 0 ] else : raise DOIRetrievalException ( 'Multiple (%d) matches found for the DOI "%s".' % ( len ( xml_matches ) , self . doi ) ) | Retrieve the data from CrossRef . | 221 | 7 |
13,044 | def add_backbone_atoms_linearly_from_loop_filepaths ( self , loop_json_filepath , fasta_filepath , residue_ids ) : # Parse the loop file loop_def = json . loads ( read_file ( loop_json_filepath ) ) assert ( len ( loop_def [ 'LoopSet' ] ) == 1 ) start_res = loop_def [ 'LoopSet' ] [ 0 ] [ 'start' ] end_res = loop_def [ 'LoopSet' ] [ 0 ] [ 'stop' ] start_res = PDB . ChainResidueID2String ( start_res [ 'chainID' ] , ( str ( start_res [ 'resSeq' ] ) + start_res [ 'iCode' ] ) . strip ( ) ) end_res = PDB . ChainResidueID2String ( end_res [ 'chainID' ] , ( str ( end_res [ 'resSeq' ] ) + end_res [ 'iCode' ] ) . strip ( ) ) assert ( start_res in residue_ids ) assert ( end_res in residue_ids ) # Parse the FASTA file and extract the sequence f = FASTA ( read_file ( fasta_filepath ) , strict = False ) assert ( len ( f . get_sequences ( ) ) == 1 ) insertion_sequence = f . sequences [ 0 ] [ 2 ] if not len ( residue_ids ) == len ( insertion_sequence ) : raise Exception ( 'The sequence in the FASTA file must have the same length as the list of residues.' ) # Create the insertion sequence (a sub-sequence of the FASTA sequence) # The post-condition is that the start and end residues are the first and last elements of kept_residues respectively kept_residues = [ ] insertion_residue_map = { } in_section = False found_end = False for x in range ( len ( residue_ids ) ) : residue_id = residue_ids [ x ] if residue_id == start_res : in_section = True if in_section : kept_residues . append ( residue_id ) insertion_residue_map [ residue_id ] = insertion_sequence [ x ] if residue_id == end_res : found_end = True break if not kept_residues : raise Exception ( 'The insertion sequence is empty (check the start and end residue ids).' ) if not found_end : raise Exception ( 'The end residue was not encountered when iterating over the insertion sequence (check the start and end residue ids).' ) # Identify the start and end Residue objects try : start_res = self . residues [ start_res [ 0 ] ] [ start_res [ 1 : ] ] end_res = self . residues [ end_res [ 0 ] ] [ end_res [ 1 : ] ] except Exception , e : raise Exception ( 'The start or end residue could not be found in the PDB file.' ) return self . add_backbone_atoms_linearly ( start_res , end_res , kept_residues , insertion_residue_map ) | A utility wrapper around add_backbone_atoms_linearly . Adds backbone atoms in a straight line from the first to the last residue of residue_ids . | 701 | 34 |
13,045 | def add_atoms_linearly ( self , start_atom , end_atom , new_atoms , jitterbug = 0.2 ) : atom_name_map = { 'CA' : ' CA ' , 'C' : ' C ' , 'N' : ' N ' , 'O' : ' O ' , } assert ( start_atom . residue . chain == end_atom . residue . chain ) chain_id = start_atom . residue . chain # Initialize steps num_new_atoms = float ( len ( new_atoms ) ) X , Y , Z = start_atom . x , start_atom . y , start_atom . z x_step = ( end_atom . x - X ) / ( num_new_atoms + 1.0 ) y_step = ( end_atom . y - Y ) / ( num_new_atoms + 1.0 ) z_step = ( end_atom . z - Z ) / ( num_new_atoms + 1.0 ) D = math . sqrt ( x_step * x_step + y_step * y_step + z_step * z_step ) jitter = 0 if jitterbug : jitter = ( ( ( x_step + y_step + z_step ) / 3.0 ) * jitterbug ) / D new_lines = [ ] next_serial_number = max ( sorted ( self . atoms . keys ( ) ) ) + 1 round = 0 for new_atom in new_atoms : X , Y , Z = X + x_step , Y + y_step , Z + z_step if jitter : if round % 3 == 0 : X , Y = X + jitter , Y - jitter elif round % 3 == 1 : Y , Z = Y + jitter , Z - jitter elif round % 3 == 2 : Z , X = Z + jitter , X - jitter round += 1 residue_id , residue_type , atom_name = new_atom assert ( len ( residue_type ) == 3 ) assert ( len ( residue_id ) == 6 ) new_lines . append ( 'ATOM {0} {1} {2} {3} {4:>8.3f}{5:>8.3f}{6:>8.3f} 1.00 0.00 ' . format ( str ( next_serial_number ) . rjust ( 5 ) , atom_name_map [ atom_name ] , residue_type , residue_id , X , Y , Z ) ) next_serial_number += 1 new_pdb = [ ] in_start_residue = False for l in self . indexed_lines : if l [ 0 ] and l [ 3 ] . serial_number == start_atom . serial_number : in_start_residue = True if in_start_residue and l [ 3 ] . serial_number != start_atom . serial_number : new_pdb . extend ( new_lines ) #colortext.warning('\n'.join(new_lines)) in_start_residue = False if l [ 0 ] : #print(l[2]) new_pdb . append ( l [ 2 ] ) else : #print(l[1]) new_pdb . append ( l [ 1 ] ) return '\n' . join ( new_pdb ) | A low - level function which adds new_atoms between start_atom and end_atom . This function does not validate the input i . e . the calling functions are responsible for ensuring that the insertion makes sense . | 745 | 44 |
13,046 | def to_string ( self ) : return '%s %s %s %s %s' % ( self . trait , self . start_position , self . peak_start_position , self . peak_stop_position , self . stop_position ) | Return the string as it should be presented in a MapChart input file . | 55 | 15 |
13,047 | def main ( ) : # register the global parser preparser = argparse . ArgumentParser ( description = description , add_help = False ) preparser . add_argument ( '--env' , '-e' , dest = 'env' , default = 'development' , help = 'choose application environment' ) # parse existing options namespace , extra = preparser . parse_known_args ( ) env = namespace . env # register the subparsers parser = argparse . ArgumentParser ( parents = [ preparser ] , description = description , add_help = True ) subparsers = parser . add_subparsers ( title = 'commands' , help = 'commands' ) # initialize a command adapter with subparsers commandadapter = CommandAdapter ( subparsers ) # register glim commands commandadapter . register ( glim . commands ) # register app commands appcommands = import_module ( 'app.commands' , pass_errors = True ) commandadapter . register ( appcommands ) app = None if paths . app_exists ( ) is False : # check if a new app is being created new = True if 'new' in extra else False if ( 'help' in extra ) or ( '--help' in extra ) or ( '-h' in extra ) : help = True else : help = False if help : parser . print_help ( ) exit ( ) else : app = make_app ( env , commandadapter ) args = parser . parse_args ( ) command = commandadapter . match ( args ) commandadapter . dispatch ( command , app ) | The single entry point to glim command line interface . Main method is called from pypi console_scripts key or by glim . py on root . This function initializes a new app given the glim commands and app commands if app exists . | 343 | 48 |
13,048 | def make_app ( env , commandadapter = None ) : mconfig = import_module ( 'app.config.%s' % env , pass_errors = True ) if mconfig is None and paths . app_exists ( ) : print ( colored ( 'Configuration for "%s" environment is not found' % env , 'red' ) ) return None mstart = import_module ( 'app.start' ) mroutes = import_module ( 'app.routes' ) mcontrollers = import_module ( 'app.controllers' ) before = mstart . before return Glim ( commandadapter , mconfig , mroutes , mcontrollers , env , before ) | Function creates an app given environment | 153 | 6 |
13,049 | def callback ( self ) : next = request . args . get ( 'next' ) or None endpoint = 'social.{}.handle' . format ( self . provider ) return url_for ( endpoint , _external = True , next = next ) | Generate callback url for provider | 52 | 6 |
13,050 | def next ( self ) : next = request . args . get ( 'next' ) if next is None : params = self . default_redirect_params next = url_for ( self . default_redirect_endpoint , * * params ) return next | Where to redirect after authorization | 55 | 5 |
13,051 | def dispatch_request ( self ) : if current_user . is_authenticated : return redirect ( self . next ) # clear previous! if 'social_data' in session : del session [ 'social_data' ] res = self . app . authorized_response ( ) if res is None : if self . flash : flash ( self . auth_failed_msg , 'danger' ) return redirect ( self . next ) # retrieve profile data = self . get_profile_data ( res ) if data is None : if self . flash : flash ( self . data_failed_msg , 'danger' ) return redirect ( self . next ) # attempt login try : ok = user_service . attempt_social_login ( self . provider , data [ 'id' ] ) if ok : if self . flash : flash ( self . logged_in_msg . format ( self . provider ) , 'success' ) return redirect ( self . logged_in ) except x . AccountLocked as locked : msg = self . lock_msg . format ( locked . locked_until ) if self . flash : flash ( msg , 'danger' ) url = url_for ( self . lock_redirect , * * self . lock_redirect_params ) return redirect ( url ) except x . EmailNotConfirmed : return redirect ( url_for ( self . unconfirmed_email_endpoint ) ) # get data email = data . get ( 'email' ) provider = data . get ( 'provider' ) id = data . get ( 'id' ) id_column = '{}_id' . format ( provider ) # user exists: add social id to profile user = user_service . first ( email = email ) if user : setattr ( user , id_column , id ) user_service . save ( user ) # no user: register if not user : cfg = current_app . config send_welcome = cfg . get ( 'USER_SEND_WELCOME_MESSAGE' ) base_confirm_url = cfg . get ( 'USER_BASE_EMAIL_CONFIRM_URL' ) if not base_confirm_url : endpoint = 'user.confirm.email.request' base_confirm_url = url_for ( endpoint , _external = True ) data = dict ( email = email ) data [ id_column ] = id user = user_service . register ( user_data = data , send_welcome = send_welcome , base_confirm_url = base_confirm_url ) # email confirmed? if user_service . require_confirmation and not user . email_confirmed : return redirect ( url_for ( self . ok_endpoint , * * self . ok_params ) ) # otherwise just login user_service . force_login ( user ) return redirect ( self . force_login_redirect ) | Handle redirect back from provider | 621 | 5 |
13,052 | def project ( v , n ) : return v - matmul ( v , n ) * n / ( norm ( n ) ** 2.0 ) | Project Vector v onto plane with normal vector n . | 32 | 10 |
13,053 | def main ( ) : args = parse_args ( ) if args . version : from . __init__ import __version__ , __release_date__ print ( 'elkme %s (release date %s)' % ( __version__ , __release_date__ ) ) print ( '(c) 2015-2017 46elks AB <hello@46elks.com>' ) print ( small_elk ) exit ( 0 ) conf , conf_status = config . init_config ( args ) if not conf_status [ 0 ] : errors . append ( conf_status [ 1 ] ) elif conf_status [ 1 ] : print ( conf_status [ 1 ] ) message = parse_message ( args ) if conf_status [ 1 ] and not message : # No message but the configuration file was stored sys . exit ( 0 ) try : elks_conn = Elks ( auth = ( conf [ 'username' ] , conf [ 'password' ] ) , api_url = conf . get ( 'api_url' ) ) except KeyError : errors . append ( 'API keys not properly set. Please refer to ' + '`elkme --usage`, `elkme --help` or ' + 'https://46elks.github.io/elkme' ) if not message : print ( USAGE , file = sys . stderr ) exit ( - 1 ) for error in errors : print ( '[ERROR] {}' . format ( error ) ) exit ( - 1 ) options = [ ] if args . flash : options . append ( 'flashsms' ) try : send_sms ( elks_conn , conf , message , length = args . length , options = options ) except ElksException as e : print ( e , file = sys . stderr ) | Executed on run | 385 | 4 |
13,054 | def _build_graph ( self ) -> nx . DiGraph : digraph = nx . DiGraph ( ) for state in self . model . all_states ( ) : self . _number_of_states += 1 for next_state in self . model . available_state ( state ) : self . _number_of_transitions += 1 digraph . add_edge ( self . _transform_state_to_string ( state ) , self . _transform_state_to_string ( next_state ) ) return digraph | Private method to build the graph from the model . | 115 | 10 |
13,055 | def _transform_state_to_string ( self , state : State ) -> str : return '' . join ( str ( state [ gene ] ) for gene in self . model . genes ) | Private method which transform a state to a string . | 40 | 10 |
13,056 | def as_dot ( self ) -> str : return nx . drawing . nx_pydot . to_pydot ( self . _graph ) . to_string ( ) | Return as a string the dot version of the graph . | 40 | 11 |
13,057 | def export_to_dot ( self , filename : str = 'output' ) -> None : with open ( filename + '.dot' , 'w' ) as output : output . write ( self . as_dot ( ) ) | Export the graph to the dot file filename . dot . | 48 | 11 |
13,058 | def get_duration_measures ( source_file_path , output_path = None , phonemic = False , semantic = False , quiet = False , similarity_file = None , threshold = None ) : #validate arguments here rather than where they're first passed in, in case this is used as a package args = Args ( ) args . output_path = output_path args . phonemic = phonemic args . semantic = semantic args . source_file_path = source_file_path args . quiet = quiet args . similarity_file = similarity_file args . threshold = threshold args = validate_arguments ( args ) if args . phonemic : response_category = args . phonemic output_prefix = os . path . basename ( args . source_file_path ) . split ( '.' ) [ 0 ] + "_vfclust_phonemic_" + args . phonemic elif args . semantic : response_category = args . semantic output_prefix = os . path . basename ( args . source_file_path ) . split ( '.' ) [ 0 ] + "_vfclust_semantic_" + args . semantic else : response_category = "" output_prefix = "" if args . output_path : #want to output csv file target_file_path = os . path . join ( args . output_path , output_prefix + '.csv' ) else : #no output to system target_file_path = False engine = VFClustEngine ( response_category = response_category , response_file_path = args . source_file_path , target_file_path = target_file_path , quiet = args . quiet , similarity_file = args . similarity_file , threshold = args . threshold ) return dict ( engine . measures ) | Parses input arguments and runs clustering algorithm . | 385 | 11 |
13,059 | def create_from_textgrid ( self , word_list ) : self . timing_included = True for i , entry in enumerate ( word_list ) : self . unit_list . append ( Unit ( entry , format = "TextGrid" , type = self . type , index_in_timed_response = i ) ) # combine compound words, remove pluralizations, etc if self . type == "SEMANTIC" : self . lemmatize ( ) self . tokenize ( ) | Fills the ParsedResponse object with a list of TextGrid . Word objects originally from a . TextGrid file . | 109 | 24 |
13,060 | def lemmatize ( self ) : for unit in self . unit_list : if lemmatizer . lemmatize ( unit . text ) in self . lemmas : unit . text = lemmatizer . lemmatize ( unit . text ) | Lemmatize all Units in self . unit_list . | 58 | 13 |
13,061 | def tokenize ( self ) : if not self . quiet : print print "Finding compound words..." # lists of animal names containing 2-5 separate words compound_word_dict = { } for compound_length in range ( 5 , 1 , - 1 ) : compound_word_dict [ compound_length ] = [ name for name in self . names if len ( name . split ( ) ) == compound_length ] current_index = 0 finished = False while not finished : for compound_length in range ( 5 , 1 , - 1 ) : #[5, 4, 3, 2] if current_index + compound_length - 1 < len ( self . unit_list ) : #don't want to overstep bounds of the list compound_word = "" #create compound word for word in self . unit_list [ current_index : current_index + compound_length ] : compound_word += " " + word . text compound_word = compound_word . strip ( ) # remove initial white space #check if compound word is in list if compound_word in compound_word_dict [ compound_length ] : #if so, create the compound word self . make_compound_word ( start_index = current_index , how_many = compound_length ) current_index += 1 break else : #if no breaks for any number of words current_index += 1 if current_index >= len ( self . unit_list ) : # check here instead of at the top in case # changing the unit list length introduces a bug finished = True | Tokenizes all multiword names in the list of Units . | 327 | 12 |
13,062 | def make_compound_word ( self , start_index , how_many ) : if not self . quiet : compound_word = "" for word in self . unit_list [ start_index : start_index + how_many ] : compound_word += " " + word . text print compound_word . strip ( ) , "-->" , "_" . join ( compound_word . split ( ) ) #combine text for other_unit in range ( 1 , how_many ) : self . unit_list [ start_index ] . original_text . append ( self . unit_list [ start_index + other_unit ] . text ) self . unit_list [ start_index ] . text += "_" + self . unit_list [ start_index + other_unit ] . text #start time is the same. End time is the end time of the LAST word self . unit_list [ start_index ] . end_time = self . unit_list [ start_index + how_many - 1 ] . end_time #shorten unit_list self . unit_list = self . unit_list [ : start_index + 1 ] + self . unit_list [ start_index + how_many : ] | Combines two Units in self . unit_list to make a compound word token . | 265 | 17 |
13,063 | def remove_unit ( self , index ) : if not self . quiet : print "Removing" , self . unit_list [ index ] . text self . unit_list . pop ( index ) | Removes the unit at the given index in self . unit_list . Does not modify any other units . | 42 | 22 |
13,064 | def combine_same_stem_units ( self , index ) : if not self . quiet : combined_word = "" for word in self . unit_list [ index : index + 2 ] : for original_word in word . original_text : combined_word += " " + original_word print combined_word . strip ( ) , "-->" , "/" . join ( combined_word . split ( ) ) # edit word list to reflect what words are represented by this unit self . unit_list [ index ] . original_text . append ( self . unit_list [ index + 1 ] . text ) #start time is the same. End time is the end time of the LAST word self . unit_list [ index ] . end_time = self . unit_list [ index + 1 ] . end_time # remove word with duplicate stem self . unit_list . pop ( index + 1 ) | Combines adjacent words with the same stem into a single unit . | 191 | 13 |
13,065 | def display ( self ) : table_list = [ ] table_list . append ( ( "Text" , "Orig. Text" , "Start time" , "End time" , "Phonetic" ) ) for unit in self . unit_list : table_list . append ( ( unit . text , "/" . join ( unit . original_text ) , unit . start_time , unit . end_time , unit . phonetic_representation ) ) print_table ( table_list ) | Pretty - prints the ParsedResponse to the screen . | 107 | 11 |
13,066 | def generate_phonetic_representation ( self , word ) : with NamedTemporaryFile ( ) as temp_file : # Write the word to a temp file temp_file . write ( word ) #todo - clean up this messy t2p path t2pargs = [ os . path . abspath ( os . path . join ( os . path . dirname ( __file__ ) , 't2p/t2p' ) ) , '-transcribe' , os . path . join ( data_path , 'cmudict.0.7a.tree' ) , temp_file . name ] temp_file . seek ( 0 ) output , error = subprocess . Popen ( t2pargs , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) . communicate ( ) output = output . split ( ) phonetic_representation = output [ 1 : ] return phonetic_representation | Returns a generated phonetic representation for a word . | 207 | 10 |
13,067 | def modify_phonetic_representation ( self , phonetic_representation ) : for i in range ( len ( phonetic_representation ) ) : # Remove numerical stress indicators phonetic_representation [ i ] = re . sub ( '\d+' , '' , phonetic_representation [ i ] ) multis = [ 'AA' , 'AE' , 'AH' , 'AO' , 'AW' , 'AY' , 'CH' , 'DH' , 'EH' , 'ER' , 'EY' , 'HH' , 'IH' , 'IY' , 'JH' , 'NG' , 'OW' , 'OY' , 'SH' , 'TH' , 'UH' , 'UW' , 'ZH' ] singles = [ 'a' , 'b' , 'c' , 'd' , 'e' , 'f' , 'g' , 'h' , 'i' , 'j' , 'k' , 'l' , 'm' , 'n' , 'o' , 'p' , 'q' , 'r' , 's' , 't' , 'u' , 'v' , 'w' ] for i in range ( len ( phonetic_representation ) ) : # Convert multicharacter phone symbols to arbitrary # single-character symbols if phonetic_representation [ i ] in multis : phonetic_representation [ i ] = singles [ multis . index ( phonetic_representation [ i ] ) ] phonetic_representation = '' . join ( phonetic_representation ) return phonetic_representation | Returns a compact phonetic representation given a CMUdict - formatted representation . | 358 | 15 |
13,068 | def clean ( self ) : if not self . quiet : print print "Preprocessing input..." print "Raw response:" print self . display ( ) if not self . quiet : print print "Cleaning words..." #weed out words not starting with the right letter or in the right category current_index = 0 while current_index < len ( self . unit_list ) : word = self . unit_list [ current_index ] . text if self . type == "PHONETIC" : test = ( word . startswith ( self . letter_or_category ) and #starts with required letter not word . endswith ( '-' ) and # Weed out word fragments '_' not in word and # Weed out, e.g., 'filledpause_um' word . lower ( ) in self . english_words ) #make sure the word is english elif self . type == "SEMANTIC" : test = word in self . permissible_words if not test : #if test fails remove word self . remove_unit ( index = current_index ) else : # otherwise just increment, but check to see if you're at the end of the list current_index += 1 #combine words with the same stem current_index = 0 finished = False while current_index < len ( self . unit_list ) - 1 : #don't combine for lists of length 0, 1 if stemmer . stem ( self . unit_list [ current_index ] . text ) == stemmer . stem ( self . unit_list [ current_index + 1 ] . text ) : #if same stem as next, merge next unit with current unit self . combine_same_stem_units ( index = current_index ) else : # if not same stem, increment index current_index += 1 #get phonetic representations if self . type == "PHONETIC" : for unit in self . unit_list : word = unit . text #get phonetic representation if word in self . cmudict : # If word in CMUdict, get its phonetic representation phonetic_representation = self . cmudict [ word ] if word not in self . cmudict : # Else, generate a phonetic representation for it phonetic_representation = self . generate_phonetic_representation ( word ) phonetic_representation = self . modify_phonetic_representation ( phonetic_representation ) unit . phonetic_representation = phonetic_representation if not self . quiet : print print "Cleaned response:" print self . display ( ) | Removes any Units that are not applicable given the current semantic or phonetic category . | 546 | 17 |
13,069 | def load_lsa_information ( self ) : if not ( 49 < int ( self . clustering_parameter ) < 101 ) : raise Exception ( 'Only LSA dimensionalities in the range 50-100' + ' are supported.' ) if not self . quiet : print "Loading LSA term vectors..." #the protocol2 used the pickle highest protocol and this one is a smaller file with open ( os . path . join ( data_path , self . category + '_' + os . path . join ( 'term_vector_dictionaries' , 'term_vectors_dict' + str ( self . clustering_parameter ) + '_cpickle.dat' ) ) , 'rb' ) as infile : self . term_vectors = pickle . load ( infile ) | Loads a dictionary from disk that maps permissible words to their LSA term vectors . | 173 | 17 |
13,070 | def get_similarity_measures ( self ) : if not self . quiet : print print "Computing" , self . current_similarity_measure , "similarity..." self . compute_similarity_scores ( ) | Helper function for computing similarity measures . | 49 | 7 |
13,071 | def get_raw_counts ( self ) : #for making the table at the end words = [ ] labels = [ ] words_said = set ( ) # Words like "polar_bear" as one semantically but two phonetically # Uncategorizable words are counted as asides for unit in self . parsed_response : word = unit . text test = False if self . type == "PHONETIC" : test = ( word . startswith ( self . letter ) and "T_" not in word and "E_" not in word and "!" not in word and # Weed out tags "FILLEDPAUSE_" not in word and # Weed out filled pauses not word . endswith ( '-' ) and # Weed out false starts word . lower ( ) in self . english_words ) #weed out non-words elif self . type == "SEMANTIC" : #automatically weed out all non-semantically-appropriate responses test = ( word in self . permissible_words ) if test : self . measures [ 'COUNT_total_words' ] += 1 self . measures [ 'COUNT_permissible_words' ] += 1 if any ( word == w for w in words_said ) : self . measures [ 'COUNT_exact_repetitions' ] += 1 labels . append ( 'EXACT REPETITION' ) elif any ( stemmer . stem ( word ) == stemmer . stem ( w ) for w in words_said ) : self . measures [ 'COUNT_stem_repetitions' ] += 1 labels . append ( 'STEM REPETITION' ) else : labels . append ( 'PERMISSIBLE WORD' ) words_said . add ( word ) words . append ( word ) elif word . lower ( ) . startswith ( 'e_' ) : self . measures [ 'COUNT_examiner_words' ] += 1 words . append ( word ) labels . append ( 'EXAMINER WORD' ) elif word . endswith ( '-' ) : self . measures [ 'COUNT_word_fragments' ] += 1 words . append ( word ) labels . append ( 'WORD FRAGMENT' ) elif word . lower ( ) . startswith ( 'filledpause' ) : self . measures [ 'COUNT_filled_pauses' ] += 1 words . append ( word ) labels . append ( 'FILLED PAUSE' ) elif word . lower ( ) not in [ '!sil' , 't_noise' , 't_cough' , 't_lipsmack' , 't_breath' ] : self . measures [ 'COUNT_total_words' ] += 1 self . measures [ 'COUNT_asides' ] += 1 words . append ( word ) labels . append ( 'ASIDE' ) if not self . quiet : print print "Labels:" print_table ( [ ( word , label ) for word , label in zip ( words , labels ) ] ) self . measures [ 'COUNT_unique_permissible_words' ] = self . measures [ 'COUNT_permissible_words' ] - self . measures [ 'COUNT_exact_repetitions' ] - self . measures [ 'COUNT_stem_repetitions' ] if not self . quiet : print print "Counts:" collection_measures = [ x for x in self . measures if x . startswith ( "COUNT_" ) ] collection_measures . sort ( ) if not self . quiet : print_table ( [ ( k , str ( self . measures [ k ] ) ) for k in collection_measures ] ) | Determines counts for unique words repetitions etc using the raw text response . | 799 | 16 |
13,072 | def compute_similarity_score ( self , unit1 , unit2 ) : if self . type == "PHONETIC" : word1 = unit1 . phonetic_representation word2 = unit2 . phonetic_representation if self . current_similarity_measure == "phone" : word1_length , word2_length = len ( word1 ) , len ( word2 ) if word1_length > word2_length : # Make sure n <= m, to use O(min(n,m)) space word1 , word2 = word2 , word1 word1_length , word2_length = word2_length , word1_length current = range ( word1_length + 1 ) for i in range ( 1 , word2_length + 1 ) : previous , current = current , [ i ] + [ 0 ] * word1_length for j in range ( 1 , word1_length + 1 ) : add , delete = previous [ j ] + 1 , current [ j - 1 ] + 1 change = previous [ j - 1 ] if word1 [ j - 1 ] != word2 [ i - 1 ] : change += 1 current [ j ] = min ( add , delete , change ) phonetic_similarity_score = 1 - current [ word1_length ] / word2_length return phonetic_similarity_score elif self . current_similarity_measure == "biphone" : if word1 [ : 2 ] == word2 [ : 2 ] or word1 [ - 2 : ] == word2 [ - 2 : ] : common_biphone_score = 1 else : common_biphone_score = 0 return common_biphone_score elif self . type == "SEMANTIC" : word1 = unit1 . text word2 = unit2 . text if self . current_similarity_measure == "lsa" : w1_vec = self . term_vectors [ word1 ] w2_vec = self . term_vectors [ word2 ] # semantic_relatedness_score = (numpy.dot(w1_vec, w2_vec) / # numpy.linalg.norm(w1_vec) / # numpy.linalg.norm(w2_vec)) dot = sum ( [ w1 * w2 for w1 , w2 in zip ( w1_vec , w2_vec ) ] ) norm1 = sqrt ( sum ( [ w * w for w in w1_vec ] ) ) norm2 = sqrt ( sum ( [ w * w for w in w2_vec ] ) ) semantic_relatedness_score = dot / ( norm1 * norm2 ) return semantic_relatedness_score elif self . current_similarity_measure == "custom" : #look it up in dict try : similarity = self . custom_similarity_scores [ ( word1 , word2 ) ] except KeyError : try : similarity = self . custom_similarity_scores [ ( word2 , word1 ) ] except KeyError : if word1 == word2 : return self . same_word_similarity #if they're the same word, they pass. This should only happen when checking with # non-adjacent words in the same cluster else : return 0 #if words aren't found, they are defined as dissimilar return similarity return None | Returns the similarity score between two words . | 738 | 8 |
13,073 | def compute_similarity_scores ( self ) : for i , unit in enumerate ( self . parsed_response ) : if i < len ( self . parsed_response ) - 1 : next_unit = self . parsed_response [ i + 1 ] self . similarity_scores . append ( self . compute_similarity_score ( unit , next_unit ) ) if not self . quiet : print self . current_similarity_measure , "similarity scores (adjacent) -- higher is closer:" table = [ ( "Word 1" , "Word 2" , "Score" ) ] + [ ( self . parsed_response [ i ] . text , self . parsed_response [ i + 1 ] . text , "{0:.3f}" . format ( round ( self . similarity_scores [ i ] , 2 ) ) ) for i in range ( len ( self . parsed_response ) - 1 ) ] print_table ( table ) | Produce a list of similarity scores for each contiguous pair in a response . | 205 | 15 |
13,074 | def compute_pairwise_similarity_score ( self ) : pairs = [ ] all_scores = [ ] for i , unit in enumerate ( self . parsed_response ) : for j , other_unit in enumerate ( self . parsed_response ) : if i != j : pair = ( i , j ) rev_pair = ( j , i ) if pair not in pairs and rev_pair not in pairs : score = self . compute_similarity_score ( unit , other_unit ) pairs . append ( pair ) pairs . append ( rev_pair ) all_scores . append ( score ) #remove any "same word" from the mean all_scores = [ i for i in all_scores if i != self . same_word_similarity ] self . measures [ "COLLECTION_" + self . current_similarity_measure + "_pairwise_similarity_score_mean" ] = get_mean ( all_scores ) if len ( pairs ) > 0 else 'NA' | Computes the average pairwise similarity score between all pairs of Units . | 221 | 14 |
13,075 | def compute_collection_measures ( self , no_singletons = False ) : prefix = "COLLECTION_" + self . current_similarity_measure + "_" + self . current_collection_type + "_" if no_singletons : prefix += "no_singletons_" if no_singletons : collection_sizes_temp = [ x for x in self . collection_sizes if x != 1 ] else : #include singletons collection_sizes_temp = self . collection_sizes self . measures [ prefix + 'count' ] = len ( collection_sizes_temp ) self . measures [ prefix + 'size_mean' ] = get_mean ( collection_sizes_temp ) if self . measures [ prefix + 'count' ] > 0 else 0 self . measures [ prefix + 'size_max' ] = max ( collection_sizes_temp ) if len ( collection_sizes_temp ) > 0 else 0 self . measures [ prefix + 'switch_count' ] = self . measures [ prefix + 'count' ] - 1 | Computes summaries of measures using the discovered collections . | 237 | 11 |
13,076 | def compute_duration_measures ( self ) : prefix = "TIMING_" + self . current_similarity_measure + "_" + self . current_collection_type + "_" if self . response_format == 'TextGrid' : self . compute_response_vowel_duration ( "TIMING_" ) #prefixes don't need collection or measure type self . compute_response_continuant_duration ( "TIMING_" ) self . compute_between_collection_interval_duration ( prefix ) self . compute_within_collection_interval_duration ( prefix ) #these give different values depending on whether singleton clusters are counted or not self . compute_within_collection_vowel_duration ( prefix , no_singletons = True ) self . compute_within_collection_continuant_duration ( prefix , no_singletons = True ) self . compute_within_collection_vowel_duration ( prefix , no_singletons = False ) self . compute_within_collection_continuant_duration ( prefix , no_singletons = False ) | Helper function for computing measures derived from timing information . | 243 | 10 |
13,077 | def compute_response_vowel_duration ( self , prefix ) : durations = [ ] for word in self . full_timed_response : if word . phones : for phone in word . phones : if phone . string in self . vowels : durations . append ( phone . end - phone . start ) self . measures [ prefix + 'response_vowel_duration_mean' ] = get_mean ( durations ) if len ( durations ) > 0 else 'NA' if not self . quiet : print "Mean response vowel duration:" , self . measures [ prefix + 'response_vowel_duration_mean' ] | Computes mean vowel duration in entire response . | 139 | 9 |
13,078 | def compute_between_collection_interval_duration ( self , prefix ) : durations = [ ] # duration of each collection for collection in self . collection_list : # Entry, with timing, in timed_response for first word in collection start = collection [ 0 ] . start_time # Entry, with timing, in timed_response for last word in collection end = collection [ - 1 ] . end_time durations . append ( ( start , end ) ) # calculation between-duration intervals interstices = [ durations [ i + 1 ] [ 0 ] - durations [ i ] [ 1 ] for i , d in enumerate ( durations [ : - 1 ] ) ] # Replace negative interstices (for overlapping clusters) with # interstices of duration 0 for i , entry in enumerate ( interstices ) : if interstices [ i ] < 0 : interstices [ i ] = 0 self . measures [ prefix + 'between_collection_interval_duration_mean' ] = get_mean ( interstices ) if len ( interstices ) > 0 else 'NA' if not self . quiet : print print self . current_similarity_measure + " between-" + self . current_collection_type + " durations" table = [ ( self . current_collection_type + " 1 (start,end)" , "Interval" , self . current_collection_type + " 2 (start,end)" ) ] + [ ( str ( d1 ) , str ( i1 ) , str ( d2 ) ) for d1 , i1 , d2 in zip ( durations [ : - 1 ] , interstices , durations [ 1 : ] ) ] print_table ( table ) print print "Mean " + self . current_similarity_measure + " between-" + self . current_collection_type + " duration" , self . measures [ prefix + 'between_collection_interval_duration_mean' ] | Calculates BETWEEN - collection intervals for the current collection and measure type and takes their mean . | 423 | 21 |
13,079 | def compute_within_collection_interval_duration ( self , prefix ) : interstices = [ ] for cluster in self . collection_list : # Make sure cluster is not a singleton if len ( cluster ) > 1 : for i in range ( len ( cluster ) ) : if i != len ( cluster ) - 1 : interstice = cluster [ i + 1 ] . start_time - cluster [ i ] . end_time interstices . append ( interstice ) self . measures [ prefix + 'within_collection_interval_duration_mean' ] = get_mean ( interstices ) if len ( interstices ) > 0 else 'NA' if not self . quiet : print "Mean within-" + self . current_similarity_measure + "-" + self . current_collection_type + " between-word duration:" , self . measures [ prefix + 'within_collection_interval_duration_mean' ] | Calculates mean between - word duration WITHIN collections . | 202 | 12 |
13,080 | def compute_within_collection_vowel_duration ( self , prefix , no_singletons = False ) : if no_singletons : min_size = 2 else : prefix += "no_singletons_" min_size = 1 durations = [ ] for cluster in self . collection_list : if len ( cluster ) >= min_size : for word in cluster : word = self . full_timed_response [ word . index_in_timed_response ] for phone in word . phones : if phone . string in self . vowels : durations . append ( phone . end - phone . start ) self . measures [ prefix + 'within_collection_vowel_duration_mean' ] = get_mean ( durations ) if len ( durations ) > 0 else 'NA' if not self . quiet : if no_singletons : print "Mean within-" + self . current_similarity_measure + "-" + self . current_collection_type + " vowel duration, excluding singletons:" , self . measures [ prefix + 'within_collection_vowel_duration_mean' ] else : print "Mean within-" + self . current_similarity_measure + "-" + self . current_collection_type + " vowel duration, including singletons:" , self . measures [ prefix + 'within_collection_vowel_duration_mean' ] | Computes the mean duration of vowels from Units within clusters . | 307 | 13 |
13,081 | def print_output ( self ) : if self . response_format == "csv" : for key in self . measures : if "TIMING_" in key : self . measures [ key ] = "NA" if not self . quiet : print print self . type . upper ( ) + " RESULTS:" keys = [ e for e in self . measures if 'COUNT_' in e ] keys . sort ( ) print "Counts:" print_table ( [ ( entry , str ( self . measures [ entry ] ) ) for entry in keys ] ) keys = [ e for e in self . measures if 'COLLECTION_' in e ] keys . sort ( ) print print "Collection measures:" print_table ( [ ( entry , str ( self . measures [ entry ] ) ) for entry in keys ] ) if self . response_format == "TextGrid" : keys = [ e for e in self . measures if 'TIMING_' in e ] keys . sort ( ) print print "Time-based measures:" print_table ( [ ( entry , str ( self . measures [ entry ] ) ) for entry in keys ] ) #write to CSV file if self . target_file : with open ( self . target_file , 'w' ) as outfile : header = [ 'file_id' ] + [ self . type + "_" + e for e in self . measures if 'COUNT_' in e ] + [ self . type + "_" + e for e in self . measures if 'COLLECTION_' in e ] + [ self . type + "_" + e for e in self . measures if 'TIMING_' in e ] writer = csv . writer ( outfile , quoting = csv . QUOTE_MINIMAL ) writer . writerow ( header ) #the split/join gets rid of the type appended just above writer . writerow ( [ self . measures [ "file_id" ] ] + [ self . measures [ "_" . join ( e . split ( '_' ) [ 1 : ] ) ] for e in header [ 1 : ] ] ) | Outputs final list of measures to screen a csv file . | 453 | 13 |
13,082 | def insert_child ( self , child_pid , index = - 1 ) : if child_pid . status != PIDStatus . REGISTERED : raise PIDRelationConsistencyError ( "Version PIDs should have status 'REGISTERED'. Use " "insert_draft_child to insert 'RESERVED' draft PID." ) with db . session . begin_nested ( ) : # if there is a draft and "child" is inserted as the last version, # it should be inserted before the draft. draft = self . draft_child if draft and index == - 1 : index = self . index ( draft ) super ( PIDNodeVersioning , self ) . insert_child ( child_pid , index = index ) self . update_redirect ( ) | Insert a Version child PID . | 163 | 6 |
13,083 | def remove_child ( self , child_pid ) : if child_pid . status == PIDStatus . RESERVED : raise PIDRelationConsistencyError ( "Version PIDs should not have status 'RESERVED'. Use " "remove_draft_child to remove a draft PID." ) with db . session . begin_nested ( ) : super ( PIDNodeVersioning , self ) . remove_child ( child_pid , reorder = True ) self . update_redirect ( ) | Remove a Version child PID . | 108 | 6 |
13,084 | def insert_draft_child ( self , child_pid ) : if child_pid . status != PIDStatus . RESERVED : raise PIDRelationConsistencyError ( "Draft child should have status 'RESERVED'" ) if not self . draft_child : with db . session . begin_nested ( ) : super ( PIDNodeVersioning , self ) . insert_child ( child_pid , index = - 1 ) else : raise PIDRelationConsistencyError ( "Draft child already exists for this relation: {0}" . format ( self . draft_child ) ) | Insert a draft child to versioning . | 127 | 8 |
13,085 | def remove_draft_child ( self ) : if self . draft_child : with db . session . begin_nested ( ) : super ( PIDNodeVersioning , self ) . remove_child ( self . draft_child , reorder = True ) | Remove the draft child from versioning . | 54 | 8 |
13,086 | def update_redirect ( self ) : if self . last_child : self . _resolved_pid . redirect ( self . last_child ) elif any ( map ( lambda pid : pid . status not in [ PIDStatus . DELETED , PIDStatus . REGISTERED , PIDStatus . RESERVED ] , super ( PIDNodeVersioning , self ) . children . all ( ) ) ) : raise PIDRelationConsistencyError ( "Invalid relation state. Only REGISTERED, RESERVED " "and DELETED PIDs are supported." ) | Update the parent redirect to the current last child . | 123 | 10 |
13,087 | def feedback ( request ) : if request . method == 'GET' : return render ( request , 'feedback_feedback.html' , { } , help_text = feedback . __doc__ ) if request . method == 'POST' : feedback_data = json_body ( request . body . decode ( "utf-8" ) ) feedback_data [ 'user_agent' ] = Session . objects . get_current_session ( ) . http_user_agent . content if not feedback_data . get ( 'username' ) : feedback_data [ 'username' ] = request . user . username if not feedback_data . get ( 'email' ) : feedback_data [ 'email' ] = request . user . email comment = Comment . objects . create ( username = feedback_data [ 'username' ] , email = feedback_data [ 'email' ] , text = feedback_data [ 'text' ] ) if get_config ( 'proso_feedback' , 'send_emails' , default = True ) : feedback_domain = get_config ( 'proso_feedback' , 'domain' , required = True ) feedback_to = get_config ( 'proso_feedback' , 'to' , required = True ) if is_likely_worthless ( feedback_data ) : mail_from = 'spam@' + feedback_domain else : mail_from = 'feedback@' + feedback_domain text_content = render_to_string ( "emails/feedback.plain.txt" , { "feedback" : feedback_data , "user" : request . user , } ) html_content = render_to_string ( "emails/feedback.html" , { "feedback" : feedback_data , "user" : request . user , } ) subject = feedback_domain + ' feedback ' + str ( comment . id ) mail = EmailMultiAlternatives ( subject , text_content , mail_from , feedback_to , ) mail . attach_alternative ( html_content , "text/html" ) mail . send ( ) LOGGER . debug ( "email sent %s\n" , text_content ) return HttpResponse ( 'ok' , status = 201 ) else : return HttpResponseBadRequest ( "method %s is not allowed" . format ( request . method ) ) | Send feedback to the authors of the system . | 510 | 9 |
13,088 | def rating ( request ) : if request . method == 'GET' : return render ( request , 'feedback_rating.html' , { } , help_text = rating . __doc__ ) if request . method == 'POST' : data = json_body ( request . body . decode ( "utf-8" ) ) if data [ 'value' ] not in list ( range ( 1 , 9 ) ) : return render_json ( request , { 'error' : _ ( 'The given value is not valid.' ) , 'error_type' : 'invalid_value' } , template = 'feedback_json.html' , status = 400 ) rating_object = Rating ( user = request . user , value = data [ 'value' ] , ) rating_object . save ( ) return HttpResponse ( 'ok' , status = 201 ) else : return HttpResponseBadRequest ( "method %s is not allowed" . format ( request . method ) ) | Rate the current practice . | 209 | 5 |
13,089 | def colour ( colour , message , bold = False ) : return style ( fg = colour , text = message , bold = bold ) | Color a message | 28 | 3 |
13,090 | def customFilter ( self , filterFunc ) : ret = self . __class__ ( ) for item in self : if filterFunc ( item ) : ret . append ( item ) return ret | customFilter - Apply a custom filter to elements and return a QueryableList of matches | 41 | 17 |
13,091 | def sort_by ( self , fieldName , reverse = False ) : return self . __class__ ( sorted ( self , key = lambda item : self . _get_item_value ( item , fieldName ) , reverse = reverse ) ) | sort_by - Return a copy of this collection sorted by the given fieldName . | 51 | 17 |
13,092 | def uri ( self ) : return self . uri_template . format ( host = self . host , port = "" if self . port is None else self . port , database = self . database , username = self . username , password = "" if self . password is None else self . password , has_password = "" if self . password is None else ":" , has_port = "" if self . port is None else ":" , ) | Return sqlalchemy connect string URI . | 94 | 8 |
13,093 | def from_json ( cls , json_file , json_path = None , key_mapping = None ) : cls . _validate_key_mapping ( key_mapping ) with open ( json_file , "rb" ) as f : data = json . loads ( f . read ( ) . decode ( "utf-8" ) ) return cls . _from_json_data ( data , json_path , key_mapping ) | Load connection credential from json file . | 100 | 7 |
13,094 | def from_s3_json ( cls , bucket_name , key , json_path = None , key_mapping = None , aws_profile = None , aws_access_key_id = None , aws_secret_access_key = None , region_name = None ) : # pragma: no cover import boto3 ses = boto3 . Session ( aws_access_key_id = aws_access_key_id , aws_secret_access_key = aws_secret_access_key , region_name = region_name , profile_name = aws_profile , ) s3 = ses . resource ( "s3" ) bucket = s3 . Bucket ( bucket_name ) object = bucket . Object ( key ) data = json . loads ( object . get ( ) [ "Body" ] . read ( ) . decode ( "utf-8" ) ) return cls . _from_json_data ( data , json_path , key_mapping ) | Load database credential from json on s3 . | 223 | 9 |
13,095 | def from_env ( cls , prefix , kms_decrypt = False , aws_profile = None ) : if len ( prefix ) < 1 : raise ValueError ( "prefix can't be empty" ) if len ( set ( prefix ) . difference ( set ( string . ascii_uppercase + "_" ) ) ) : raise ValueError ( "prefix can only use [A-Z] and '_'!" ) if not prefix . endswith ( "_" ) : prefix = prefix + "_" data = dict ( host = os . getenv ( prefix + "HOST" ) , port = os . getenv ( prefix + "PORT" ) , database = os . getenv ( prefix + "DATABASE" ) , username = os . getenv ( prefix + "USERNAME" ) , password = os . getenv ( prefix + "PASSWORD" ) , ) if kms_decrypt is True : # pragma: no cover import boto3 from base64 import b64decode if aws_profile is not None : kms = boto3 . client ( "kms" ) else : ses = boto3 . Session ( profile_name = aws_profile ) kms = ses . client ( "kms" ) def decrypt ( kms , text ) : return kms . decrypt ( CiphertextBlob = b64decode ( text . encode ( "utf-8" ) ) ) [ "Plaintext" ] . decode ( "utf-8" ) data = { key : value if value is None else decrypt ( kms , str ( value ) ) for key , value in data . items ( ) } return cls ( * * data ) | Load database credential from env variable . | 370 | 7 |
13,096 | def to_dict ( self ) : return dict ( host = self . host , port = self . port , database = self . database , username = self . username , password = self . password , ) | Convert credentials into a dict . | 42 | 7 |
13,097 | def start_debugging ( ) : exc_type , exc_value , exc_tb = sys . exc_info ( ) # If the exception has been annotated to be re-raised, raise the exception if hasattr ( exc_value , '_ipdbugger_let_raise' ) : raise_ ( * sys . exc_info ( ) ) print ( ) for line in traceback . format_exception ( exc_type , exc_value , exc_tb ) : print ( colored ( line , 'red' ) , end = ' ' ) # Get the frame with the error. test_frame = sys . _getframe ( - 1 ) . f_back from ipdb . __main__ import wrap_sys_excepthook wrap_sys_excepthook ( ) IPDBugger ( exc_info = sys . exc_info ( ) ) . set_trace ( test_frame ) | Start a debugging session after catching an exception . | 201 | 9 |
13,098 | def get_last_lineno ( node ) : max_lineno = 0 if hasattr ( node , "lineno" ) : max_lineno = node . lineno for _ , field in ast . iter_fields ( node ) : if isinstance ( field , list ) : for value in field : if isinstance ( value , ast . AST ) : max_lineno = max ( max_lineno , get_last_lineno ( value ) ) elif isinstance ( field , ast . AST ) : max_lineno = max ( max_lineno , get_last_lineno ( field ) ) return max_lineno | Recursively find the last line number of the ast node . | 138 | 13 |
13,099 | def do_raise ( self , arg ) : self . do_continue ( arg ) # Annotating the exception for a continual re-raise _ , exc_value , _ = self . exc_info exc_value . _ipdbugger_let_raise = True raise_ ( * self . exc_info ) | Raise the last exception caught . | 68 | 7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.