signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def toggle_grid ( self , evt = None , show = None ) : "toggle grid display"
if show is None : show = not self . conf . show_grid self . conf . enable_grid ( show )
def offload_all_service_containers ( self , service ) : """Deletes all containers related to the service ."""
def anonymous ( anonymous_service ) : if not isinstance ( anonymous_service , Service ) : raise TypeError ( "service must be an instance of Service." ) containers = self . find_service_containers ( anonymous_service ) if containers : logger . info ( "Deleting service: {0} containers." . form...
def cleanup ( self ) : """Cleans up jobs on the remote run location . The job ids are read from the submission file which has to exist for obvious reasons ."""
task = self . task # get job ids from submission data job_ids = [ d [ "job_id" ] for d in self . submission_data . jobs . values ( ) if d [ "job_id" ] not in ( self . submission_data . dummy_job_id , None ) ] if not job_ids : return # cleanup jobs task . publish_message ( "going to cleanup {} jobs" . format ( len (...
def _dumpOnlineConf ( self , format ) : """dump element configuration json string for online modeling , in which control configuration should be overwritten simulation conf , e . g . in simuinfo : { ' k1 ' : 10 , ' l ' : 1 } , ctrlinfo : { ' k1 ' : pv _ name , . . . } the k1 value should be replaced by pv _ n...
oinfod = { k : v for k , v in self . simuinfo . items ( ) } for k in ( set ( oinfod . keys ( ) ) & set ( self . ctrlkeys ) ) : oinfod [ k ] = self . ctrlinfo [ k ] return { self . name . upper ( ) : { self . typename : oinfod } }
def currentRecord ( self ) : """Returns the current record based on the active index from the model . : return < orb . Table > | | None"""
completion = nativestring ( self . _pywidget . text ( ) ) options = map ( str , self . model ( ) . stringList ( ) ) try : index = options . index ( completion ) except ValueError : return None return self . _records [ index ]
def pie_plot ( df , value = 'value' , category = 'variable' , ax = None , legend = False , title = True , cmap = None , ** kwargs ) : """Plot data as a bar chart . Parameters df : pd . DataFrame Data to plot as a long - form data frame value : string , optional The column to use for data values default ...
for col in set ( SORT_IDX ) - set ( [ category ] ) : if len ( df [ col ] . unique ( ) ) > 1 : msg = 'Can not plot multiple {}s in pie_plot with value={},' + ' category={}' raise ValueError ( msg . format ( col , value , category ) ) if ax is None : fig , ax = plt . subplots ( ) # get data , set ...
def add_section ( self , section ) : """Create a new section in the configuration . Raise DuplicateSectionError if a section by the specified name already exists . Raise ValueError if name is DEFAULT ."""
if section == self . default_section : raise ValueError ( 'Invalid section name: %r' % section ) if section in self . _sections : raise DuplicateSectionError ( section ) self . _sections [ section ] = self . _dict ( ) self . _proxies [ section ] = SectionProxy ( self , section )
def update ( self , ** kwargs ) : """Update the Account resource with specified content . Args : name ( str ) : Human - readable name for the account Returns : the updated Account object ."""
return self . __class__ ( self . resource . update ( kwargs ) , self . client , wallet = self . wallet )
def show_image ( kwargs , call = None ) : """Show the details of an image"""
if call != 'function' : raise SaltCloudSystemExit ( 'The show_image action must be called with -f or --function.' ) name = kwargs [ 'image' ] log . info ( "Showing image %s" , name ) machine = vb_get_machine ( name ) ret = { machine [ "name" ] : treat_machine_dict ( machine ) } del machine [ "name" ] return ret
def getPeer ( self , url ) : """Finds a peer by URL and return the first peer record with that URL ."""
peers = list ( models . Peer . select ( ) . where ( models . Peer . url == url ) ) if len ( peers ) == 0 : raise exceptions . PeerNotFoundException ( url ) return peers [ 0 ]
def skip_class_parameters ( ) : """Can be used with : meth : ` add _ parametric _ object _ params ` , this removes duplicate variables cluttering the sphinx docs . This is only intended to be used with * sphinx autodoc * In your * sphinx * ` ` config . py ` ` file : : from cqparts . utils . sphinx import sk...
from . . params import Parameter def callback ( app , what , name , obj , skip , options ) : if ( what == 'class' ) and isinstance ( obj , Parameter ) : return True # yes , skip this object return None return callback
def retrieveVals ( self ) : """Retrieve values for graphs ."""
apacheInfo = ApacheInfo ( self . _host , self . _port , self . _user , self . _password , self . _statuspath , self . _ssl ) stats = apacheInfo . getServerStats ( ) if self . hasGraph ( 'apache_access' ) : self . setGraphVal ( 'apache_access' , 'reqs' , stats [ 'Total Accesses' ] ) if self . hasGraph ( 'apache_byte...
def libvlc_video_set_spu_delay ( p_mi , i_delay ) : '''Set the subtitle delay . This affects the timing of when the subtitle will be displayed . Positive values result in subtitles being displayed later , while negative values will result in subtitles being displayed earlier . The subtitle delay will be reset...
f = _Cfunctions . get ( 'libvlc_video_set_spu_delay' , None ) or _Cfunction ( 'libvlc_video_set_spu_delay' , ( ( 1 , ) , ( 1 , ) , ) , None , ctypes . c_int , MediaPlayer , ctypes . c_int64 ) return f ( p_mi , i_delay )
def _compute_acq ( self , x ) : """Integrated GP - Lower Confidence Bound"""
means , stds = self . model . predict ( x ) f_acqu = 0 for m , s in zip ( means , stds ) : f_acqu += - m + self . exploration_weight * s return f_acqu / ( len ( means ) )
def weather_from_dictionary ( d ) : """Builds a * Weather * object out of a data dictionary . Only certain properties of the dictionary are used : if these properties are not found or cannot be read , an error is issued . : param d : a data dictionary : type d : dict : returns : a * Weather * instance :...
# - - times if 'dt' in d : reference_time = d [ 'dt' ] elif 'dt' in d [ 'last' ] : reference_time = d [ 'last' ] [ 'dt' ] if 'sys' in d and 'sunset' in d [ 'sys' ] : sunset_time = d [ 'sys' ] [ 'sunset' ] else : sunset_time = 0 if 'sys' in d and 'sunrise' in d [ 'sys' ] : sunrise_time = d [ 'sys' ] ...
def name ( self ) : """The descriptive device name as advertised by the kernel and / or the hardware itself . To get the sysname for this device , use : attr : ` sysname ` . Returns : str : The device name ."""
pchar = self . _libinput . libinput_device_get_name ( self . _handle ) return string_at ( pchar ) . decode ( )
def _valcache_lookup ( self , cache , branch , turn , tick ) : """Return the value at the given time in ` ` cache ` `"""
if branch in cache : branc = cache [ branch ] try : if turn in branc and branc [ turn ] . rev_gettable ( tick ) : return branc [ turn ] [ tick ] elif branc . rev_gettable ( turn - 1 ) : turnd = branc [ turn - 1 ] return turnd [ turnd . end ] except History...
def del_option ( self , section , option ) : """Deletes an option if the section and option exist"""
if self . config . has_section ( section ) : if self . config . has_option ( section , option ) : self . config . remove_option ( section , option ) return ( True , self . config . options ( section ) ) return ( False , 'Option: ' + option + ' does not exist' ) return ( False , 'Section: ' + sec...
def _load ( self , ** kwargs ) : """Must check if rule actually exists before proceeding with load ."""
if self . _check_existence_by_collection ( self . _meta_data [ 'container' ] , kwargs [ 'name' ] ) : return super ( Rules , self ) . _load ( ** kwargs ) msg = 'The rule named, {}, does not exist on the device.' . format ( kwargs [ 'name' ] ) raise NonExtantPolicyRule ( msg )
def put_skeleton_files_on_disk ( metadata_type , where , github_template = None , params = { } ) : """Generates file based on jinja2 templates"""
api_name = params [ "api_name" ] file_name = github_template [ "file_name" ] template_source = config . connection . get_plugin_client_setting ( 'mm_template_source' , 'joeferraro/MavensMate-Templates/master' ) template_location = config . connection . get_plugin_client_setting ( 'mm_template_location' , 'remote' ) try...
def trees_by_path ( self , path ) : """Search trees by ` path ` . Args : path ( str ) : : attr : ` . Tree . path ` property of : class : ` . Tree ` . Returns : set : Set of matching : class : ` Tree ` instances ."""
return set ( self . path_db . get ( path , OOSet ( ) ) . keys ( ) )
def rsdl_s ( self , Yprev , Y ) : """Compute dual residual vector ."""
return self . rho * self . cnst_AT ( self . U )
def _list_nodes_full ( location = None ) : '''Return a list of the VMs that in this location'''
provider = __active_provider_name__ or 'ec2' if ':' in provider : comps = provider . split ( ':' ) provider = comps [ 0 ] params = { 'Action' : 'DescribeInstances' } instances = aws . query ( params , location = location , provider = provider , opts = __opts__ , sigver = '4' ) if 'error' in instances : rais...
def _evaluate ( self , R , z , phi = 0. , t = 0. , dR = 0 , dphi = 0 ) : """NAME : _ evaluate PURPOSE : evaluate the potential at ( R , z ) INPUT : R - Cylindrical Galactocentric radius z - vertical height phi - azimuth t - time OUTPUT : potential at ( R , z ) HISTORY : 2010-04-16 - Written ...
if True : if isinstance ( R , float ) : floatIn = True R = nu . array ( [ R ] ) z = nu . array ( [ z ] ) else : floatIn = False out = nu . empty ( len ( R ) ) indx = ( R <= 6. ) out [ True ^ indx ] = self . _kp ( R [ True ^ indx ] , z [ True ^ indx ] ) R4max = nu ...
def count ( self ) : "Return a count of rows this Query would return ."
return self . rpc_model . search_count ( self . domain , context = self . context )
def _get_files ( path ) : """Returns the list of files contained in path ( recursively ) ."""
ret_val = [ ] for root , _ , files in os . walk ( path ) : for f in files : ret_val . append ( os . path . join ( root , f ) ) return ret_val
def evaluate_precision_recall ( self , dataset , cutoffs = list ( range ( 1 , 11 , 1 ) ) + list ( range ( 11 , 50 , 5 ) ) , skip_set = None , exclude_known = True , verbose = True , ** kwargs ) : """Compute a model ' s precision and recall scores for a particular dataset . Parameters dataset : SFrame An SFram...
user_column = self . user_id item_column = self . item_id assert user_column in dataset . column_names ( ) and item_column in dataset . column_names ( ) , 'Provided data set must have a column pertaining to user ids and \ item ids, similar to what we had during training.' dataset = self . __prepare_dataset...
def BuildLegacySubject ( subject_id , approval_type ) : """Builds a legacy AFF4 urn string for a given subject and approval type ."""
at = rdf_objects . ApprovalRequest . ApprovalType if approval_type == at . APPROVAL_TYPE_CLIENT : return "aff4:/%s" % subject_id elif approval_type == at . APPROVAL_TYPE_HUNT : return "aff4:/hunts/%s" % subject_id elif approval_type == at . APPROVAL_TYPE_CRON_JOB : return "aff4:/cron/%s" % subject_id raise ...
def convert_to_namespace ( file , output , keyword ) : """Convert an annotation file to a namespace file ."""
resource = parse_bel_resource ( file ) write_namespace ( namespace_keyword = ( keyword or resource [ 'AnnotationDefinition' ] [ 'Keyword' ] ) , namespace_name = resource [ 'AnnotationDefinition' ] [ 'Keyword' ] , namespace_description = resource [ 'AnnotationDefinition' ] [ 'DescriptionString' ] , author_name = 'Charle...
def face_locations ( img , number_of_times_to_upsample = 1 , model = "hog" ) : """Returns an array of bounding boxes of human faces in a image : param img : An image ( as a numpy array ) : param number _ of _ times _ to _ upsample : How many times to upsample the image looking for faces . Higher numbers find sm...
if model == "cnn" : return [ _trim_css_to_bounds ( _rect_to_css ( face . rect ) , img . shape ) for face in _raw_face_locations ( img , number_of_times_to_upsample , "cnn" ) ] else : return [ _trim_css_to_bounds ( _rect_to_css ( face ) , img . shape ) for face in _raw_face_locations ( img , number_of_times_to_u...
def current_timestamp ( ) : """Returns current time as ISO8601 formatted string in the Zulu TZ"""
now = datetime . utcnow ( ) timestamp = now . isoformat ( ) [ 0 : 19 ] + 'Z' debug ( "generated timestamp: {now}" . format ( now = timestamp ) ) return timestamp
def strip ( self , text ) : '''Return string with markup tags removed .'''
tags , results = [ ] , [ ] return self . re_tag . sub ( lambda m : self . clear_tag ( m , tags , results ) , text )
def make_query ( args , other = None , limit = None , strand = None , featuretype = None , extra = None , order_by = None , reverse = False , completely_within = False ) : """Multi - purpose , bare - bones ORM function . This function composes queries given some commonly - used kwargs that can be passed to Feat...
_QUERY = ( "{_SELECT} {OTHER} {EXTRA} {FEATURETYPE} " "{LIMIT} {STRAND} {ORDER_BY}" ) # Construct a dictionary ` d ` that will be used later as _ QUERY . format ( * * d ) . # Default is just _ SELECT , which returns all records in the features table . # ( Recall that constants . _ SELECT gets the fields in the order ne...
def message ( self , data ) : """Sends a message to the framework scheduler . These messages are best effort ; do not expect a framework message to be retransmitted in any reliable fashion ."""
logging . info ( 'Driver sends framework message {}' . format ( data ) ) return self . driver . sendFrameworkMessage ( data )
def rsky_distribution ( self , rmax = None , smooth = 0.1 , nbins = 100 ) : """Distribution of projected separations Returns a : class : ` simpledists . Hist _ Distribution ` object . : param rmax : ( optional ) Maximum radius to calculate distribution . : param dr : ( optional ) Bin width for histogram ...
if rmax is None : if hasattr ( self , 'maxrad' ) : rmax = self . maxrad else : rmax = np . percentile ( self . Rsky , 99 ) dist = dists . Hist_Distribution ( self . Rsky . value , bins = nbins , maxval = rmax , smooth = smooth ) return dist
def _unpickle_panel_compat ( self , state ) : # pragma : no cover """Unpickle the panel ."""
from pandas . io . pickle import _unpickle_array _unpickle = _unpickle_array vals , items , major , minor = state items = _unpickle ( items ) major = _unpickle ( major ) minor = _unpickle ( minor ) values = _unpickle ( vals ) wp = Panel ( values , items , major , minor ) self . _data = wp . _data
def _vertically_size_cells ( rendered_rows ) : """Grow row heights to cater for vertically spanned cells that do not fit in the available space ."""
for r , rendered_row in enumerate ( rendered_rows ) : for rendered_cell in rendered_row : if rendered_cell . rowspan > 1 : row_height = sum ( row . height for row in rendered_rows [ r : r + rendered_cell . rowspan ] ) extra_height_needed = rendered_cell . height - row_height ...
def set_pool_quota ( service , pool_name , max_bytes = None , max_objects = None ) : """: param service : The Ceph user name to run the command under : type service : str : param pool _ name : Name of pool : type pool _ name : str : param max _ bytes : Maximum bytes quota to apply : type max _ bytes : int...
cmd = [ 'ceph' , '--id' , service , 'osd' , 'pool' , 'set-quota' , pool_name ] if max_bytes : cmd = cmd + [ 'max_bytes' , str ( max_bytes ) ] if max_objects : cmd = cmd + [ 'max_objects' , str ( max_objects ) ] check_call ( cmd )
def get_attribute_value ( self , tag_name , attribute , format_value = False , ** attribute_filter ) : """Return the attribute value in xml files which matches the tag name and the specific attribute : param str tag _ name : specify the tag name : param str attribute : specify the attribute : param bool forma...
for value in self . get_all_attribute_value ( tag_name , attribute , format_value , ** attribute_filter ) : if value is not None : return value
def transcript_to_fake_psl_line ( self , ref ) : """Convert a mapping to a fake PSL line : param ref : reference genome dictionary : type ref : dict ( ) : return : psl line : rtype : string"""
self . _initialize ( ) e = self mylen = 0 matches = 0 qstartslist = [ ] for exon in self . exons : mylen = exon . rng . length ( ) matches += mylen qstartslist . append ( matches - mylen ) qstarts = ',' . join ( [ str ( x ) for x in qstartslist ] ) + ',' oline = str ( matches ) + "\t" oline += "0\t" oline +...
def is_null ( * symbols ) : """True if no nodes or all the given nodes are either None , NOP or empty blocks . For blocks this applies recursively"""
from symbols . symbol_ import Symbol for sym in symbols : if sym is None : continue if not isinstance ( sym , Symbol ) : return False if sym . token == 'NOP' : continue if sym . token == 'BLOCK' : if not is_null ( * sym . children ) : return False cont...
def _check_and_handle_includes ( self , from_file ) : """Look for an optional INCLUDE section in the given file path . If the parser set ` paths ` , it is cleared so that they do not keep showing up when additional files are parsed ."""
logger . debug ( "Check/handle includes from %s" , from_file ) try : paths = self . _parser . get ( "INCLUDE" , "paths" ) except ( config_parser . NoSectionError , config_parser . NoOptionError ) as exc : logger . debug ( "_check_and_handle_includes: EXCEPTION: %s" , exc ) return paths_lines = [ p . strip (...
def delete_user ( self , auth , username ) : """Deletes the user with username ` ` username ` ` . Should only be called if the to - be - deleted user has no repositories . : param auth . Authentication auth : authentication object , must be admin - level : param str username : username of user to delete"""
path = "/admin/users/{}" . format ( username ) self . delete ( path , auth = auth )
def _is_molecule_linear ( self , mol ) : """Is the molecule a linear one Args : mol : The molecule . OpenBabel OBMol object . Returns : Boolean value ."""
if mol . NumAtoms ( ) < 3 : return True a1 = mol . GetAtom ( 1 ) a2 = mol . GetAtom ( 2 ) for i in range ( 3 , mol . NumAtoms ( ) + 1 ) : angle = float ( mol . GetAtom ( i ) . GetAngle ( a2 , a1 ) ) if angle < 0.0 : angle = - angle if angle > 90.0 : angle = 180.0 - angle if angle > s...
def average_gradients ( model ) : """Gradient averaging ."""
size = float ( dist . get_world_size ( ) ) for param in model . parameters ( ) : dist . all_reduce ( param . grad . data , op = dist . reduce_op . SUM , group = 0 ) param . grad . data /= size
def simple_lesk ( context_sentence : str , ambiguous_word : str , pos : str = None , lemma = True , stem = False , hyperhypo = True , stop = True , context_is_lemmatized = False , nbest = False , keepscore = False , normalizescore = False , from_cache = True ) -> "wn.Synset" : """Simple Lesk is somewhere in between...
# Ensure that ambiguous word is a lemma . ambiguous_word = lemmatize ( ambiguous_word , pos = pos ) # If ambiguous word not in WordNet return None if not wn . synsets ( ambiguous_word ) : return None # Get the signatures for each synset . ss_sign = simple_signatures ( ambiguous_word , pos , lemma , stem , hyperhypo...
def getPiLambert ( n ) : """Returns a list containing first n digits of Pi"""
mypi = piGenLambert ( ) result = [ ] if n > 0 : result += [ next ( mypi ) for i in range ( n ) ] mypi . close ( ) return result
def savefig ( self , output_path , title , dpi = 400 , format = 'png' , cmap = None ) : """Write the image to a file using pyplot . Parameters output _ path : : obj : ` str ` The directory in which to place the file . title : : obj : ` str ` The title of the file in which to save the image . dpi : int ...
plt . figure ( ) plt . imshow ( self . data , cmap = cmap ) plt . title ( title ) plt . axis ( 'off' ) title_underscore = title . replace ( ' ' , '_' ) plt . savefig ( os . path . join ( output_path , '{0}.{1}' . format ( title_underscore , format ) ) , dpi = dpi , format = format )
def getmu_vertices_stability_phase ( self , target_comp , dep_elt , tol_en = 1e-2 ) : """returns a set of chemical potentials corresponding to the vertices of the simplex in the chemical potential phase diagram . The simplex is built using all elements in the target _ composition except dep _ elt . The chem...
muref = np . array ( [ self . el_refs [ e ] . energy_per_atom for e in self . elements if e != dep_elt ] ) chempot_ranges = self . get_chempot_range_map ( [ e for e in self . elements if e != dep_elt ] ) for e in self . elements : if not e in target_comp . elements : target_comp = target_comp + Composition ...
def _process ( self , on_commit : UpdateCallable , on_rollback : UpdateCallable ) -> Any : """Process action . oncommit is a callback to execute action , onrollback is a callback to execute if the oncommit ( ) has been called and a rollback is required"""
_debug ( "---> commiting" , on_commit ) result = self . _do_with_retry ( on_commit ) if len ( self . _transactions ) > 0 : # add statement to rollback log in case something goes wrong self . _transactions [ - 1 ] . insert ( 0 , on_rollback ) return result
def _do_connection ( self , wgt , sig , func ) : """Make a connection between a GUI widget and a callable . wgt and sig are strings with widget and signal name func is a callable for that signal"""
# new style ( we use this ) # self . btn _ name . clicked . connect ( self . on _ btn _ name _ clicked ) # old style # self . connect ( self . btn _ name , SIGNAL ( ' clicked ( ) ' ) , self . on _ btn _ name _ clicked ) if hasattr ( self , wgt ) : wgtobj = getattr ( self , wgt ) if hasattr ( wgtobj , sig ) : ...
def _zforce ( self , R , z , phi = 0 , t = 0 ) : """NAME : _ zforce PURPOSE : evaluate the vertical force at ( R , z , phi ) INPUT : R - Cylindrical Galactocentric radius z - vertical height phi - azimuth t - time OUTPUT : vertical force at ( R , z , phi ) HISTORY : 2016-12-26 - Written - Bo...
r = numpy . sqrt ( R ** 2. + z ** 2. ) out = self . _scf . zforce ( R , z , phi = phi , use_physical = False ) for a , s , ds , H , dH in zip ( self . _Sigma_amp , self . _Sigma , self . _dSigmadR , self . _Hz , self . _dHzdz ) : out -= 4. * numpy . pi * a * ( ds ( r ) * H ( z ) * z / r + s ( r ) * dH ( z ) ) retur...
def splay ( vec ) : """Determine two lengths to split stride the input vector by"""
N2 = 2 ** int ( numpy . log2 ( len ( vec ) ) / 2 ) N1 = len ( vec ) / N2 return N1 , N2
def load ( cls , path ) : """Load a recursive SOM from a JSON file . You can use this function to load weights of other SOMs . If there are no context weights , they will be set to 0. Parameters path : str The path to the JSON file . Returns s : cls A som of the specified class ."""
data = json . load ( open ( path ) ) weights = data [ 'weights' ] weights = np . asarray ( weights , dtype = np . float64 ) try : context_weights = data [ 'context_weights' ] context_weights = np . asarray ( context_weights , dtype = np . float64 ) except KeyError : context_weights = np . zeros ( ( len ( we...
def damaged_by_cut ( self , subsystem ) : """Return ` ` True ` ` if this MICE is affected by the subsystem ' s cut . The cut affects the MICE if it either splits the MICE ' s mechanism or splits the connections between the purview and mechanism ."""
return ( subsystem . cut . splits_mechanism ( self . mechanism ) or np . any ( self . _relevant_connections ( subsystem ) * subsystem . cut . cut_matrix ( subsystem . network . size ) == 1 ) )
def make_relative ( self , other ) : """Return a new path that is the equivalent of this one relative to the path * other * . Unlike : meth : ` relative _ to ` , this will not throw an error if * self * is not a sub - path of * other * ; instead , it will use ` ` . . ` ` to build a relative path . This can re...
if self . is_absolute ( ) : return self from os . path import relpath other = self . __class__ ( other ) return self . __class__ ( relpath ( text_type ( self ) , text_type ( other ) ) )
async def connect ( self , connection ) : """Connects to the specified given connection using the given auth key ."""
if self . _user_connected : self . _log . info ( 'User is already connected!' ) return self . _connection = connection await self . _connect ( ) self . _user_connected = True
def path_selection_changed ( self ) : """Handles when the current index of the combobox changes ."""
idx = self . currentIndex ( ) if idx == SELECT_OTHER : external_path = self . select_directory ( ) if len ( external_path ) > 0 : self . add_external_path ( external_path ) self . setCurrentIndex ( self . count ( ) - 1 ) else : self . setCurrentIndex ( CWD ) elif idx == CLEAR_LIST : ...
def read_readme ( ) : """Reads part of the README . rst for use as long _ description in setup ( ) ."""
text = open ( "README.rst" , "rt" ) . read ( ) text_lines = text . split ( "\n" ) ld_i_beg = 0 while text_lines [ ld_i_beg ] . find ( "start long description" ) < 0 : ld_i_beg += 1 ld_i_beg += 1 ld_i_end = ld_i_beg while text_lines [ ld_i_end ] . find ( "end long description" ) < 0 : ld_i_end += 1 ld_text = "\n...
def advance ( self ) : """Carry out one iteration of Arnoldi ."""
if self . iter >= self . maxiter : raise ArgumentError ( 'Maximum number of iterations reached.' ) if self . invariant : raise ArgumentError ( 'Krylov subspace was found to be invariant ' 'in the previous iteration.' ) N = self . V . shape [ 0 ] k = self . iter # the matrix - vector multiplication Av = self . A...
def get_smtp_header ( self ) : """Returns the SMTP formatted header of the line . : rtype : string : return : The SMTP header ."""
header = "From: %s\r\n" % self . get_sender ( ) header += "To: %s\r\n" % ',\r\n ' . join ( self . get_to ( ) ) header += "Cc: %s\r\n" % ',\r\n ' . join ( self . get_cc ( ) ) header += "Bcc: %s\r\n" % ',\r\n ' . join ( self . get_bcc ( ) ) header += "Subject: %s\r\n" % self . get_subject ( ) return header
def wb_db010 ( self , value = None ) : """Corresponds to IDD Field ` wb _ db010 ` mean coincident wet - bulb temperature to Dry - bulb temperature corresponding to 1.0 % annual cumulative frequency of occurrence ( warm conditions ) Args : value ( float ) : value for IDD Field ` wb _ db010 ` Unit : C if ...
if value is not None : try : value = float ( value ) except ValueError : raise ValueError ( 'value {} need to be of type float ' 'for field `wb_db010`' . format ( value ) ) self . _wb_db010 = value
def list ( self , id ) : """Fetch info about a specific list . Returns a ` list dict ` _ ."""
id = self . __unpack_id ( id ) return self . __api_request ( 'GET' , '/api/v1/lists/{0}' . format ( id ) )
def get_consumption ( self , deviceid , timerange = "10" ) : """Return all available energy consumption data for the device . You need to divice watt _ values by 100 and volt _ values by 1000 to get the " real " values . : return : dict"""
tranges = ( "10" , "24h" , "month" , "year" ) if timerange not in tranges : raise ValueError ( "Unknown timerange. Possible values are: {0}" . format ( tranges ) ) url = self . base_url + "/net/home_auto_query.lua" response = self . session . get ( url , params = { 'sid' : self . sid , 'command' : 'EnergyStats_{0}'...
def iter_tiles ( self , include_controller = True ) : """Iterate over all tiles in this device in order . The ordering is by tile address which places the controller tile first in the list . Args : include _ controller ( bool ) : Include the controller tile in the results . Yields : int , EmulatedTile...
for address , tile in sorted ( self . _tiles . items ( ) ) : if address == 8 and not include_controller : continue yield address , tile
def populate_user ( self ) : """Populates the Django user object using the default bind credentials ."""
user = None try : # self . attrs will only be non - None if we were able to load this user # from the LDAP directory , so this filters out nonexistent users . if self . attrs is not None : self . _get_or_create_user ( force_populate = True ) user = self . _user except ldap . LDAPError as e : results...
def run ( self ) : """Main loop"""
while True : keymap = self . _okeymap . get_keymap ( ) if keymap == self . _last_keymap or not keymap : sleep ( self . _sleep_time ) continue keys = self . _okeymap . get_keys ( keymap ) if ( keys [ 'regular' ] and keys [ 'regular' ] != self . _last_keys [ 'regular' ] ) : if self...
def strip_vl_extension ( filename ) : """Strip the vega - lite extension ( either vl . json or json ) from filename"""
for ext in [ '.vl.json' , '.json' ] : if filename . endswith ( ext ) : return filename [ : - len ( ext ) ] else : return filename
def remove_data ( self , request , pk = None ) : """Remove data from collection ."""
collection = self . get_object ( ) if 'ids' not in request . data : return Response ( { "error" : "`ids`parameter is required" } , status = status . HTTP_400_BAD_REQUEST ) for data_id in request . data [ 'ids' ] : collection . data . remove ( data_id ) return Response ( )
def getEvents ( self ) : """Gets all events from Redunda and returns them . : returns : Returns a dictionary of the events which were fetched ."""
url = "https://redunda.sobotics.org/events.json" data = parse . urlencode ( { "key" : self . key } ) . encode ( ) req = request . Request ( url , data ) response = request . urlopen ( req ) return json . loads ( response . read ( ) . decode ( "utf-8" ) )
def save_configuration ( self , configuration_file ) : '''Saving configuration Parameters configuration _ file : string Filename of the configuration file .'''
if not isinstance ( configuration_file , tb . file . File ) and os . path . splitext ( configuration_file ) [ 1 ] . strip ( ) . lower ( ) != ".h5" : return save_configuration_to_text_file ( self , configuration_file ) else : return save_configuration_to_hdf5 ( self , configuration_file )
def build ( self , builder ) : """Build XML by appending to builder"""
builder . start ( "LocationRef" , dict ( LocationOID = str ( self . oid ) ) ) builder . end ( "LocationRef" )
def find_by_field ( self , table , field , field_value ) : '''从数据库里查询指定条件的记录 Args : table : 表名字 str field : 字段名 field _ value : 字段值 return : 成功 : [ dict ] 保存的记录 失败 : - 1 并打印返回报错信息'''
sql = "select * from {} where {} = '{}'" . format ( table , field , field_value ) res = self . query ( sql ) return res
def max_version ( self ) : """Version with the most downloads . : return : A tuple of the form ( version , n _ downloads )"""
data = self . version_downloads if not data : return None , 0 return max ( data . items ( ) , key = lambda item : item [ 1 ] )
def get_user ( ) : '''Get the current user'''
if HAS_PWD : ret = pwd . getpwuid ( os . geteuid ( ) ) . pw_name elif HAS_WIN_FUNCTIONS and salt . utils . win_functions . HAS_WIN32 : ret = salt . utils . win_functions . get_current_user ( ) else : raise CommandExecutionError ( 'Required external library (pwd or win32api) not installed' ) return salt . ut...
def start_end_from_segments ( segment_file ) : """Return the start and end time arrays from a segment file . Parameters segment _ file : xml segment file Returns start : numpy . ndarray end : numpy . ndarray"""
from glue . ligolw . ligolw import LIGOLWContentHandler as h ; lsctables . use_in ( h ) indoc = ligolw_utils . load_filename ( segment_file , False , contenthandler = h ) segment_table = table . get_table ( indoc , lsctables . SegmentTable . tableName ) start = numpy . array ( segment_table . getColumnByName ( 'start_t...
def simple_in_memory_settings ( cls ) : """Decorator that returns a class that " persists " data in - memory . Mostly useful for testing : param cls : the class whose features should be persisted in - memory : return : A new class that will persist features in memory"""
class Settings ( ff . PersistenceSettings ) : id_provider = ff . UuidProvider ( ) key_builder = ff . StringDelimitedKeyBuilder ( ) database = ff . InMemoryDatabase ( key_builder = key_builder ) class Model ( cls , Settings ) : pass Model . __name__ = cls . __name__ Model . __module__ = cls . __module__ ...
def register_module_alias ( self , alias , module_path , after_init = False ) : """Adds an alias for a module . http : / / uwsgi - docs . readthedocs . io / en / latest / PythonModuleAlias . html : param str | unicode alias : : param str | unicode module _ path : : param bool after _ init : add a python mod...
command = 'post-pymodule-alias' if after_init else 'pymodule-alias' self . _set ( command , '%s=%s' % ( alias , module_path ) , multi = True ) return self . _section
def check_new_round ( self , hours = 24 , tournament = 1 ) : """Check if a new round has started within the last ` hours ` . Args : hours ( int , optional ) : timeframe to consider , defaults to 24 tournament ( int ) : ID of the tournament ( optional , defaults to 1) Returns : bool : True if a new round h...
query = ''' query($tournament: Int!) { rounds(tournament: $tournament number: 0) { number openTime } } ''' arguments = { 'tournament' : tournament } raw = self . raw_query ( query , arguments ) [ 'data' ] [ ...
def _load_plugin ( self , plugin_script , args = None , config = None ) : """Load the plugin ( script ) , init it and add to the _ plugin dict ."""
# The key is the plugin name # for example , the file glances _ xxx . py # generate self . _ plugins _ list [ " xxx " ] = . . . name = plugin_script [ len ( self . header ) : - 3 ] . lower ( ) try : # Import the plugin plugin = __import__ ( plugin_script [ : - 3 ] ) # Init and add the plugin to the dictionary ...
def error ( self , coro ) : """A decorator that registers a coroutine as a local error handler . A local error handler is an : func : ` . on _ command _ error ` event limited to a single command . However , the : func : ` . on _ command _ error ` is still invoked afterwards as the catch - all . Parameters ...
if not asyncio . iscoroutinefunction ( coro ) : raise TypeError ( 'The error handler must be a coroutine.' ) self . on_error = coro return coro
def add_logger ( self , cb , level = 'NORMAL' , filters = 'ALL' ) : '''Add a callback to receive log events from this component . @ param cb The callback function to receive log events . It must have the signature cb ( name , time , source , level , message ) , where name is the name of the component the log ...
with self . _mutex : obs = sdo . RTCLogger ( self , cb ) uuid_val = uuid . uuid4 ( ) intf_type = obs . _this ( ) . _NP_RepositoryId props = { 'logger.log_level' : level , 'logger.filter' : filters } props = utils . dict_to_nvlist ( props ) sprof = SDOPackage . ServiceProfile ( id = uuid_val . ge...
def buildDescriptor ( self , dir = os . getcwd ( ) , configuration = 'Development' , args = [ ] , suppressOutput = False ) : """Builds the editor modules for the Unreal project or plugin in the specified directory , using the specified build configuration"""
# Verify that an Unreal project or plugin exists in the specified directory descriptor = self . getDescriptor ( dir ) descriptorType = 'project' if self . isProject ( descriptor ) else 'plugin' # If the project or plugin is Blueprint - only , there is no C + + code to build if os . path . exists ( os . path . join ( di...
def from_text_list ( name , ttl , rdclass , rdtype , text_rdatas ) : """Create an RRset with the specified name , TTL , class , and type , and with the specified list of rdatas in text format . @ rtype : dns . rrset . RRset object"""
if isinstance ( name , ( str , unicode ) ) : name = dns . name . from_text ( name , None ) if isinstance ( rdclass , ( str , unicode ) ) : rdclass = dns . rdataclass . from_text ( rdclass ) if isinstance ( rdtype , ( str , unicode ) ) : rdtype = dns . rdatatype . from_text ( rdtype ) r = RRset ( name , rdcl...
def add_node_set_configuration ( self , param_name , node_to_value ) : """Set Nodes parameter : param param _ name : parameter identifier ( as specified by the chosen model ) : param node _ to _ value : dictionary mapping each node a parameter value"""
for nid , val in future . utils . iteritems ( node_to_value ) : self . add_node_configuration ( param_name , nid , val )
def Validate ( self , value ) : """Validate a potential list ."""
if isinstance ( value , string_types ) : raise TypeValueError ( "Value must be an iterable not a string." ) elif not isinstance ( value , ( list , tuple ) ) : raise TypeValueError ( "%r not a valid List" % value ) # Validate each value in the list validates against our type . return [ self . validator . Validat...
def create_fleet ( Name = None , ImageName = None , InstanceType = None , ComputeCapacity = None , VpcConfig = None , MaxUserDurationInSeconds = None , DisconnectTimeoutInSeconds = None , Description = None , DisplayName = None , EnableDefaultInternetAccess = None ) : """Creates a new fleet . See also : AWS API D...
pass
def _dyn_loader ( self , module : str , kwargs : str ) : """Dynamically load a specific module instance ."""
package_directory : str = os . path . dirname ( os . path . abspath ( __file__ ) ) modules : str = package_directory + "/modules" module = module + ".py" if module not in os . listdir ( modules ) : raise Exception ( "Module %s is not valid" % module ) module_name : str = module [ : - 3 ] import_path : str = "%s.%s"...
def DOM_setFileInputFiles ( self , files , ** kwargs ) : """Function path : DOM . setFileInputFiles Domain : DOM Method name : setFileInputFiles WARNING : This function is marked ' Experimental ' ! Parameters : Required arguments : ' files ' ( type : array ) - > Array of file paths to set . Optional a...
assert isinstance ( files , ( list , tuple ) ) , "Argument 'files' must be of type '['list', 'tuple']'. Received type: '%s'" % type ( files ) expected = [ 'nodeId' , 'backendNodeId' , 'objectId' ] passed_keys = list ( kwargs . keys ( ) ) assert all ( [ ( key in expected ) for key in passed_keys ] ) , "Allowed kwargs ar...
def setup_menu ( self ) : """Setup context menu"""
self . copy_action = create_action ( self , _ ( 'Copy' ) , shortcut = keybinding ( 'Copy' ) , icon = ima . icon ( 'editcopy' ) , triggered = self . copy , context = Qt . WidgetShortcut ) menu = QMenu ( self ) add_actions ( menu , [ self . copy_action , ] ) return menu
def export_losses_by_event ( ekey , dstore ) : """: param ekey : export key , i . e . a pair ( datastore key , fmt ) : param dstore : datastore object"""
oq = dstore [ 'oqparam' ] writer = writers . CsvWriter ( fmt = writers . FIVEDIGITS ) dest = dstore . build_fname ( 'losses_by_event' , '' , 'csv' ) if oq . calculation_mode . startswith ( 'scenario' ) : dtlist = [ ( 'eid' , U64 ) ] + oq . loss_dt_list ( ) arr = dstore [ 'losses_by_event' ] . value [ [ 'eid' , ...
def get_rotations ( self ) : """Return all rotations , including inversions for centrosymmetric crystals ."""
if self . centrosymmetric : return np . vstack ( ( self . rotations , - self . rotations ) ) else : return self . rotations
def deleted ( self , src , path ) : """Update the reference tree when a handled file is deleted ."""
if self . parents [ path ] is not None : for parent in self . parents [ path ] : self . children [ parent ] . remove ( path ) if not self . children [ parent ] : del self . children [ parent ] del self . parents [ path ]
def _release ( self ) : """Destroy self since closures cannot be called again ."""
del self . funcs del self . variables del self . variable_values del self . satisfied
def convert_to_shape ( x ) : """Converts input to a Shape . Args : x : Shape , str , or None . Returns : Shape or None . Raises : ValueError : If x cannot be converted to a Shape ."""
if x is None : return None if isinstance ( x , Shape ) : return x if isinstance ( x , str ) : x = _parse_string_to_list_of_pairs ( x , seconds_to_int = True ) return Shape ( x )
def is60 ( msg ) : """Check if a message is likely to be BDS code 6,0 Args : msg ( String ) : 28 bytes hexadecimal message string Returns : bool : True or False"""
if allzeros ( msg ) : return False d = hex2bin ( data ( msg ) ) # status bit 1 , 13 , 24 , 35 , 46 if wrongstatus ( d , 1 , 2 , 12 ) : return False if wrongstatus ( d , 13 , 14 , 23 ) : return False if wrongstatus ( d , 24 , 25 , 34 ) : return False if wrongstatus ( d , 35 , 36 , 45 ) : return False...
def describe_configs ( self , config_resources , include_synonyms = False ) : """Fetch configuration parameters for one or more Kafka resources . : param config _ resources : An list of ConfigResource objects . Any keys in ConfigResource . configs dict will be used to filter the result . Setting the configs d...
version = self . _matching_api_version ( DescribeConfigsRequest ) if version == 0 : if include_synonyms : raise IncompatibleBrokerVersion ( "include_synonyms requires DescribeConfigsRequest >= v1, which is not supported by Kafka {}." . format ( self . config [ 'api_version' ] ) ) request = DescribeConfi...
def add_transition ( self , from_state_id , from_outcome , to_state_id , to_outcome , transition_id = None ) : """Adds a transition to the container state Note : Either the toState or the toOutcome needs to be " None " : param from _ state _ id : The source state of the transition : param from _ outcome : The...
transition_id = self . check_transition_id ( transition_id ) # Set from _ state _ id to None for start transitions , as from _ state _ id and from _ outcome should both be None for # these transitions if from_state_id == self . state_id and from_outcome is None : from_state_id = None new_transition = Transition ( f...
def cluster ( self , method , ** kwargs ) : """Cluster the tribe . Cluster templates within a tribe : returns multiple tribes each of which could be stacked . : type method : str : param method : Method of stacking , see : mod : ` eqcorrscan . utils . clustering ` : return : List of tribes . . . rubri...
from eqcorrscan . utils import clustering tribes = [ ] func = getattr ( clustering , method ) if method in [ 'space_cluster' , 'space_time_cluster' ] : cat = Catalog ( [ t . event for t in self . templates ] ) groups = func ( cat , ** kwargs ) for group in groups : new_tribe = Tribe ( ) for ...
def safe_decode ( text , incoming = None , errors = 'strict' ) : """Decodes incoming text / bytes string using ` incoming ` if they ' re not already unicode . This function was copied from novaclient . openstack . strutils : param incoming : Text ' s current encoding : param errors : Errors handling policy ...
if not isinstance ( text , ( six . string_types , six . binary_type ) ) : raise TypeError ( "%s can't be decoded" % type ( text ) ) if isinstance ( text , six . text_type ) : return text if not incoming : incoming = ( sys . stdin . encoding or sys . getdefaultencoding ( ) ) try : return text . decode ( ...