signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_processed_events ( self ) -> List [ Event ] : """Get all processed events . This method is intended to be used to recover events stuck in the processed state which could happen if an event handling processing an processed event goes down before completing the event processing . Returns : list [ Ev...
event_ids = DB . get_list ( self . _processed_key ) events = [ ] for event_id in event_ids : event_str = DB . get_hash_value ( self . _data_key , event_id ) event_dict = ast . literal_eval ( event_str ) event_dict [ 'id' ] = event_id event_dict [ 'subscriber' ] = self . _subscriber events . append (...
def create_person ( self , first_name , last_name , email , department = None , default_rate = None , admin = False , contractor = False ) : '''Creates a Person with the given information .'''
person = { 'user' : { 'first_name' : first_name , 'last_name' : last_name , 'email' : email , 'department' : department , 'default_hourly_rate' : default_rate , 'is_admin' : admin , 'is_contractor' : contractor , } } response = self . post_request ( 'people/' , person , follow = True ) if response : return Person (...
def key_summary ( keyjar , issuer ) : """Return a text representation of the keyjar . : param keyjar : A : py : class : ` oidcmsg . key _ jar . KeyJar ` instance : param issuer : Which key owner that we are looking at : return : A text representation of the keys"""
try : kbl = keyjar [ issuer ] except KeyError : return '' else : key_list = [ ] for kb in kbl : for key in kb . keys ( ) : if key . inactive_since : key_list . append ( '*{}:{}:{}' . format ( key . kty , key . use , key . kid ) ) else : key...
def remove_variable ( self , variable , * , implied = True , verbose = True ) : """Remove variable from data . Parameters variable : int or str Variable index or name to remove . implied : boolean ( optional ) Toggle deletion of other variables that start with the same name . Default is True . verbose...
if isinstance ( variable , int ) : variable = self . variable_names [ variable ] # find all of the implied variables removed = [ ] if implied : for n in self . variable_names : if n . startswith ( variable ) : removed . append ( n ) else : removed = [ variable ] # check that axes will no...
def __ip_addr ( addr , address_family = socket . AF_INET ) : '''Returns True if the IP address ( and optional subnet ) are valid , otherwise returns False .'''
mask_max = '32' if address_family == socket . AF_INET6 : mask_max = '128' try : if '/' not in addr : addr = '{addr}/{mask_max}' . format ( addr = addr , mask_max = mask_max ) except TypeError : return False ip , mask = addr . rsplit ( '/' , 1 ) # Verify that IP address is valid try : socket . in...
def invertible_flatten1 ( unflat_list ) : r"""Flattens ` unflat _ list ` but remember how to reconstruct the ` unflat _ list ` Returns ` flat _ list ` and the ` reverse _ list ` with indexes into the ` flat _ list ` Args : unflat _ list ( list ) : list of nested lists that we will flatten . Returns : tu...
nextnum = functools . partial ( six . next , itertools . count ( 0 ) ) # Build an unflat list of flat indexes reverse_list = [ [ nextnum ( ) for _ in tup ] for tup in unflat_list ] flat_list = flatten ( unflat_list ) return flat_list , reverse_list
def _generator ( tmp_dir , training , size = _BASE_EXAMPLE_IMAGE_SIZE , training_fraction = 0.95 ) : """Base problem example generator for Allen Brain Atlas problems . Args : tmp _ dir : str , a directory where raw example input data has been stored . training : bool , whether the mode of operation is trainin...
maybe_download_image_dataset ( _IMAGE_IDS , tmp_dir ) image_files = _get_case_file_paths ( tmp_dir = tmp_dir , case = training , training_fraction = training_fraction ) image_obj = PIL_Image ( ) tf . logging . info ( "Loaded case file paths (n=%s)" % len ( image_files ) ) height = size width = size for input_path in im...
def delete ( self , uuid ) : # type : ( UUID ) - > None """Delete file with given uuid . : param : uuid : : class : ` UUID ` instance : raises : KeyError if file does not exists"""
dest = self . abs_path ( uuid ) if not dest . exists ( ) : raise KeyError ( "No file can be found for this uuid" , uuid ) dest . unlink ( )
def set_entries ( self , entries , user_scope ) : """SetEntries . [ Preview API ] Set the specified setting entry values for the given user / all - users scope : param { object } entries : The entries to set : param str user _ scope : User - Scope at which to set the values . Should be " me " for the current ...
route_values = { } if user_scope is not None : route_values [ 'userScope' ] = self . _serialize . url ( 'user_scope' , user_scope , 'str' ) content = self . _serialize . body ( entries , '{object}' ) self . _send ( http_method = 'PATCH' , location_id = 'cd006711-163d-4cd4-a597-b05bad2556ff' , version = '5.0-preview...
def popupWidget ( self ) : """Returns the popup widget for this editor . : return < skyline . gui . XPopupWidget >"""
if not self . _popup : btns = QDialogButtonBox . Save | QDialogButtonBox . Cancel self . _popup = XPopupWidget ( self , btns ) self . _popup . setShowTitleBar ( False ) self . _popup . setAutoCalculateAnchor ( True ) self . _popup . setPositionLinkedTo ( self ) return self . _popup
def pfcount ( self , * sources ) : """Return the approximated cardinality of the set observed by the HyperLogLog at key ( s ) . Using the execute _ command because redis - py - cluster disabled it unnecessarily . but you can only send one key at a time in that case , or only keys that map to the same keyslo...
sources = [ self . redis_key ( s ) for s in sources ] with self . pipe as pipe : return pipe . execute_command ( 'PFCOUNT' , * sources )
def _is_dynamic ( module ) : """Return True if the module is special module that cannot be imported by its name ."""
# Quick check : module that have _ _ file _ _ attribute are not dynamic modules . if hasattr ( module , '__file__' ) : return False if hasattr ( module , '__spec__' ) : return module . __spec__ is None else : # Backward compat for Python 2 import imp try : path = None for part in module ...
def _stream_search ( self , * args , ** kwargs ) : """Helper method for iterating over ES search results ."""
for hit in scan ( self . elastic , query = kwargs . pop ( "body" , None ) , scroll = "10m" , ** kwargs ) : hit [ "_source" ] [ "_id" ] = hit [ "_id" ] yield hit [ "_source" ]
def _set_dscp_to_cos_mapping ( self , v , load = False ) : """Setter method for dscp _ to _ cos _ mapping , mapped from YANG variable / qos / map / dscp _ cos / dscp _ to _ cos _ mapping ( list ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ dscp _ to _ cos _ mapping ...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = YANGListType ( "dscp_in_values" , dscp_to_cos_mapping . dscp_to_cos_mapping , yang_name = "dscp-to-cos-mapping" , rest_name = "map" , parent = self , is_container = 'list' , user_ordered = False , path_helper = self . _path_h...
def _state ( self ) : """The internal state of the object . The api responses are not consistent so a retry is performed on every call with information updating the internally saved state refreshing the data . The info is cached for STATE _ CACHING _ SECONDS . : return : The current state of the toons ' inf...
state = { } required_keys = ( 'deviceStatusInfo' , 'gasUsage' , 'powerUsage' , 'thermostatInfo' , 'thermostatStates' ) try : for _ in range ( self . _state_retries ) : state . update ( self . _get_data ( '/client/auth/retrieveToonState' ) ) except TypeError : self . _logger . exception ( 'Could not get ...
def op_left ( op ) : """Returns a type instance method for the given operator , applied when the instance appears on the left side of the expression ."""
def method ( self , other ) : return op ( self . value , value_left ( self , other ) ) return method
def _create_w_objective ( m , X , R ) : """Creates an objective function and its derivative for W , given M and X ( data ) Args : m ( array ) : genes x clusters X ( array ) : genes x cells R ( array ) : 1 x genes"""
genes , clusters = m . shape cells = X . shape [ 1 ] R1 = R . reshape ( ( genes , 1 ) ) . dot ( np . ones ( ( 1 , cells ) ) ) def objective ( w ) : # convert w into a matrix first . . . because it ' s a vector for # optimization purposes w = w . reshape ( ( m . shape [ 1 ] , X . shape [ 1 ] ) ) d = m . dot ( w ...
def read_value ( self ) : """Grabs a lux reading either with autoranging ( gain = 0 ) or with a specified gain ( 1 , 16)"""
if self . gain == 1 or self . gain == 16 : self . set_gain ( self . gain ) ambient = self . read_full ( ) ir_reading = self . read_ir ( ) elif self . gain == 0 : self . set_gain ( 16 ) ambient = self . read_full ( ) if ambient < 65535 : ir_reading = self . read_ir ( ) if ambient >= 6...
def _check_node_attributes_consistency ( self ) : """Consistency Check 2 : consider all nodes listed in _ node _ attributes : raises : ValueError - - detected inconsistency among dictionaries"""
# Get list of nodes from the node attributes dict nodes_from_attributes = set ( self . _node_attributes . keys ( ) ) # Perform consistency checks on each node . for node in nodes_from_attributes : # Check 2.1 : make sure that the forward star for the node # exists . if node not in self . _forward_star : rai...
def isPeregrine ( ID , sign , lon ) : """Returns if an object is peregrine on a sign and longitude ."""
info = getInfo ( sign , lon ) for dign , objID in info . items ( ) : if dign not in [ 'exile' , 'fall' ] and ID == objID : return False return True
def data ( self , data ) : """Use msgpack ' s streaming feed feature to build up a set of lists . The lists should then contain the messagepack - rpc specified items . This should be outrageously fast ."""
self . unpacker . feed ( data ) for msg in self . unpacker : self . handlers [ msg [ 0 ] ] ( * msg )
def get_stores_secrets_command_args ( cls , stores_secrets ) : """Create an auth command for S3 and GCS ."""
commands = [ ] for store_secret in stores_secrets : store = store_secret [ 'store' ] if store == GCS : commands . append ( 'export GOOGLE_APPLICATION_CREDENTIALS={}' . format ( cls . STORE_SECRET_KEY_MOUNT_PATH . format ( store ) + '/' + store_secret [ 'persistence_secret_key' ] ) ) elif store == S3...
def authorize ( self , api_token = None , username = None , password = None ) : """Authorize a user using the browser and a CherryPy server , and write the resulting credentials to a config file ."""
access_token = None if username and password : # if we have a username and password , go and collect a token auth = ExistAuthBasic ( username , password ) auth . authorize ( ) if auth . token : access_token = auth . token [ 'access_token' ] elif api_token : # if we already have a token , just use th...
def interval_range ( start = None , end = None , periods = None , freq = None , name = None , closed = 'right' ) : """Return a fixed frequency IntervalIndex Parameters start : numeric or datetime - like , default None Left bound for generating intervals end : numeric or datetime - like , default None Righ...
start = com . maybe_box_datetimelike ( start ) end = com . maybe_box_datetimelike ( end ) endpoint = start if start is not None else end if freq is None and com . _any_none ( periods , start , end ) : freq = 1 if is_number ( endpoint ) else 'D' if com . count_not_none ( start , end , periods , freq ) != 3 : rai...
def all_stars ( self ) : """A list of all ` EPSFStar ` objects stored in this object , including those that comprise linked stars ( i . e . ` LinkedEPSFStar ` ) , as a flat list ."""
stars = [ ] for item in self . _data : if isinstance ( item , LinkedEPSFStar ) : stars . extend ( item . all_stars ) else : stars . append ( item ) return stars
def iter_acgt_geno ( self ) : """Iterates over genotypes ( ACGT format ) . Returns : tuple : The name of the marker as a string , and its genotypes as a : py : class : ` numpy . ndarray ` ( ACGT format ) ."""
# Need to iterate over itself , and modify the actual genotypes for i , ( marker , geno ) in enumerate ( self . iter_geno ( ) ) : yield marker , self . _allele_encoding [ i ] [ geno ]
def close ( self ) : """Tell all the workers to quit ."""
if self . is_worker ( ) : return for worker in self . workers : self . comm . send ( None , worker , 0 )
def generation_dispatchable ( self ) : """Get generation time series of dispatchable generators ( only active power ) Returns : pandas : ` pandas . DataFrame < dataframe > ` See class definition for details ."""
try : return self . _generation_dispatchable . loc [ [ self . timeindex ] , : ] except : return self . _generation_dispatchable . loc [ self . timeindex , : ]
def azimintpix ( data , dataerr , bcx , bcy , mask = None , Ntheta = 100 , pixmin = 0 , pixmax = np . inf , returnmask = False , errorpropagation = 2 ) : """Azimuthal integration ( averaging ) on the detector plane Inputs : data : scattering pattern matrix ( np . ndarray , dtype : np . double ) dataerr : erro...
if isinstance ( data , np . ndarray ) : data = data . astype ( np . double ) if isinstance ( dataerr , np . ndarray ) : dataerr = dataerr . astype ( np . double ) if isinstance ( mask , np . ndarray ) : mask = mask . astype ( np . uint8 ) return azimint ( data , dataerr , - 1 , - 1 , - 1 , bcx , bcy , mask ...
def add ( self , indices , values ) : """Add triggers in ' values ' to the buffers indicated by the indices"""
for i , v in zip ( indices , values ) : self . buffer [ i ] = numpy . append ( self . buffer [ i ] , v ) self . buffer_expire [ i ] = numpy . append ( self . buffer_expire [ i ] , self . time ) self . advance_time ( )
def chat_update_message ( self , channel , text , timestamp , ** params ) : """chat . update This method updates a message . Required parameters : ` channel ` : Channel containing the message to be updated . ( e . g : " C1234567890 " ) ` text ` : New text for the message , using the default formatting rules...
method = 'chat.update' if self . _channel_is_name ( channel ) : # chat . update only takes channel ids ( not channel names ) channel = self . channel_name_to_id ( channel ) params . update ( { 'channel' : channel , 'text' : text , 'ts' : timestamp , } ) return self . _make_request ( method , params )
def make_create_table_statement ( table , tablename , schema = None , constraints = True , metadata = None , dialect = None ) : """Generate a CREATE TABLE statement based on data in ` table ` . Keyword arguments : table : table container Table data to use to infer types etc . tablename : text Name of the ...
import sqlalchemy sql_table = make_sqlalchemy_table ( table , tablename , schema = schema , constraints = constraints , metadata = metadata ) if dialect : module = __import__ ( 'sqlalchemy.dialects.%s' % DIALECTS [ dialect ] , fromlist = [ 'dialect' ] ) sql_dialect = module . dialect ( ) else : sql_dialect ...
def to_er7 ( self , encoding_chars = None , trailing_children = False ) : """Return the ER7 - encoded string : type encoding _ chars : ` ` dict ` ` : param encoding _ chars : a dictionary containing the encoding chars or None to use the default ( see : func : ` get _ default _ encoding _ chars < hl7apy . get ...
if encoding_chars is None : encoding_chars = self . encoding_chars try : return self . value . to_er7 ( encoding_chars ) except AttributeError : return self . value
def answer_inline_query ( self , inline_query_id : str , results : List [ InlineQueryResult ] , cache_time : int = 300 , is_personal : bool = None , next_offset : str = "" , switch_pm_text : str = "" , switch_pm_parameter : str = "" ) : """Use this method to send answers to an inline query . No more than 50 resul...
return self . send ( functions . messages . SetInlineBotResults ( query_id = int ( inline_query_id ) , results = [ r . write ( ) for r in results ] , cache_time = cache_time , gallery = None , private = is_personal or None , next_offset = next_offset or None , switch_pm = types . InlineBotSwitchPM ( text = switch_pm_te...
def _track_changes ( self ) : """Update the track _ changes on the parent to reflect a needed update on this field"""
if self . _field and getattr ( self . _parent , '_track_changes' , None ) is not None : self . _parent . _track_changes . add ( self . _field )
def version ( ) : '''Return the version of the FreeType library being used as a tuple of ( major version number , minor version number , patch version number )'''
amajor = FT_Int ( ) aminor = FT_Int ( ) apatch = FT_Int ( ) library = get_handle ( ) FT_Library_Version ( library , byref ( amajor ) , byref ( aminor ) , byref ( apatch ) ) return ( amajor . value , aminor . value , apatch . value )
def stop ( self ) : """Stop the daemon ."""
if self . pidfile is None : raise DaemonError ( 'Cannot stop daemon without PID file' ) pid = self . _read_pidfile ( ) if pid is None : # I don ' t think this should be a fatal error self . _emit_warning ( '{prog} is not running' . format ( prog = self . prog ) ) return self . _emit_message ( 'Stopping {pro...
def syllabify ( self , words : str ) -> List [ str ] : """Parse a Latin word into a list of syllable strings . : param words : a string containing one latin word or many words separated by spaces . : return : list of string , each representing a syllable . > > > syllabifier = Syllabifier ( ) > > > print ( s...
cleaned = words . translate ( self . remove_punct_map ) cleaned = cleaned . replace ( "qu" , "kw" ) cleaned = cleaned . replace ( "Qu" , "Kw" ) cleaned = cleaned . replace ( "gua" , "gwa" ) cleaned = cleaned . replace ( "Gua" , "Gwa" ) cleaned = cleaned . replace ( "gue" , "gwe" ) cleaned = cleaned . replace ( "Gue" , ...
def _removeBPoint ( self , index , ** kwargs ) : """index will be a valid index . Subclasses may override this method ."""
bPoint = self . bPoints [ index ] nextSegment = bPoint . _nextSegment offCurves = nextSegment . offCurve if offCurves : offCurve = offCurves [ 0 ] self . removePoint ( offCurve ) segment = bPoint . _segment offCurves = segment . offCurve if offCurves : offCurve = offCurves [ - 1 ] self . removePoint ( o...
def run ( self ) : """Run the deduplication process . We apply the removal strategy one duplicate set at a time to keep memory footprint low and make the log of actions easier to read ."""
logger . info ( "The {} strategy will be applied on each duplicate set." . format ( self . conf . strategy ) ) self . stats [ 'set_total' ] = len ( self . mails ) for hash_key , mail_path_set in self . mails . items ( ) : # Print visual clue to separate duplicate sets . logger . info ( '---' ) duplicates = Dupl...
def main ( ) : """main ."""
config = context . config config . set_main_option ( "sqlalchemy.url" , config . get_main_option ( 'url' ) ) run_migrations_online ( config )
def invitelist ( self , channel ) : """Get the channel invitelist . Required arguments : * channel - Channel of which to get the invitelist for ."""
with self . lock : self . is_in_channel ( channel ) self . send ( 'MODE %s i' % channel ) invites = [ ] while self . readable ( ) : msg = self . _recv ( expected_replies = ( '346' , '347' ) ) if msg [ 0 ] == '346' : invitemask , who , timestamp = msg [ 2 ] . split ( ) [ 1 : ]...
def create_ca ( ca_name , bits = 2048 , days = 365 , CN = 'localhost' , C = 'US' , ST = 'Utah' , L = 'Salt Lake City' , O = 'SaltStack' , OU = None , emailAddress = None , fixmode = False , cacert_path = None , ca_filename = None , digest = 'sha256' , onlyif = None , unless = None , replace = False ) : '''Create a ...
status = _check_onlyif_unless ( onlyif , unless ) if status is not None : return None set_ca_path ( cacert_path ) if not ca_filename : ca_filename = '{0}_ca_cert' . format ( ca_name ) certp = '{0}/{1}/{2}.crt' . format ( cert_base_path ( ) , ca_name , ca_filename ) ca_keyp = '{0}/{1}/{2}.key' . format ( cert_ba...
def plot_hist ( image , threshold = 0. , fit_line = False , normfreq = True , # # plot label arguments title = None , grid = True , xlabel = None , ylabel = None , # # other plot arguments facecolor = 'green' , alpha = 0.75 ) : """Plot a histogram from an ANTsImage Arguments image : ANTsImage image from which...
img_arr = image . numpy ( ) . flatten ( ) img_arr = img_arr [ np . abs ( img_arr ) > threshold ] if normfreq != False : normfreq = 1. if normfreq == True else normfreq n , bins , patches = plt . hist ( img_arr , 50 , normed = normfreq , facecolor = facecolor , alpha = alpha ) if fit_line : # add a ' best fit ' line...
def close ( self ) : """close : Close zipfile when done Args : None Returns : None"""
index_present = self . contains ( 'index.html' ) self . zf . close ( ) # Make sure zipfile closes no matter what if not index_present : raise ReferenceError ( "Invalid Zip at {}: missing index.html file (use write_index_contents method)" . format ( self . write_to_path ) )
def child ( self ) : """Return a child of this L { TaskLevel } . @ return : L { TaskLevel } which is the first child of this one ."""
new_level = self . _level [ : ] new_level . append ( 1 ) return TaskLevel ( level = new_level )
def register ( conf , conf_admin , ** options ) : """Register a new admin section . : param conf : A subclass of ` ` djconfig . admin . Config ` ` : param conf _ admin : A subclass of ` ` djconfig . admin . ConfigAdmin ` ` : param options : Extra options passed to ` ` django . contrib . admin . site . registe...
assert issubclass ( conf_admin , ConfigAdmin ) , ( 'conf_admin is not a ConfigAdmin subclass' ) assert issubclass ( getattr ( conf_admin , 'change_list_form' , None ) , ConfigForm ) , 'No change_list_form set' assert issubclass ( conf , Config ) , ( 'conf is not a Config subclass' ) assert conf . app_label , 'No app_la...
def run ( self ) : """Modified ` ` run ` ` that captures return value and exceptions from ` ` target ` `"""
try : if self . _target : return_value = self . _target ( * self . _args , ** self . _kwargs ) if return_value is not None : self . _exception = OrphanedReturn ( self , return_value ) except BaseException as err : self . _exception = err finally : # Avoid a refcycle if the thread is ...
def centroid_1dg ( data , error = None , mask = None ) : """Calculate the centroid of a 2D array by fitting 1D Gaussians to the marginal ` ` x ` ` and ` ` y ` ` distributions of the array . Invalid values ( e . g . NaNs or infs ) in the ` ` data ` ` or ` ` error ` ` arrays are automatically masked . The mask ...
data = np . ma . asanyarray ( data ) if mask is not None and mask is not np . ma . nomask : mask = np . asanyarray ( mask ) if data . shape != mask . shape : raise ValueError ( 'data and mask must have the same shape.' ) data . mask |= mask if np . any ( ~ np . isfinite ( data ) ) : data = np . ...
def toStringDuration ( duration ) : """Returns a description of the given duration in the most appropriate units ( e . g . seconds , ms , us , or ns ) ."""
table = ( ( '%dms' , 1e-3 , 1e3 ) , ( u'%d\u03BCs' , 1e-6 , 1e6 ) , ( '%dns' , 1e-9 , 1e9 ) ) if duration > 1 : return '%fs' % duration for format , threshold , factor in table : if duration > threshold : return format % int ( duration * factor ) return '%fs' % duration
def run ( self , i , o ) : # type : ( ) - > int """Initialize command ."""
self . input = i self . output = PoetryStyle ( i , o ) for logger in self . _loggers : self . register_logger ( logging . getLogger ( logger ) ) return super ( BaseCommand , self ) . run ( i , o )
def reorient ( image , orientation ) : """Return reoriented view of image array . Parameters image : numpy array Non - squeezed output of asarray ( ) functions . Axes - 3 and - 2 must be image length and width respectively . orientation : int or str One of TIFF _ ORIENTATIONS keys or values ."""
o = TIFF_ORIENTATIONS . get ( orientation , orientation ) if o == 'top_left' : return image elif o == 'top_right' : return image [ ... , : : - 1 , : ] elif o == 'bottom_left' : return image [ ... , : : - 1 , : , : ] elif o == 'bottom_right' : return image [ ... , : : - 1 , : : - 1 , : ] elif o == 'left_...
def add_prompt ( self , prompt , echo = True ) : """Add a prompt to this query . The prompt should be a ( reasonably short ) string . Multiple prompts can be added to the same query . : param str prompt : the user prompt : param bool echo : ` ` True ` ` ( default ) if the user ' s response should be echoed ...
self . prompts . append ( ( prompt , echo ) )
def running_time ( self ) : """For how long was the job running ? : return : Running time , seconds : rtype : Optional [ float ]"""
if not self . is_done ( ) : raise ValueError ( "Cannot get running time for a program that isn't completed." ) try : running_time = float ( self . _raw [ 'running_time' ] . split ( ) [ 0 ] ) except ( ValueError , KeyError , IndexError ) : raise UnknownApiError ( str ( self . _raw ) ) return running_time
def settle_timeout ( self ) -> int : """Returns the channels settle _ timeout ."""
# There is no way to get the settle timeout after the channel has been closed as # we ' re saving gas . Therefore get the ChannelOpened event and get the timeout there . filter_args = get_filter_args_for_specific_event_from_channel ( token_network_address = self . token_network . address , channel_identifier = self . c...
def get_beam ( self , ra , dec ) : """Get the psf as a : class : ` AegeanTools . fits _ image . Beam ` object . Parameters ra , dec : float The sky position ( degrees ) . Returns beam : : class : ` AegeanTools . fits _ image . Beam ` The psf at the given location ."""
if self . data is None : return self . wcshelper . beam else : psf = self . get_psf_sky ( ra , dec ) if not all ( np . isfinite ( psf ) ) : return None return Beam ( psf [ 0 ] , psf [ 1 ] , psf [ 2 ] )
def saml_provider_present ( name , saml_metadata_document , region = None , key = None , keyid = None , profile = None ) : '''. . versionadded : : 2016.11.0 Ensure the SAML provider with the specified name is present . name ( string ) The name of the SAML provider . saml _ metadata _ document ( string ) T...
ret = { 'name' : name , 'result' : True , 'comment' : '' , 'changes' : { } } if 'salt://' in saml_metadata_document : try : saml_metadata_document = __salt__ [ 'cp.get_file_str' ] ( saml_metadata_document ) ET . fromstring ( saml_metadata_document ) except IOError as e : log . debug ( e ...
def stream ( self , priority = values . unset , assignment_status = values . unset , workflow_sid = values . unset , workflow_name = values . unset , task_queue_sid = values . unset , task_queue_name = values . unset , evaluate_task_attributes = values . unset , ordering = values . unset , has_addons = values . unset ,...
limits = self . _version . read_limits ( limit , page_size ) page = self . page ( priority = priority , assignment_status = assignment_status , workflow_sid = workflow_sid , workflow_name = workflow_name , task_queue_sid = task_queue_sid , task_queue_name = task_queue_name , evaluate_task_attributes = evaluate_task_att...
def get_representative_cases ( self ) : """> > > armr = OldNorseNoun ( " armr " , decl _ utils . Gender . masculine ) > > > armr . set _ representative _ cases ( " armr " , " arms " , " armar " ) > > > armr . get _ representative _ cases ( ) ( ' armr ' , ' arms ' , ' armar ' ) : return : nominative singular...
return ( self . get_declined ( decl_utils . Case . nominative , decl_utils . Number . singular ) , self . get_declined ( decl_utils . Case . genitive , decl_utils . Number . singular ) , self . get_declined ( decl_utils . Case . nominative , decl_utils . Number . plural ) )
def _new_mock_response ( self , response , file_path ) : '''Return a new mock Response with the content .'''
mock_response = copy . copy ( response ) mock_response . body = Body ( open ( file_path , 'rb' ) ) mock_response . fields = NameValueRecord ( ) for name , value in response . fields . get_all ( ) : mock_response . fields . add ( name , value ) mock_response . fields [ 'Content-Type' ] = 'text/html; charset="utf-8"'...
def logical_chassis_fwdl_sanity_output_fwdl_cmd_msg ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) logical_chassis_fwdl_sanity = ET . Element ( "logical_chassis_fwdl_sanity" ) config = logical_chassis_fwdl_sanity output = ET . SubElement ( logical_chassis_fwdl_sanity , "output" ) fwdl_cmd_msg = ET . SubElement ( output , "fwdl-cmd-msg" ) fwdl_cmd_msg . text = kwargs . pop ( 'fwdl_c...
def use_plenary_book_view ( self ) : """Pass through to provider CommentBookSession . use _ plenary _ book _ view"""
self . _book_view = PLENARY # self . _ get _ provider _ session ( ' comment _ book _ session ' ) # To make sure the session is tracked for session in self . _get_provider_sessions ( ) : try : session . use_plenary_book_view ( ) except AttributeError : pass
def new_keypair ( key , value , ambig , unambig ) : """Check new keypair against existing unambiguous dict : param key : of pair : param value : of pair : param ambig : set of keys with ambig decoding : param unambig : set of keys with unambig decoding : return :"""
if key in ambig : return if key in unambig and value != unambig [ key ] : ambig . add ( key ) del unambig [ key ] return unambig [ key ] = value return
def _commitData ( self , commit ) : """Get data from a commit object : param commit : commit object : type commit : git . objects . commit . Commit"""
return { "hexsha" : commit . hexsha , "adate" : commit . authored_date , "cdate" : commit . committed_date , "author" : "%s <%s>" % ( commit . author . name , commit . author . email ) , "message" : commit . message }
def verify ( self , base_path , update = False ) : """Verify the submission and return testables that can be executed ."""
return self . project . verify_submission ( base_path , self , update = update )
def __ungrabHotkey ( self , key , modifiers , window ) : """Ungrab a specific hotkey in the given window"""
logger . debug ( "Ungrabbing hotkey: %r %r" , modifiers , key ) try : keycode = self . __lookupKeyCode ( key ) mask = 0 for mod in modifiers : mask |= self . modMasks [ mod ] window . ungrab_key ( keycode , mask ) if Key . NUMLOCK in self . modMasks : window . ungrab_key ( keycode , ...
def plot_s_bc ( fignum , Bc , S , sym ) : """function to plot Squareness , Coercivity Parameters _ _ _ _ _ fignum : matplotlib figure number Bc : list or array coercivity values S : list or array of ratio of saturation remanence to saturation sym : matplotlib symbol ( e . g . , ' g ^ ' for green triangl...
plt . figure ( num = fignum ) plt . plot ( Bc , S , sym ) plt . xlabel ( 'Bc' ) plt . ylabel ( 'Mr/Ms' ) plt . title ( 'Squareness-Coercivity Plot' ) bounds = plt . axis ( ) plt . axis ( [ 0 , bounds [ 1 ] , 0 , 1 ] )
def append_data ( self , data_buffer ) : """Append data to this audio stream : Parameters : ` data _ buffer ` : str , basestring , Bytes a buffer with a length multiple of ( sample _ width * channels )"""
if len ( data_buffer ) % ( self . sample_width * self . channels ) != 0 : raise ValueError ( "length of data_buffer must be a multiple of (sample_width * channels)" ) self . _buffer += data_buffer self . _left += len ( data_buffer )
def get_search_index ( self , index ) : """Fetch the specified Solr search index for Yokozuna . : param index : a name of a yz index : type index : string : rtype string"""
if not self . yz_wm_index : raise NotImplementedError ( "Search 2.0 administration is not " "supported for this version" ) url = self . search_index_path ( index ) # Run the request . . . status , headers , body = self . _request ( 'GET' , url ) if status == 200 : return json . loads ( bytes_to_str ( body ) ) e...
def get_nodes_from_ids ( id_list : Iterable [ str ] ) -> List [ Node ] : """Given a list of ids return their types : param id _ list : list of ids : return : dictionary where the id is the key and the value is a list of types"""
node_list = [ ] for result in get_scigraph_nodes ( id_list ) : if 'lbl' in result : label = result [ 'lbl' ] else : label = None # Empty string or None ? node_list . append ( Node ( result [ 'id' ] , label ) ) return node_list
def get_repo_name ( repo_dir ) : """Takes a directory ( which must be a git repo ) and returns the repository name , derived from remote . origin . url ; < domain > / foo / bar . git = > bar : param repo _ dir : path of the directory : return : string"""
repo = git . Repo ( repo_dir ) url = repo . remotes . origin . url return url . split ( '/' ) [ - 1 ] . split ( '.git' ) [ 0 ]
def _normalize_percent_rgb ( value ) : """Internal normalization function for clipping percent values into the permitted range ( 0 % - 100 % , inclusive ) ."""
percent = value . split ( u'%' ) [ 0 ] percent = float ( percent ) if u'.' in percent else int ( percent ) return u'0%' if percent < 0 else u'100%' if percent > 100 else u'{}%' . format ( percent )
def sigma_to_pressure ( sigma , psfc , ptop ) : r"""Calculate pressure from sigma values . Parameters sigma : ndarray The sigma levels to be converted to pressure levels . psfc : ` pint . Quantity ` The surface pressure value . ptop : ` pint . Quantity ` The pressure value at the top of the model doma...
if np . any ( sigma < 0 ) or np . any ( sigma > 1 ) : raise ValueError ( 'Sigma values should be bounded by 0 and 1' ) if psfc . magnitude < 0 or ptop . magnitude < 0 : raise ValueError ( 'Pressure input should be non-negative' ) return sigma * ( psfc - ptop ) + ptop
def join_timeseries ( base , overwrite , join_linear = None ) : """Join two sets of timeseries Parameters base : : obj : ` MAGICCData ` , : obj : ` pd . DataFrame ` , filepath Base timeseries to use . If a filepath , the data will first be loaded from disk . overwrite : : obj : ` MAGICCData ` , : obj : ` pd...
if join_linear is not None : if len ( join_linear ) != 2 : raise ValueError ( "join_linear must have a length of 2" ) if isinstance ( base , str ) : base = MAGICCData ( base ) elif isinstance ( base , MAGICCData ) : base = deepcopy ( base ) if isinstance ( overwrite , str ) : overwrite = MAGICCD...
def add_ignore ( self ) : """Writes a . gitignore file to ignore the generated data file ."""
path = self . lazy_folder + self . ignore_filename # If the file exists , return . if os . path . isfile ( os . path . realpath ( path ) ) : return None sp , sf = os . path . split ( self . data_file ) # Write the file . try : handle = open ( path , 'w' ) handle . write ( sf + '\n' ) except IOError as e : ...
def delete ( self , * , if_unused = True , if_empty = True ) : """Delete the queue . This method is a : ref : ` coroutine < coroutine > ` . : keyword bool if _ unused : If true , the queue will only be deleted if it has no consumers . : keyword bool if _ empty : If true , the queue will only be deleted if ...
if self . deleted : raise Deleted ( "Queue {} was already deleted" . format ( self . name ) ) self . sender . send_QueueDelete ( self . name , if_unused , if_empty ) yield from self . synchroniser . wait ( spec . QueueDeleteOK ) self . deleted = True self . reader . ready ( )
def main ( ) -> int : """Utility to create and publish the Docker cache to Docker Hub : return :"""
# We need to be in the same directory than the script so the commands in the dockerfiles work as # expected . But the script can be invoked from a different path base = os . path . split ( os . path . realpath ( __file__ ) ) [ 0 ] os . chdir ( base ) logging . getLogger ( ) . setLevel ( logging . DEBUG ) logging . getL...
def get ( self , request , bot_id , hook_id , id , format = None ) : """Get recipient by id serializer : TelegramRecipientSerializer responseMessages : - code : 401 message : Not authenticated"""
bot = self . get_bot ( bot_id , request . user ) hook = self . get_hook ( hook_id , bot , request . user ) recipient = self . get_recipient ( id , hook , request . user ) serializer = self . serializer ( recipient ) return Response ( serializer . data )
def get ( cls ) : # type : ( ) - > Shell """Retrieve the current shell ."""
if cls . _shell is not None : return cls . _shell try : name , path = detect_shell ( os . getpid ( ) ) except ( RuntimeError , ShellDetectionFailure ) : raise RuntimeError ( "Unable to detect the current shell." ) cls . _shell = cls ( name , path ) return cls . _shell
def is_cellular_component ( self , go_term ) : """Returns True is go _ term has is _ a , part _ of ancestor of cellular component GO : 0005575"""
cc_root = "GO:0005575" if go_term == cc_root : return True ancestors = self . get_isa_closure ( go_term ) if cc_root in ancestors : return True else : return False
def remove_callback ( self , callback , msg_type = None ) : """Remove per message type of global callback . Parameters callback : fn Callback function msg _ type : int | iterable Message type to remove callback from . Default ` None ` means global callback . Iterable type removes the callback from all t...
if msg_type is None : msg_type = self . _callbacks . keys ( ) cb_keys = self . _to_iter ( msg_type ) if cb_keys is not None : for msg_type_ in cb_keys : try : self . _callbacks [ msg_type_ ] . remove ( callback ) except KeyError : pass else : self . _callbacks [ msg_t...
def to_serializable_value ( self ) : """Parses the Hightonmodel to a serializable value such dicts , lists , strings This can be used to save the model in a NoSQL database : return : the serialized HightonModel : rtype : dict"""
return_dict = { } for name , field in self . __dict__ . items ( ) : if isinstance ( field , fields . Field ) : return_dict [ name ] = field . to_serializable_value ( ) return return_dict
def acquire ( self , * , raise_on_failure = True ) : """Attempt to acquire a slot under this rate limiter . Parameters : raise _ on _ failure ( bool ) : Whether or not failures should raise an exception . If this is false , the context manager will instead return a boolean value representing whether or not ...
acquired = False try : acquired = self . _acquire ( ) if raise_on_failure and not acquired : raise RateLimitExceeded ( "rate limit exceeded for key %(key)r" % vars ( self ) ) yield acquired finally : if acquired : self . _release ( )
def com ( points , masses = None ) : """Calculate center of mass for given points . If masses is not set , assume equal masses ."""
if masses is None : return np . average ( points , axis = 0 ) else : return np . average ( points , axis = 0 , weights = masses )
def filter_travis ( self , entry ) : """Only show the latest entry iif this entry is in a new state"""
fstate = entry . filename + '.state' if os . path . isfile ( fstate ) : with open ( fstate ) as fd : state = fd . read ( ) . strip ( ) else : state = None if 'failed' in entry . summary : nstate = 'failed' else : nstate = 'success' with open ( fstate , 'w' ) as fd : fd . write ( nstate ) if ...
def only ( name , hostnames ) : '''Ensure that only the given hostnames are associated with the given IP address . . . versionadded : : 2016.3.0 name The IP address to associate with the given hostnames . hostnames Either a single hostname or a list of hostnames to associate with the given IP address ...
ret = { 'name' : name , 'changes' : { } , 'result' : None , 'comment' : '' } if isinstance ( hostnames , six . string_types ) : hostnames = [ hostnames ] old = ' ' . join ( __salt__ [ 'hosts.get_alias' ] ( name ) ) new = ' ' . join ( ( x . strip ( ) for x in hostnames ) ) if old == new : ret [ 'comment' ] = 'IP...
def parse_arguments ( ) : """Parses all the command line arguments using argparse and returns them ."""
parser = argparse . ArgumentParser ( ) parser . add_argument ( 'file' , metavar = "FILE" , nargs = '+' , help = 'file to be made executable' ) parser . add_argument ( "-p" , "--python" , metavar = "VERSION" , help = "python version (2 or 3)" ) parser . add_argument ( '-v' , '--version' , action = 'version' , version = ...
def inbox ( request , template_name = 'django_messages/inbox.html' ) : """Displays a list of received messages for the current user . Optional Arguments : ` ` template _ name ` ` : name of the template to use ."""
message_list = Message . objects . inbox_for ( request . user ) return render ( request , template_name , { 'message_list' : message_list , } )
def timeout ( self , timeout ) : """Set request timeout in seconds ( or fractions of a second )"""
if timeout is None : self . _timeout = None # no timeout return self . _timeout = float ( timeout )
def number_of_interactions ( self , u = None , v = None , t = None ) : """Return the number of interaction between two nodes at time t . Parameters u , v : nodes , optional ( default = all interaction ) If u and v are specified , return the number of interaction between u and v . Otherwise return the total ...
if t is None : if u is None : return int ( self . size ( ) ) elif u is not None and v is not None : if v in self . _succ [ u ] : return 1 else : return 0 else : if u is None : return int ( self . size ( t ) ) elif u is not None and v is not None : ...
def update_license_file ( data_dir ) : """Update NLPIR license file if it is out - of - date or missing . : param str data _ dir : The NLPIR data directory that houses the license . : returns bool : Whether or not an update occurred ."""
license_file = os . path . join ( data_dir , LICENSE_FILENAME ) temp_dir = tempfile . mkdtemp ( ) gh_license_filename = os . path . join ( temp_dir , LICENSE_FILENAME ) try : _ , headers = urlretrieve ( LICENSE_URL , gh_license_filename ) except IOError as e : # Python 2 uses the unhelpful IOError for this . Re - r...
def get_files ( ) : """Return the list of all source / header files in ` c / ` directory . The files will have pathnames relative to the current folder , for example " c / csv / reader _ utils . cc " ."""
sources = [ ] headers = [ "datatable/include/datatable.h" ] assert os . path . isfile ( headers [ 0 ] ) for dirpath , _ , filenames in os . walk ( "c" ) : for f in filenames : fullname = os . path . join ( dirpath , f ) if f . endswith ( ".h" ) or f . endswith ( ".inc" ) : headers . appe...
def dumps ( xs , model = None , properties = False , indent = True , ** kwargs ) : """Serialize Xmrs ( or subclass ) objects to PENMAN notation Args : xs : iterator of : class : ` ~ delphin . mrs . xmrs . Xmrs ` objects to serialize model : Xmrs subclass used to get triples properties : if ` True ` , enco...
xs = list ( xs ) if not xs : return '' given_class = xs [ 0 ] . __class__ # assume they are all the same if model is None : model = xs [ 0 ] . __class__ if not hasattr ( model , 'to_triples' ) : raise TypeError ( '{} class does not implement to_triples()' . format ( model . __name__ ) ) # convert MRS to DMR...
def _select_in_voltage_range ( self , min_voltage = None , max_voltage = None ) : """Selects VoltagePairs within a certain voltage range . Args : min _ voltage ( float ) : The minimum allowable voltage for a given step . max _ voltage ( float ) : The maximum allowable voltage allowable for a given step . ...
min_voltage = min_voltage if min_voltage is not None else self . min_voltage max_voltage = max_voltage if max_voltage is not None else self . max_voltage return list ( filter ( lambda p : min_voltage <= p . voltage <= max_voltage , self . voltage_pairs ) )
def split_block_by_row_length ( block , split_row_length ) : '''Splits the block by finding all rows with less consequetive , non - empty rows than the min _ row _ length input .'''
split_blocks = [ ] current_block = [ ] for row in block : if row_content_length ( row ) <= split_row_length : if current_block : split_blocks . append ( current_block ) split_blocks . append ( [ row ] ) current_block = [ ] else : current_block . append ( row ) if curr...
def _isLastCodeColumn ( self , block , column ) : """Return true if the given column is at least equal to the column that contains the last non - whitespace character at the given line , or if the rest of the line is a comment ."""
return column >= self . _lastColumn ( block ) or self . _isComment ( block , self . _nextNonSpaceColumn ( block , column + 1 ) )
def keep_season ( show , keep ) : """Keep only the latest season ."""
deleted = 0 print ( '%s Cleaning %s to latest season.' % ( datestr ( ) , show . title ) ) for season in show . seasons ( ) [ : - 1 ] : for episode in season . episodes ( ) : delete_episode ( episode ) deleted += 1 return deleted
def make_json_formatter ( graph ) : """Create the default json formatter ."""
return { "()" : graph . config . logging . json_formatter . formatter , "fmt" : graph . config . logging . json_required_keys , }
def pvR ( self , vR , R , z , gl = True , ngl = _DEFAULTNGL2 , nsigma = 4. , vTmax = 1.5 ) : """NAME : pvR PURPOSE : calculate the marginalized vR probability at this location ( NOT normalized by the density ) INPUT : vR - radial velocity ( can be Quantity ) R - radius ( can be Quantity ) z - height (...
sigmaz1 = self . _sz * numpy . exp ( ( self . _refr - R ) / self . _hsz ) if gl : if ngl % 2 == 1 : raise ValueError ( "ngl must be even" ) # Use Gauss - Legendre integration for all if ngl == _DEFAULTNGL : glx , glw = self . _glxdef , self . _glwdef glx12 , glw12 = self . _glxdef12 ...
def time ( value , allow_empty = False , minimum = None , maximum = None , coerce_value = True , ** kwargs ) : """Validate that ` ` value ` ` is a valid : class : ` time < python : datetime . time > ` . . . caution : : This validator will * * always * * return the time as timezone naive ( effectively UTC ) . ...
# pylint : disable = too - many - branches if not value and not allow_empty : if isinstance ( value , datetime_ . time ) : pass else : raise errors . EmptyValueError ( 'value (%s) was empty' % value ) elif not value : if not isinstance ( value , datetime_ . time ) : return None minim...