idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
15,500 | def set_attributes_from_headers ( self , headers ) : self . total_count = headers . get ( 'x-total-count' , None ) self . current_page = headers . get ( 'x-current-page' , None ) self . per_page = headers . get ( 'x-per-page' , None ) self . user_type = headers . get ( 'x-user-type' , None ) if self . total_count : self . total_count = int ( self . total_count ) if self . current_page : self . current_page = int ( self . current_page ) if self . per_page : self . per_page = int ( self . per_page ) | Set instance attributes with HTTP header | 158 | 6 |
15,501 | def _validate_base_classes ( meta , bases ) : for base in bases : if meta . _is_final ( base ) : raise ClassError ( "cannot inherit from @final class %s" % ( base . __name__ , ) ) | Validate the base classes of the new class to be created making sure none of them are | 55 | 18 |
15,502 | def _validate_method_decoration ( meta , class_ ) : # TODO(xion): employ some code inspection tricks to serve ClassErrors # as if they were thrown at the offending class's/method's definition super_mro = class_ . __mro__ [ 1 : ] own_methods = ( ( name , member ) for name , member in class_ . __dict__ . items ( ) if is_method ( member ) ) # check that ``@override`` modifier is present where it should be # and absent where it shouldn't (e.g. ``@final`` methods) for name , method in own_methods : shadowed_method , base_class = next ( ( ( getattr ( base , name ) , base ) for base in super_mro if hasattr ( base , name ) ) , ( None , None ) ) if meta . _is_override ( method ) : # ``@override`` is legal only when the method actually shadows # a method from a superclass, and that metod is not ``@final`` if not shadowed_method : raise ClassError ( "unnecessary @override on %s.%s" % ( class_ . __name__ , name ) , class_ = class_ ) if meta . _is_final ( shadowed_method ) : raise ClassError ( "illegal @override on a @final method %s.%s" % ( base_class . __name__ , name ) , class_ = class_ ) # if @override had parameter supplied, verify if it was # the same class as the base of shadowed method override_base = meta . _get_override_base ( method ) if override_base and base_class is not override_base : if is_class ( override_base ) : raise ClassError ( "incorrect override base: expected %s, got %s" % ( base_class . __name__ , override_base . __name__ ) ) else : raise ClassError ( "invalid override base specified: %s" % ( override_base , ) ) setattr ( class_ , name , method . method ) else : if shadowed_method and name not in meta . OVERRIDE_EXEMPTIONS : if meta . _is_final ( shadowed_method ) : msg = "%s.%s is hiding a @final method %s.%s" % ( class_ . __name__ , name , base_class . __name__ , name ) else : msg = ( "overridden method %s.%s " "must be marked with @override" % ( class_ . __name__ , name ) ) raise ClassError ( msg , class_ = class_ ) | Validate the usage of | 587 | 5 |
15,503 | def _is_final ( meta , arg ) : if inspect . isclass ( arg ) and not isinstance ( arg , ObjectMetaclass ) : return False # of classes, only subclasses of Object can be final # account for method wrappers, such as the one introduced by @override from taipan . objective . modifiers import _WrappedMethod if isinstance ( arg , _WrappedMethod ) : arg = arg . method return getattr ( arg , '__final__' , False ) | Checks whether given class or method has been marked with the | 106 | 12 |
15,504 | def _is_override ( meta , method ) : from taipan . objective . modifiers import _OverriddenMethod return isinstance ( method , _OverriddenMethod ) | Checks whether given class or instance method has been marked with the | 36 | 13 |
15,505 | def trace_dependencies ( req , requirement_set , dependencies , _visited = None ) : _visited = _visited or set ( ) if req in _visited : return _visited . add ( req ) for reqName in req . requirements ( ) : try : name = pkg_resources . Requirement . parse ( reqName ) . project_name except ValueError , e : logger . error ( 'Invalid requirement: %r (%s) in requirement %s' % ( reqName , e , req ) ) continue subreq = requirement_set . get_requirement ( name ) dependencies . append ( ( req , subreq ) ) trace_dependencies ( subreq , requirement_set , dependencies , _visited ) | Trace all dependency relationship | 157 | 5 |
15,506 | def pad_zeroes ( addr , n_zeroes ) : if len ( addr ) < n_zeroes : return pad_zeroes ( "0" + addr , n_zeroes ) return addr | Padds the address with zeroes | 44 | 9 |
15,507 | def next_addr ( addr , i ) : str_addr = pad_zeroes ( str ( int_addr ( addr ) + i ) , len ( addr [ 1 : ] ) ) return addr [ 0 ] + str_addr | Gets address after the current + i | 49 | 8 |
15,508 | def mark_address ( self , addr , size ) : i = 0 while i < size : self . _register_map [ addr ] = True i += 1 | Marks address as being used in simulator | 34 | 8 |
15,509 | def next_address_avoid_collision ( self , start_addr ) : i = 1 while self . is_address_in_use ( next_addr ( start_addr , i ) ) : i += 1 return next_addr ( start_addr , i ) | Finds the next address recursively which does not collide with any other address | 57 | 16 |
15,510 | def move_to_next_bit_address ( self ) : self . _current_bit_address = self . next_bit_address ( ) self . mark_address ( self . _current_bit_address . split ( '.' ) [ 0 ] , self . _size_of_current_register_address ) | Moves to next available bit address position | 69 | 8 |
15,511 | def next_bit_address ( self ) : if self . _current_bit_address == "" : if self . _is_16bit : return "{0}.{1}" . format ( self . next_address ( ) , "00" ) return "{0}.{1}" . format ( self . next_address ( ) , "0" ) if self . _is_16bit : bool_half = int ( self . _current_bit_address . split ( "." ) [ 1 ] ) if bool_half < 4 : register_half = self . _current_bit_address . split ( "." ) [ 0 ] return "{0}.{1}" . format ( register_half , pad_zeroes ( str ( bool_half + 1 ) , 2 ) ) self . move_to_next_address ( self . _size_of_current_register_address ) return "{0}.{1}" . format ( self . next_address ( ) , "00" ) bool_half = int ( self . _current_bit_address . split ( "." ) [ 1 ] ) if bool_half < 3 : register_half = self . _current_bit_address . split ( "." ) [ 0 ] return "{0}.{1}" . format ( register_half , bool_half + 1 ) self . move_to_next_address ( self . _size_of_current_register_address ) return "{0}.{1}" . format ( self . next_address ( ) , "0" ) | Gets the next boolean address | 329 | 6 |
15,512 | def route_election ( self , election ) : if ( election . election_type . slug == ElectionType . GENERAL or ElectionType . GENERAL_RUNOFF ) : self . bootstrap_general_election ( election ) elif election . race . special : self . bootstrap_special_election ( election ) if election . race . office . is_executive : self . bootstrap_executive_office ( election ) else : self . bootstrap_legislative_office ( election ) | Legislative or executive office? | 104 | 7 |
15,513 | def get_status ( * nrs ) : # If we called get_status with one single bug, we get a single bug, # if we called it with a list of bugs, we get a list, # No available bugreports returns an empty list bugs = [ ] list_ = [ ] for nr in nrs : if isinstance ( nr , list ) : list_ . extend ( nr ) else : list_ . append ( nr ) # Process the input in batches to avoid hitting resource limits on the BTS soap_client = _build_soap_client ( ) for i in range ( 0 , len ( list_ ) , BATCH_SIZE ) : slice_ = list_ [ i : i + BATCH_SIZE ] # I build body by hand, pysimplesoap doesn't generate soap Arrays # without using wsdl method_el = SimpleXMLElement ( '<get_status></get_status>' ) _build_int_array_el ( 'arg0' , method_el , slice_ ) reply = soap_client . call ( 'get_status' , method_el ) for bug_item_el in reply ( 's-gensym3' ) . children ( ) or [ ] : bug_el = bug_item_el . children ( ) [ 1 ] bugs . append ( _parse_status ( bug_el ) ) return bugs | Returns a list of Bugreport objects . | 302 | 8 |
15,514 | def get_usertag ( email , * tags ) : reply = _soap_client_call ( 'get_usertag' , email , * tags ) map_el = reply ( 's-gensym3' ) mapping = { } # element <s-gensys3> in response can have standard type # xsi:type=apachens:Map (example, for email debian-python@lists.debian.org) # OR no type, in this case keys are the names of child elements and # the array is contained in the child elements type_attr = map_el . attributes ( ) . get ( 'xsi:type' ) if type_attr and type_attr . value == 'apachens:Map' : for usertag_el in map_el . children ( ) or [ ] : tag = _uc ( str ( usertag_el ( 'key' ) ) ) buglist_el = usertag_el ( 'value' ) mapping [ tag ] = [ int ( bug ) for bug in buglist_el . children ( ) or [ ] ] else : for usertag_el in map_el . children ( ) or [ ] : tag = _uc ( usertag_el . get_name ( ) ) mapping [ tag ] = [ int ( bug ) for bug in usertag_el . children ( ) or [ ] ] return mapping | Get buglists by usertags . | 306 | 9 |
15,515 | def get_bug_log ( nr ) : reply = _soap_client_call ( 'get_bug_log' , nr ) items_el = reply ( 'soapenc:Array' ) buglogs = [ ] for buglog_el in items_el . children ( ) : buglog = { } buglog [ "header" ] = _parse_string_el ( buglog_el ( "header" ) ) buglog [ "body" ] = _parse_string_el ( buglog_el ( "body" ) ) buglog [ "msg_num" ] = int ( buglog_el ( "msg_num" ) ) # server always returns an empty attachments array ? buglog [ "attachments" ] = [ ] mail_parser = email . feedparser . FeedParser ( ) mail_parser . feed ( buglog [ "header" ] ) mail_parser . feed ( "\n\n" ) mail_parser . feed ( buglog [ "body" ] ) buglog [ "message" ] = mail_parser . close ( ) buglogs . append ( buglog ) return buglogs | Get Buglogs . | 259 | 5 |
15,516 | def newest_bugs ( amount ) : reply = _soap_client_call ( 'newest_bugs' , amount ) items_el = reply ( 'soapenc:Array' ) return [ int ( item_el ) for item_el in items_el . children ( ) or [ ] ] | Returns the newest bugs . | 65 | 5 |
15,517 | def get_bugs ( * key_value ) : # previous versions also accepted # get_bugs(['package', 'gtk-qt-engine', 'severity', 'normal']) # if key_value is a list in a one elemented tuple, remove the # wrapping list if len ( key_value ) == 1 and isinstance ( key_value [ 0 ] , list ) : key_value = tuple ( key_value [ 0 ] ) # pysimplesoap doesn't generate soap Arrays without using wsdl # I build body by hand, converting list to array and using standard # pysimplesoap marshalling for other types method_el = SimpleXMLElement ( '<get_bugs></get_bugs>' ) for arg_n , kv in enumerate ( key_value ) : arg_name = 'arg' + str ( arg_n ) if isinstance ( kv , ( list , tuple ) ) : _build_int_array_el ( arg_name , method_el , kv ) else : method_el . marshall ( arg_name , kv ) soap_client = _build_soap_client ( ) reply = soap_client . call ( 'get_bugs' , method_el ) items_el = reply ( 'soapenc:Array' ) return [ int ( item_el ) for item_el in items_el . children ( ) or [ ] ] | Get list of bugs matching certain criteria . | 310 | 8 |
15,518 | def _parse_status ( bug_el ) : bug = Bugreport ( ) # plain fields for field in ( 'originator' , 'subject' , 'msgid' , 'package' , 'severity' , 'owner' , 'summary' , 'location' , 'source' , 'pending' , 'forwarded' ) : setattr ( bug , field , _parse_string_el ( bug_el ( field ) ) ) bug . date = datetime . utcfromtimestamp ( float ( bug_el ( 'date' ) ) ) bug . log_modified = datetime . utcfromtimestamp ( float ( bug_el ( 'log_modified' ) ) ) bug . tags = [ _uc ( tag ) for tag in str ( bug_el ( 'tags' ) ) . split ( ) ] bug . done = _parse_bool ( bug_el ( 'done' ) ) bug . archived = _parse_bool ( bug_el ( 'archived' ) ) bug . unarchived = _parse_bool ( bug_el ( 'unarchived' ) ) bug . bug_num = int ( bug_el ( 'bug_num' ) ) bug . mergedwith = [ int ( i ) for i in str ( bug_el ( 'mergedwith' ) ) . split ( ) ] bug . blockedby = [ int ( i ) for i in str ( bug_el ( 'blockedby' ) ) . split ( ) ] bug . blocks = [ int ( i ) for i in str ( bug_el ( 'blocks' ) ) . split ( ) ] bug . found_versions = [ _uc ( str ( el ) ) for el in bug_el ( 'found_versions' ) . children ( ) or [ ] ] bug . fixed_versions = [ _uc ( str ( el ) ) for el in bug_el ( 'fixed_versions' ) . children ( ) or [ ] ] affects = [ _f for _f in str ( bug_el ( 'affects' ) ) . split ( ',' ) if _f ] bug . affects = [ _uc ( a ) . strip ( ) for a in affects ] # Also available, but unused or broken # bug.keywords = [_uc(keyword) for keyword in # str(bug_el('keywords')).split()] # bug.fixed = _parse_crappy_soap(tmp, "fixed") # bug.found = _parse_crappy_soap(tmp, "found") # bug.found_date = \ # [datetime.utcfromtimestamp(i) for i in tmp["found_date"]] # bug.fixed_date = \ # [datetime.utcfromtimestamp(i) for i in tmp["fixed_date"]] return bug | Return a bugreport object from a given status xml element | 612 | 11 |
15,519 | def _convert_soap_method_args ( * args ) : soap_args = [ ] for arg_n , arg in enumerate ( args ) : soap_args . append ( ( 'arg' + str ( arg_n ) , arg ) ) return soap_args | Convert arguments to be consumed by a SoapClient method | 60 | 12 |
15,520 | def _soap_client_call ( method_name , * args ) : # a new client instance is built for threading issues soap_client = _build_soap_client ( ) soap_args = _convert_soap_method_args ( * args ) # if pysimplesoap version requires it, apply a workaround for # https://github.com/pysimplesoap/pysimplesoap/issues/31 if PYSIMPLESOAP_1_16_2 : return getattr ( soap_client , method_name ) ( * soap_args ) else : return getattr ( soap_client , method_name ) ( soap_client , * soap_args ) | Wrapper to call SoapClient method | 156 | 8 |
15,521 | def _parse_string_el ( el ) : value = str ( el ) el_type = el . attributes ( ) . get ( 'xsi:type' ) if el_type and el_type . value == 'xsd:base64Binary' : value = base64 . b64decode ( value ) if not PY2 : value = value . decode ( 'utf-8' , errors = 'replace' ) value = _uc ( value ) return value | read a string element maybe encoded in base64 | 102 | 9 |
15,522 | def get_solc_input ( self ) : def legal ( r , file_name ) : hidden = file_name [ 0 ] == '.' dotsol = len ( file_name ) > 3 and file_name [ - 4 : ] == '.sol' path = os . path . normpath ( os . path . join ( r , file_name ) ) notfile = not os . path . isfile ( path ) symlink = Path ( path ) . is_symlink ( ) return dotsol and ( not ( symlink or hidden or notfile ) ) solc_input = { 'language' : 'Solidity' , 'sources' : { file_name : { 'urls' : [ os . path . realpath ( os . path . join ( r , file_name ) ) ] } for r , d , f in os . walk ( self . contracts_dir ) for file_name in f if legal ( r , file_name ) } , 'settings' : { 'optimizer' : { 'enabled' : 1 , 'runs' : 10000 } , 'outputSelection' : { "*" : { "" : [ "legacyAST" , "ast" ] , "*" : [ "abi" , "evm.bytecode.object" , "evm.bytecode.sourceMap" , "evm.deployedBytecode.object" , "evm.deployedBytecode.sourceMap" ] } } } } return solc_input | Walks the contract directory and returns a Solidity input dict | 328 | 12 |
15,523 | def compile_all ( self ) : # Solidity input JSON solc_input = self . get_solc_input ( ) # Compile the contracts real_path = os . path . realpath ( self . contracts_dir ) compilation_result = compile_standard ( solc_input , allow_paths = real_path ) # Create the output folder if it doesn't already exist os . makedirs ( self . output_dir , exist_ok = True ) # Write the contract ABI to output files compiled_contracts = compilation_result [ 'contracts' ] for contract_file in compiled_contracts : for contract in compiled_contracts [ contract_file ] : contract_name = contract . split ( '.' ) [ 0 ] contract_data = compiled_contracts [ contract_file ] [ contract_name ] contract_data_path = self . output_dir + '/{0}.json' . format ( contract_name ) with open ( contract_data_path , "w+" ) as contract_data_file : json . dump ( contract_data , contract_data_file ) | Compiles all of the contracts in the self . contracts_dir directory | 239 | 14 |
15,524 | def get_contract_data ( self , contract_name ) : contract_data_path = self . output_dir + '/{0}.json' . format ( contract_name ) with open ( contract_data_path , 'r' ) as contract_data_file : contract_data = json . load ( contract_data_file ) abi = contract_data [ 'abi' ] bytecode = contract_data [ 'evm' ] [ 'bytecode' ] [ 'object' ] return abi , bytecode | Returns the contract data for a given contract | 113 | 8 |
15,525 | def exception ( maxTBlevel = None ) : try : from marrow . util . bunch import Bunch cls , exc , trbk = sys . exc_info ( ) excName = cls . __name__ excArgs = getattr ( exc , 'args' , None ) excTb = '' . join ( traceback . format_exception ( cls , exc , trbk , maxTBlevel ) ) return Bunch ( name = excName , cls = cls , exception = exc , trace = trbk , formatted = excTb , args = excArgs ) finally : del cls , exc , trbk | Retrieve useful information about an exception . | 137 | 8 |
15,526 | def native ( s , encoding = 'utf-8' , fallback = 'iso-8859-1' ) : if isinstance ( s , str ) : return s if str is unicode : # Python 3.x -> return unicodestr ( s , encoding , fallback ) return bytestring ( s , encoding , fallback ) | Convert a given string into a native string . | 74 | 10 |
15,527 | def unicodestr ( s , encoding = 'utf-8' , fallback = 'iso-8859-1' ) : if isinstance ( s , unicode ) : return s try : return s . decode ( encoding ) except UnicodeError : return s . decode ( fallback ) | Convert a string to unicode if it isn t already . | 62 | 13 |
15,528 | def uvalues ( a , encoding = 'utf-8' , fallback = 'iso-8859-1' ) : try : return encoding , [ s . decode ( encoding ) for s in a ] except UnicodeError : return fallback , [ s . decode ( fallback ) for s in a ] | Return a list of decoded values from an iterator . | 65 | 11 |
15,529 | def _build_query ( self ) : if isinstance ( self . _query_string , QueryString ) : self . _query_dsl = self . _query_string elif isinstance ( self . _query_string , string_types ) : self . _query_dsl = QueryString ( self . _query_string ) else : self . _query_dsl = MatchAll ( ) | Build the base query dictionary | 87 | 5 |
15,530 | def _build_filtered_query ( self , f , operator ) : self . _filtered = True if isinstance ( f , Filter ) : filter_object = f else : filter_object = Filter ( operator ) . filter ( f ) self . _filter_dsl = filter_object | Create the root of the filter tree | 63 | 7 |
15,531 | def filter ( self , f , operator = "and" ) : if self . _filtered : self . _filter_dsl . filter ( f ) else : self . _build_filtered_query ( f , operator ) return self | Add a filter to the query | 51 | 6 |
15,532 | def check ( self , inst , value ) : if not ( self . or_none and value is None ) : if self . seq : self . checktype_seq ( value , self . kind , unique = self . unique , inst = inst ) else : self . checktype ( value , self . kind , inst = inst ) | Raise TypeError if value doesn t satisfy the constraints for use on instance inst . | 69 | 17 |
15,533 | def normalize ( self , inst , value ) : if ( not ( self . or_none and value is None ) and self . seq ) : value = tuple ( value ) return value | Return value or a normalized form of it for use on instance inst . | 39 | 14 |
15,534 | def plot_decision_boundary ( model , X , y , step = 0.1 , figsize = ( 10 , 8 ) , alpha = 0.4 , size = 20 ) : x_min , x_max = X [ : , 0 ] . min ( ) - 1 , X [ : , 0 ] . max ( ) + 1 y_min , y_max = X [ : , 1 ] . min ( ) - 1 , X [ : , 1 ] . max ( ) + 1 xx , yy = np . meshgrid ( np . arange ( x_min , x_max , step ) , np . arange ( y_min , y_max , step ) ) f , ax = plt . subplots ( figsize = figsize ) Z = model . predict ( np . c_ [ xx . ravel ( ) , yy . ravel ( ) ] ) Z = Z . reshape ( xx . shape ) ax . contourf ( xx , yy , Z , alpha = alpha ) ax . scatter ( X [ : , 0 ] , X [ : , 1 ] , c = y , s = size , edgecolor = 'k' ) plt . show ( ) | Plots the classification decision boundary of model on X with labels y . Using numpy and matplotlib . | 260 | 22 |
15,535 | def ensure_argcount ( args , min_ = None , max_ = None ) : ensure_sequence ( args ) has_min = min_ is not None has_max = max_ is not None if not ( has_min or has_max ) : raise ValueError ( "minimum and/or maximum number of arguments must be provided" ) if has_min and has_max and min_ > max_ : raise ValueError ( "maximum number of arguments must be greater or equal to minimum" ) if has_min and len ( args ) < min_ : raise TypeError ( "expected at least %s arguments, got %s" % ( min_ , len ( args ) ) ) if has_max and len ( args ) > max_ : raise TypeError ( "expected at most %s arguments, got %s" % ( max_ , len ( args ) ) ) return args | Checks whether iterable of positional arguments satisfies conditions . | 188 | 11 |
15,536 | def ensure_keyword_args ( kwargs , mandatory = ( ) , optional = ( ) ) : from taipan . strings import ensure_string ensure_mapping ( kwargs ) mandatory = list ( map ( ensure_string , ensure_iterable ( mandatory ) ) ) optional = list ( map ( ensure_string , ensure_iterable ( optional ) ) ) if not ( mandatory or optional ) : raise ValueError ( "mandatory and/or optional argument names must be provided" ) names = set ( kwargs ) for name in mandatory : try : names . remove ( name ) except KeyError : raise TypeError ( "no value for mandatory keyword argument '%s'" % name ) excess = names - set ( optional ) if excess : if len ( excess ) == 1 : raise TypeError ( "unexpected keyword argument '%s'" % excess . pop ( ) ) else : raise TypeError ( "unexpected keyword arguments: %s" % ( tuple ( excess ) , ) ) return kwargs | Checks whether dictionary of keyword arguments satisfies conditions . | 216 | 10 |
15,537 | def _api_call ( self , path , data = { } , http_method = requests . get ) : log . info ( 'performing api request' , path = path ) response = http_method ( '/' . join ( [ self . api_url , path ] ) , params = { 'auth_token' : self . api_key } , data = data ) log . debug ( '{} remaining calls' . format ( response . headers [ 'x-ratelimit-remaining' ] ) ) return response . json ( ) | Process an http call against the hipchat api | 115 | 9 |
15,538 | def message ( self , body , room_id , style = 'text' ) : # TODO Automatically detect body format ? path = 'rooms/message' data = { 'room_id' : room_id , 'message' : body , 'from' : self . name , 'notify' : 1 , 'message_format' : style , 'color' : self . bg_color } log . info ( 'sending message to hipchat' , message = body , room = room_id ) feedback = self . _api_call ( path , data , requests . post ) log . debug ( feedback ) return feedback | Send a message to the given room | 135 | 7 |
15,539 | def job_file ( self ) : job_file_name = '%s.job' % ( self . name ) job_file_path = os . path . join ( self . initial_dir , job_file_name ) self . _job_file = job_file_path return self . _job_file | The path to the submit description file representing this job . | 69 | 11 |
15,540 | def log_file ( self ) : log_file = self . get ( 'log' ) if not log_file : log_file = '%s.log' % ( self . name ) self . set ( 'log' , log_file ) return os . path . join ( self . initial_dir , self . get ( 'log' ) ) | The path to the log file for this job . | 76 | 10 |
15,541 | def initial_dir ( self ) : initial_dir = self . get ( 'initialdir' ) if not initial_dir : initial_dir = os . curdir #TODO does this conflict with the working directory? if self . _remote and os . path . isabs ( initial_dir ) : raise RemoteError ( 'Cannot define an absolute path as an initial_dir on a remote scheduler' ) return initial_dir | The initial directory defined for the job . | 92 | 8 |
15,542 | def submit ( self , queue = None , options = [ ] ) : if not self . executable : log . error ( 'Job %s was submitted with no executable' , self . name ) raise NoExecutable ( 'You cannot submit a job without an executable' ) self . _num_jobs = queue or self . num_jobs self . _write_job_file ( ) args = [ 'condor_submit' ] args . extend ( options ) args . append ( self . job_file ) log . info ( 'Submitting job %s with options: %s' , self . name , args ) return super ( Job , self ) . submit ( args ) | Submits the job either locally or to a remote server if it is defined . | 141 | 16 |
15,543 | def wait ( self , options = [ ] , sub_job_num = None ) : args = [ 'condor_wait' ] args . extend ( options ) job_id = '%s.%s' % ( self . cluster_id , sub_job_num ) if sub_job_num else str ( self . cluster_id ) if self . _remote : abs_log_file = self . log_file else : abs_log_file = os . path . abspath ( self . log_file ) args . extend ( [ abs_log_file , job_id ] ) out , err = self . _execute ( args ) return out , err | Wait for the job or a sub - job to complete . | 144 | 12 |
15,544 | def get ( self , attr , value = None , resolve = True ) : try : if resolve : value = self . _resolve_attribute ( attr ) else : value = self . attributes [ attr ] except KeyError : pass return value | Get the value of an attribute from submit description file . | 53 | 11 |
15,545 | def set ( self , attr , value ) : def escape_new_syntax ( value , double_quote_escape = '"' ) : value = str ( value ) value = value . replace ( "'" , "''" ) value = value . replace ( '"' , '%s"' % double_quote_escape ) if ' ' in value or '\t' in value : value = "'%s'" % value return value def escape_new_syntax_pre_post_script ( value ) : return escape_new_syntax ( value , '\\' ) def escape_remap ( value ) : value = value . replace ( '=' , '\=' ) value = value . replace ( ';' , '\;' ) return value def join_function_template ( join_string , escape_func ) : return lambda value : join_string . join ( [ escape_func ( i ) for i in value ] ) def quote_join_function_template ( join_string , escape_func ) : return lambda value : join_function_template ( join_string , escape_func ) ( value ) join_functions = { 'rempas' : quote_join_function_template ( '; ' , escape_remap ) , 'arguments' : quote_join_function_template ( ' ' , escape_new_syntax ) , 'Arguments' : quote_join_function_template ( ' ' , escape_new_syntax_pre_post_script ) } if value is False : value = 'false' elif value is True : value = 'true' elif isinstance ( value , list ) or isinstance ( value , tuple ) : join_function = join_function_template ( ', ' , str ) for key in list ( join_functions . keys ( ) ) : if attr . endswith ( key ) : join_function = join_functions [ key ] value = join_function ( value ) self . attributes [ attr ] = value | Set the value of an attribute in the submit description file . | 432 | 12 |
15,546 | def _update_status ( self , sub_job_num = None ) : job_id = '%s.%s' % ( self . cluster_id , sub_job_num ) if sub_job_num else str ( self . cluster_id ) format = [ '-format' , '"%d"' , 'JobStatus' ] cmd = 'condor_q {0} {1} && condor_history {0} {1}' . format ( job_id , ' ' . join ( format ) ) args = [ cmd ] out , err = self . _execute ( args , shell = True , run_in_job_dir = False ) if err : log . error ( 'Error while updating status for job %s: %s' , job_id , err ) raise HTCondorError ( err ) if not out : log . error ( 'Error while updating status for job %s: Job not found.' , job_id ) raise HTCondorError ( 'Job not found.' ) out = out . replace ( '\"' , '' ) log . info ( 'Job %s status: %s' , job_id , out ) if not sub_job_num : if len ( out ) >= self . num_jobs : out = out [ : self . num_jobs ] else : msg = 'There are {0} sub-jobs, but {1} status(es).' . format ( self . num_jobs , len ( out ) ) log . error ( msg ) raise HTCondorError ( msg ) #initialize status dictionary status_dict = dict ( ) for val in CONDOR_JOB_STATUSES . values ( ) : status_dict [ val ] = 0 for status_code_str in out : status_code = 0 try : status_code = int ( status_code_str ) except ValueError : pass key = CONDOR_JOB_STATUSES [ status_code ] status_dict [ key ] += 1 return status_dict | Gets the job status . | 434 | 6 |
15,547 | def _resolve_attribute ( self , attribute ) : value = self . attributes [ attribute ] if not value : return None resolved_value = re . sub ( '\$\((.*?)\)' , self . _resolve_attribute_match , value ) return resolved_value | Recursively replaces references to other attributes with their value . | 60 | 12 |
15,548 | def _resolve_attribute_match ( self , match ) : if match . group ( 1 ) == 'cluster' : return str ( self . cluster_id ) return self . get ( match . group ( 1 ) , match . group ( 0 ) ) | Replaces a reference to an attribute with the value of the attribute . | 55 | 14 |
15,549 | def total_capacity ( self ) : # Ensure this task's channel has spare capacity for this task. total_capacity = 0 hosts = yield self . hosts ( enabled = True ) for host in hosts : total_capacity += host . capacity defer . returnValue ( total_capacity ) | Find the total task capacity available for this channel . | 58 | 10 |
15,550 | def cmd ( send , msg , args ) : if not msg : send ( "Google what?" ) return key = args [ 'config' ] [ 'api' ] [ 'googleapikey' ] cx = args [ 'config' ] [ 'api' ] [ 'googlesearchid' ] data = get ( 'https://www.googleapis.com/customsearch/v1' , params = { 'key' : key , 'cx' : cx , 'q' : msg } ) . json ( ) if 'items' not in data : send ( "Google didn't say much." ) else : url = data [ 'items' ] [ 0 ] [ 'link' ] send ( "Google says %s" % url ) | Googles something . | 161 | 5 |
15,551 | def get_deps ( cfg = None , deps = [ ] ) : if not cfg is None : if not 'deps' in cfg : cfg [ 'deps' ] = deps else : deps = cfg [ 'deps' ] if not len ( deps ) == 0 : for dep in deps : if not dep in cfg : runbashcmd ( f'conda install {dep}' , test = cfg [ 'test' ] ) cfg [ dep ] = dep logging . info ( f"{len(deps)} deps installed." ) return cfg | Installs conda dependencies . | 133 | 6 |
15,552 | def mont_pub_from_mont_priv ( cls , mont_priv ) : if not isinstance ( mont_priv , bytes ) : raise TypeError ( "Wrong type passed for the mont_priv parameter." ) if len ( mont_priv ) != cls . MONT_PRIV_KEY_SIZE : raise ValueError ( "Invalid value passed for the mont_priv parameter." ) return bytes ( cls . _mont_pub_from_mont_priv ( bytearray ( mont_priv ) ) ) | Restore the Montgomery public key from a Montgomery private key . | 113 | 12 |
15,553 | def mont_priv_to_ed_pair ( cls , mont_priv ) : if not isinstance ( mont_priv , bytes ) : raise TypeError ( "Wrong type passed for the mont_priv parameter." ) if len ( mont_priv ) != cls . MONT_PRIV_KEY_SIZE : raise ValueError ( "Invalid value passed for the mont_priv parameter." ) ed_priv , ed_pub = cls . _mont_priv_to_ed_pair ( bytearray ( mont_priv ) ) return bytes ( ed_priv ) , bytes ( ed_pub ) | Derive a Twisted Edwards key pair from given Montgomery private key . | 131 | 13 |
15,554 | def mont_pub_to_ed_pub ( cls , mont_pub ) : if not isinstance ( mont_pub , bytes ) : raise TypeError ( "Wrong type passed for the mont_pub parameter." ) if len ( mont_pub ) != cls . MONT_PUB_KEY_SIZE : raise ValueError ( "Invalid value passed for the mont_pub parameter." ) return bytes ( cls . _mont_pub_to_ed_pub ( bytearray ( mont_pub ) ) ) | Derive a Twisted Edwards public key from given Montgomery public key . | 113 | 13 |
15,555 | def sign ( self , data , nonce = None ) : cls = self . __class__ if not self . __mont_priv : raise MissingKeyException ( "Cannot sign using this XEdDSA instance, Montgomery private key missing." ) if not isinstance ( data , bytes ) : raise TypeError ( "The data parameter must be a bytes-like object." ) if nonce == None : nonce = os . urandom ( 64 ) if not isinstance ( nonce , bytes ) : raise TypeError ( "Wrong type passed for the nonce parameter." ) if len ( nonce ) != 64 : raise ValueError ( "Invalid value passed for the nonce parameter." ) ed_priv , ed_pub = cls . _mont_priv_to_ed_pair ( bytearray ( self . __mont_priv ) ) return bytes ( cls . _sign ( bytearray ( data ) , bytearray ( nonce ) , ed_priv , ed_pub ) ) | Sign data using the Montgomery private key stored by this XEdDSA instance . | 217 | 16 |
15,556 | def verify ( self , data , signature ) : cls = self . __class__ if not isinstance ( data , bytes ) : raise TypeError ( "The data parameter must be a bytes-like object." ) if not isinstance ( signature , bytes ) : raise TypeError ( "Wrong type passed for the signature parameter." ) if len ( signature ) != cls . SIGNATURE_SIZE : raise ValueError ( "Invalid value passed for the signature parameter." ) return cls . _verify ( bytearray ( data ) , bytearray ( signature ) , cls . _mont_pub_to_ed_pub ( bytearray ( self . __mont_pub ) ) ) | Verify signed data using the Montgomery public key stored by this XEdDSA instance . | 150 | 18 |
15,557 | def mangle ( text ) : text_bytes = text . encode ( 'utf-8' ) # Wrap the input script as a byte stream buff = BytesIO ( text_bytes ) # Byte stream for the mangled script mangled = BytesIO ( ) last_tok = token . INDENT last_line = - 1 last_col = 0 last_line_text = '' open_list_dicts = 0 # Build tokens from the script tokens = tokenizer ( buff . readline ) for t , text , ( line_s , col_s ) , ( line_e , col_e ) , line in tokens : # If this is a new line (except the very first) if line_s > last_line and last_line != - 1 : # Reset the column last_col = 0 # If the last line ended in a '\' (continuation) if last_line_text . rstrip ( ) [ - 1 : ] == '\\' : # Recreate it mangled . write ( b' \\\n' ) # We don't want to be calling the this multiple times striped = text . strip ( ) # Tokens or characters for opening or closing a list/dict list_dict_open = [ token . LSQB , token . LBRACE , '[' , '{' ] list_dict_close = [ token . RSQB , token . RBRACE , ']' , '}' ] # If this is a list or dict if t in list_dict_open or striped in list_dict_open : # Increase the dict / list level open_list_dicts += 1 elif t in list_dict_close or striped in list_dict_close : # Decrease the dict / list level open_list_dicts -= 1 # Remove docstrings # Docstrings are strings not used in an expression, # unfortunatly it isn't as simple as "t is string and t # not in expression" if t == token . STRING and ( last_tok == token . INDENT or ( ( last_tok == token . NEWLINE or last_tok == tokenize . NL or last_tok == token . DEDENT or last_tok == tokenize . ENCODING ) and open_list_dicts == 0 ) ) : # Output number of lines corresponding those in # the docstring comment mangled . write ( b'\n' * ( len ( text . split ( '\n' ) ) - 1 ) ) # Or is it a standard comment elif t == tokenize . COMMENT : # Plain comment, just don't write it pass else : # Recreate indentation, ideally we should use tabs if col_s > last_col : mangled . write ( b' ' * ( col_s - last_col ) ) # On Python 3 the first token specifies the encoding # but we already know it's utf-8 and writing it just # gives us an invalid script if t != tokenize . ENCODING : mangled . write ( text . encode ( 'utf-8' ) ) # Store the previous state last_tok = t last_col = col_e last_line = line_e last_line_text = line # Return a string return mangled . getvalue ( ) . decode ( 'utf-8' ) | Takes a script and mangles it | 714 | 8 |
15,558 | def main ( argv = None ) : if not argv : argv = sys . argv [ 1 : ] parser = argparse . ArgumentParser ( description = _HELP_TEXT ) parser . add_argument ( 'input' , nargs = '?' , default = None ) parser . add_argument ( 'output' , nargs = '?' , default = None ) parser . add_argument ( '--version' , action = 'version' , version = '%(prog)s ' + get_version ( ) ) args = parser . parse_args ( argv ) if not args . input : print ( "No file specified" , file = sys . stderr ) sys . exit ( 1 ) try : with open ( args . input , 'r' ) as f : res = mangle ( f . read ( ) ) if not args . output : print ( res , end = '' ) else : with open ( args . output , 'w' ) as o : o . write ( res ) except Exception as ex : print ( "Error mangling {}: {!s}" . format ( args . input , ex ) , file = sys . stderr ) sys . exit ( 1 ) | Command line entry point | 259 | 4 |
15,559 | def get_histograms_in_list ( filename : str , list_name : str = None ) -> Dict [ str , Any ] : hists : dict = { } with RootOpen ( filename = filename , mode = "READ" ) as fIn : if list_name is not None : hist_list = fIn . Get ( list_name ) else : hist_list = [ obj . ReadObj ( ) for obj in fIn . GetListOfKeys ( ) ] if not hist_list : fIn . ls ( ) # Closing this file appears (but is not entirely confirmed) to be extremely important! Otherwise, # the memory will leak, leading to ROOT memory issues! fIn . Close ( ) raise ValueError ( f"Could not find list with name \"{list_name}\". Possible names are listed above." ) # Retrieve objects in the hist list for obj in hist_list : _retrieve_object ( hists , obj ) return hists | Get histograms from the file and make them available in a dict . | 208 | 14 |
15,560 | def _retrieve_object ( output_dict : Dict [ str , Any ] , obj : Any ) -> None : import ROOT # Store TH1 or THn if isinstance ( obj , ROOT . TH1 ) or isinstance ( obj , ROOT . THnBase ) : # Ensure that it is not lost after the file is closed # Only works for TH1 if isinstance ( obj , ROOT . TH1 ) : obj . SetDirectory ( 0 ) # Explicitly note that python owns the object # From more on memory management with ROOT and python, see: # https://root.cern.ch/root/html/guides/users-guide/PythonRuby.html#memory-handling ROOT . SetOwnership ( obj , False ) # Store the object output_dict [ obj . GetName ( ) ] = obj # Recurse over lists if isinstance ( obj , ROOT . TCollection ) : # Keeping it in order simply makes it easier to follow output_dict [ obj . GetName ( ) ] = { } # Iterate over the objects in the collection and recursively store them for obj_temp in list ( obj ) : _retrieve_object ( output_dict [ obj . GetName ( ) ] , obj_temp ) | Function to recursively retrieve histograms from a list in a ROOT file . | 270 | 17 |
15,561 | def get_bin_edges_from_axis ( axis ) -> np . ndarray : # Don't include over- or underflow bins bins = range ( 1 , axis . GetNbins ( ) + 1 ) # Bin edges bin_edges = np . empty ( len ( bins ) + 1 ) bin_edges [ : - 1 ] = [ axis . GetBinLowEdge ( i ) for i in bins ] bin_edges [ - 1 ] = axis . GetBinUpEdge ( axis . GetNbins ( ) ) return bin_edges | Get bin edges from a ROOT hist axis . | 124 | 10 |
15,562 | def sistr ( self ) : logging . info ( 'Performing sistr analyses' ) with progressbar ( self . metadata ) as bar : for sample in bar : # Create the analysis-type specific attribute setattr ( sample , self . analysistype , GenObject ( ) ) if sample . general . bestassemblyfile != 'NA' : try : # Only process strains that have been determined to be Salmonella if sample . general . referencegenus == 'Salmonella' : # Set and create the path of the directory to store the strain-specific reports sample [ self . analysistype ] . reportdir = os . path . join ( sample . general . outputdirectory , self . analysistype ) # Name of the .json output file sample [ self . analysistype ] . jsonoutput = os . path . join ( sample [ self . analysistype ] . reportdir , '{}.json' . format ( sample . name ) ) # Set the sistr system call sample . commands . sistr = 'sistr -f json -o {} -t {} -T {} {}' . format ( sample [ self . analysistype ] . jsonoutput , self . cpus , os . path . join ( sample [ self . analysistype ] . reportdir , 'tmp' ) , sample . general . bestassemblyfile ) # sample [ self . analysistype ] . logout = os . path . join ( sample [ self . analysistype ] . reportdir , 'logout' ) sample [ self . analysistype ] . logerr = os . path . join ( sample [ self . analysistype ] . reportdir , 'logerr' ) # Only run the analyses if the output json file does not exist if not os . path . isfile ( sample [ self . analysistype ] . jsonoutput ) : out , err = run_subprocess ( sample . commands . sistr ) write_to_logfile ( sample . commands . sistr , sample . commands . sistr , self . logfile , sample . general . logout , sample . general . logerr , sample [ self . analysistype ] . logout , sample [ self . analysistype ] . logerr ) write_to_logfile ( out , err , self . logfile , sample . general . logout , sample . general . logerr , sample [ self . analysistype ] . logout , sample [ self . analysistype ] . logerr ) self . queue . task_done ( ) except ( ValueError , KeyError ) : pass self . queue . join ( ) self . report ( ) | Perform sistr analyses on Salmonella | 561 | 10 |
15,563 | def report ( self ) : # Initialise strings to store report data header = '\t' . join ( self . headers ) + '\n' data = '' for sample in self . metadata : if sample . general . bestassemblyfile != 'NA' : # Each strain is a fresh row row = '' try : # Read in the output .json file into the metadata sample [ self . analysistype ] . jsondata = json . load ( open ( sample [ self . analysistype ] . jsonoutput , 'r' ) ) # Set the name of the report. # Note that this is a tab-separated file, as there can be commas in the results sample [ self . analysistype ] . report = os . path . join ( sample [ self . analysistype ] . reportdir , '{}.tsv' . format ( sample . name ) ) # Iterate through all the headers to use as keys in the json-formatted output for category in self . headers : # Tab separate all the results row += '{}\t' . format ( sample [ self . analysistype ] . jsondata [ 0 ] [ category ] ) # Create attributes for each category setattr ( sample [ self . analysistype ] , category , str ( sample [ self . analysistype ] . jsondata [ 0 ] [ category ] ) ) # End the results with a newline row += '\n' data += row # Create and write headers and results to the strain-specific report with open ( sample [ self . analysistype ] . report , 'w' ) as strainreport : strainreport . write ( header ) strainreport . write ( row ) except ( KeyError , AttributeError ) : pass # Create and write headers and cumulative results to the combined report with open ( os . path . join ( self . reportdir , 'sistr.tsv' ) , 'w' ) as report : report . write ( header ) report . write ( data ) | Creates sistr reports | 420 | 6 |
15,564 | def purgeDeletedWidgets ( ) : toremove = [ ] for field in AbstractEditorWidget . funit_fields : if sip . isdeleted ( field ) : toremove . append ( field ) for field in toremove : AbstractEditorWidget . funit_fields . remove ( field ) toremove = [ ] for field in AbstractEditorWidget . tunit_fields : if sip . isdeleted ( field ) : toremove . append ( field ) for field in toremove : AbstractEditorWidget . tunit_fields . remove ( field ) | Finds old references to stashed fields and deletes them | 116 | 12 |
15,565 | def movefastq ( self ) : logging . info ( 'Moving FASTQ files' ) # Iterate through each sample for sample in self . metadata . runmetadata . samples : # Retrieve the output directory outputdir = os . path . join ( self . path , sample . name ) # Find any fastq files with the sample name fastqfiles = sorted ( glob ( os . path . join ( self . path , '{}_*.fastq*' . format ( sample . name ) ) ) ) if sorted ( glob ( os . path . join ( self . path , '{}_*.fastq*' . format ( sample . name ) ) ) ) else sorted ( glob ( os . path . join ( self . path , '{}.fastq*' . format ( sample . name ) ) ) ) if sorted ( glob ( os . path . join ( self . path , '{}.fastq*' . format ( sample . name ) ) ) ) else sorted ( glob ( os . path . join ( self . path , '{}*.fastq*' . format ( sample . name ) ) ) ) # Only try and move the files if the files exist if fastqfiles : make_path ( outputdir ) # Symlink the fastq files to the directory try : list ( map ( lambda x : os . symlink ( os . path . join ( '..' , os . path . basename ( x ) ) , os . path . join ( outputdir , os . path . basename ( x ) ) ) , fastqfiles ) ) except OSError : pass # Find any fastq files with the sample name fastqfiles = [ fastq for fastq in sorted ( glob ( os . path . join ( outputdir , '{}*.fastq*' . format ( sample . name ) ) ) ) if 'trimmed' not in fastq and 'normalised' not in fastq and 'corrected' not in fastq and 'paired' not in fastq and 'unpaired' not in fastq ] else : if outputdir : # Find any fastq files with the sample name fastqfiles = [ fastq for fastq in sorted ( glob ( os . path . join ( outputdir , '{}*.fastq*' . format ( outputdir , sample . name ) ) ) ) if 'trimmed' not in fastq and 'normalised' not in fastq and 'corrected' not in fastq and 'paired' not in fastq and 'unpaired' not in fastq ] sample . general . fastqfiles = fastqfiles | Find . fastq files for each sample and move them to an appropriately named folder | 562 | 16 |
15,566 | def get_list ( self , datatype , url , * * kwargs ) : search_url = [ url , '?' ] kwargs . update ( { 'key' : self . api_key } ) search_url . append ( urlencode ( kwargs ) ) data = json . loads ( urlopen ( '' . join ( search_url ) ) . read ( ) ) return data [ datatype ] | base function for connecting to API | 93 | 6 |
15,567 | def film_search ( self , title ) : films = [ ] #check for cache or update if not hasattr ( self , 'film_list' ) : self . get_film_list ( ) #iterate over films and check for fuzzy string match for film in self . film_list : strength = WRatio ( title , film [ 'title' ] ) if strength > 80 : film . update ( { u'strength' : strength } ) films . append ( film ) #sort films by the strength of the fuzzy string match films_sorted = sorted ( films , key = itemgetter ( 'strength' ) , reverse = True ) return films_sorted | film search using fuzzy matching | 142 | 5 |
15,568 | def get_film_id ( self , title , three_dimensional = False ) : films = self . film_search ( title ) for film in films : if ( film [ 'title' ] . find ( '3D' ) is - 1 ) is not three_dimensional : return film [ 'edi' ] return - 1 | get the film id using the title in conjunction with the searching function | 69 | 13 |
15,569 | def set_current_stim_parameter ( self , param , val ) : component = self . _stimulus . component ( 0 , 1 ) component . set ( param , val ) | Sets a parameter on the current stimulus | 39 | 8 |
15,570 | def save_to_file ( self , data , stamp ) : self . datafile . append ( self . current_dataset_name , data ) # save stimulu info info = dict ( self . _stimulus . componentDoc ( ) . items ( ) + self . _stimulus . testDoc ( ) . items ( ) ) print 'saving doc' , info info [ 'time_stamps' ] = [ stamp ] info [ 'samplerate_ad' ] = self . player . aifs self . datafile . append_trace_info ( self . current_dataset_name , info ) | Saves data to current dataset . | 133 | 7 |
15,571 | def countdown_timer ( seconds = 10 ) : tick = 0.1 # seconds n_ticks = int ( seconds / tick ) widgets = [ 'Pause for panic: ' , progressbar . ETA ( ) , ' ' , progressbar . Bar ( ) ] pbar = progressbar . ProgressBar ( widgets = widgets , max_value = n_ticks ) . start ( ) for i in range ( n_ticks ) : pbar . update ( i ) sleep ( tick ) pbar . finish ( ) | Show a simple countdown progress bar | 110 | 6 |
15,572 | def write_dicts_to_csv ( self , dicts ) : csv_headers = sorted ( dicts [ 0 ] . keys ( ) ) with open ( self . path , "w" ) as out_file : # write to file dict_writer = csv . DictWriter ( out_file , csv_headers , delimiter = "," , quotechar = "\"" ) dict_writer . writeheader ( ) dict_writer . writerows ( dicts ) | Saves . csv file with posts data | 104 | 9 |
15,573 | def write_matrix_to_csv ( self , headers , data ) : with open ( self . path , "w" ) as out_file : # write to file data_writer = csv . writer ( out_file , delimiter = "," ) data_writer . writerow ( headers ) # write headers data_writer . writerows ( data ) | Saves . csv file with data | 77 | 8 |
15,574 | def write_dicts_to_json ( self , data ) : with open ( self . path , "w" ) as out : json . dump ( data , # data out , # file handler indent = 4 , sort_keys = True # pretty print ) | Saves . json file with data | 55 | 7 |
15,575 | def start_listening ( self ) : self . _qlisten ( ) self . _halt_threads = False for t in self . queue_threads : t . start ( ) | Start listener threads for acquistion callback queues | 42 | 9 |
15,576 | def stop_listening ( self ) : self . _halt_threads = True # wake them up so that they can die for name , queue_waker in self . recieved_signals . items ( ) : q , wake_event = queue_waker wake_event . set ( ) | Stop listener threads for acquistion queues | 65 | 8 |
15,577 | def set_queue_callback ( self , name , func ) : if name in self . acquisition_hooks : self . acquisition_hooks [ name ] . append ( func ) else : self . acquisition_hooks [ name ] = [ func ] | Sets a function to execute when the named acquistion queue has data placed in it . | 53 | 19 |
15,578 | def set_calibration ( self , datakey , calf = None , frange = None ) : if datakey is None : calibration_vector , calibration_freqs = None , None else : if calf is None : raise Exception ( 'calibration reference frequency must be specified' ) try : cal = self . datafile . get_calibration ( datakey , calf ) except : print "Error: unable to load calibration data from: " , datakey raise calibration_vector , calibration_freqs = cal # clear one cache -- affects all StimulusModels StimulusModel . clearCache ( ) logger = logging . getLogger ( 'main' ) logger . debug ( 'clearing cache' ) logger . debug ( 'setting explore calibration' ) self . explorer . set_calibration ( calibration_vector , calibration_freqs , frange , datakey ) logger . debug ( 'setting protocol calibration' ) self . protocoler . set_calibration ( calibration_vector , calibration_freqs , frange , datakey ) logger . debug ( 'setting chart calibration' ) self . charter . set_calibration ( calibration_vector , calibration_freqs , frange , datakey ) logger . debug ( 'setting calibrator calibration' ) self . bs_calibrator . stash_calibration ( calibration_vector , calibration_freqs , frange , datakey ) logger . debug ( 'setting tone calibrator calibration' ) self . tone_calibrator . stash_calibration ( calibration_vector , calibration_freqs , frange , datakey ) | Sets a calibration for all of the acquisition operations from an already gathered calibration data set . | 347 | 18 |
15,579 | def set_calibration_duration ( self , dur ) : self . bs_calibrator . set_duration ( dur ) self . tone_calibrator . set_duration ( dur ) | Sets the stimulus duration for the calibration stimulus . Sets for calibration chirp test tone and calibration curve tones | 43 | 22 |
15,580 | def set_calibration_reps ( self , reps ) : self . bs_calibrator . set_reps ( reps ) self . tone_calibrator . set_reps ( reps ) | Sets the number of repetitions for calibration stimuli | 46 | 10 |
15,581 | def load_data_file ( self , fname , filemode = 'a' ) : self . close_data ( ) self . datafile = open_acqdata ( fname , filemode = filemode ) self . explorer . set ( datafile = self . datafile ) self . protocoler . set ( datafile = self . datafile ) self . charter . set ( datafile = self . datafile ) self . bs_calibrator . set ( datafile = self . datafile ) self . tone_calibrator . set ( datafile = self . datafile ) self . set_calibration ( None ) self . current_cellid = dict ( self . datafile . get_info ( '' ) ) . get ( 'total cells' , 0 ) | Opens an existing data file to append to | 168 | 9 |
15,582 | def set_threshold ( self , threshold ) : self . explorer . set_threshold ( threshold ) self . protocoler . set_threshold ( threshold ) | Sets spike detection threshold | 34 | 5 |
15,583 | def set ( self , * * kwargs ) : self . explorer . set ( * * kwargs ) self . protocoler . set ( * * kwargs ) self . tone_calibrator . set ( * * kwargs ) self . charter . set ( * * kwargs ) self . bs_calibrator . set ( * * kwargs ) self . mphone_calibrator . set ( * * kwargs ) | Sets acquisition parameters for all acquisition types | 99 | 8 |
15,584 | def set_mphone_calibration ( self , sens , db ) : self . bs_calibrator . set_mphone_calibration ( sens , db ) self . tone_calibrator . set_mphone_calibration ( sens , db ) | Sets the microphone calibration for the purpose of calculating recorded dB levels | 60 | 13 |
15,585 | def run_chart_protocol ( self , interval ) : self . charter . setup ( interval ) return self . charter . run ( ) | Runs the stimuli presentation during a chart acquisition | 29 | 9 |
15,586 | def process_calibration ( self , save = True , calf = 20000 ) : if self . selected_calibration_index == 2 : raise Exception ( "Calibration curve processing not currently supported" ) else : results , calname , freq , db = self . bs_calibrator . process_calibration ( save ) return calname , db | Processes a completed calibration | 80 | 5 |
15,587 | def close_data ( self ) : # save the total number of cells to make re-loading convient if self . datafile is not None : if self . datafile . filemode != 'r' : self . datafile . set_metadata ( '' , { 'total cells' : self . current_cellid } ) self . datafile . close ( ) self . datafile = None | Closes the current data file | 83 | 6 |
15,588 | def calibration_stimulus ( self , mode ) : if mode == 'tone' : return self . tone_calibrator . stimulus elif mode == 'noise' : return self . bs_calibrator . stimulus | Gets the stimulus model for calibration | 48 | 7 |
15,589 | def calibration_template ( self ) : temp = { } temp [ 'tone_doc' ] = self . tone_calibrator . stimulus . templateDoc ( ) comp_doc = [ ] for calstim in self . bs_calibrator . get_stims ( ) : comp_doc . append ( calstim . stateDict ( ) ) temp [ 'noise_doc' ] = comp_doc return temp | Gets the template documentation for the both the tone curve calibration and noise calibration | 91 | 15 |
15,590 | def load_calibration_template ( self , template ) : self . tone_calibrator . stimulus . clearComponents ( ) self . tone_calibrator . stimulus . loadFromTemplate ( template [ 'tone_doc' ] , self . tone_calibrator . stimulus ) comp_doc = template [ 'noise_doc' ] for state , calstim in zip ( comp_doc , self . bs_calibrator . get_stims ( ) ) : calstim . loadState ( state ) | Reloads calibration settings from saved template doc | 112 | 9 |
15,591 | def attenuator_connection ( self , connect = True ) : # all or none will be connected acquisition_modules = [ self . explorer , self . protocoler , self . bs_calibrator , self . tone_calibrator , self . charter ] if connect : if not acquisition_modules [ 0 ] . player . attenuator_connected ( ) : #attempt to re-connect first for module in acquisition_modules : success = module . player . connect_attenuator ( ) if success is None : StimulusModel . setMinVoltage ( 0.0 ) return False else : StimulusModel . setMinVoltage ( 0.005 ) return True else : StimulusModel . setMinVoltage ( 0.005 ) return True else : for module in acquisition_modules : module . player . connect_attenuator ( False ) StimulusModel . setMinVoltage ( 0.0 ) return False | Checks the connection to the attenuator and attempts to connect if not connected . Will also set an appropriate ouput minimum for stimuli if connection successful | 200 | 31 |
15,592 | def readline ( self , timeout = 0.1 ) : try : return self . _q . get ( block = timeout is not None , timeout = timeout ) except Empty : return None | Try to read a line from the stream queue . | 39 | 10 |
15,593 | def verification_events ( self ) : queued = self . _assemble_event ( 'Verifier_Queued' ) started = self . _assemble_event ( 'Verifier_Started' ) return [ x for x in [ queued , started ] if x ] | Events related to command verification . | 60 | 6 |
15,594 | def events ( self ) : events = [ self . acknowledge_event ] + self . verification_events return [ x for x in events if x ] | All events . | 31 | 3 |
15,595 | def generation_time ( self ) : entry = self . _proto . commandQueueEntry if entry . HasField ( 'generationTimeUTC' ) : return parse_isostring ( entry . generationTimeUTC ) return None | The generation time as set by Yamcs . | 47 | 9 |
15,596 | def username ( self ) : entry = self . _proto . commandQueueEntry if entry . HasField ( 'username' ) : return entry . username return None | The username of the issuer . | 34 | 6 |
15,597 | def queue ( self ) : entry = self . _proto . commandQueueEntry if entry . HasField ( 'queueName' ) : return entry . queueName return None | The name of the queue that this command was assigned to . | 36 | 12 |
15,598 | def origin ( self ) : entry = self . _proto . commandQueueEntry if entry . cmdId . HasField ( 'origin' ) : return entry . cmdId . origin return None | The origin of this command . This is often empty but may also be a hostname . | 40 | 18 |
15,599 | def sequence_number ( self ) : entry = self . _proto . commandQueueEntry if entry . cmdId . HasField ( 'sequenceNumber' ) : return entry . cmdId . sequenceNumber return None | The sequence number of this command . This is the sequence number assigned by the issuing client . | 44 | 18 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.