signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def plotcorr ( X , plotargs = None , full = True , labels = None ) : """Plots a scatterplot matrix of subplots . Usage : plotcorr ( X ) plotcorr ( . . . , plotargs = . . . ) # e . g . , ' r * ' , ' bo ' , etc . plotcorr ( . . . , full = . . . ) # e . g . , True or False plotcorr ( . . . , labels = . . . )...
import matplotlib . pyplot as plt X = [ Xi . _mcpts if isinstance ( Xi , UncertainFunction ) else Xi for Xi in X ] X = np . atleast_2d ( X ) numvars , numdata = X . shape fig , axes = plt . subplots ( nrows = numvars , ncols = numvars , figsize = ( 8 , 8 ) ) fig . subplots_adjust ( hspace = 0.0 , wspace = 0.0 ) for ax ...
async def get_data ( self ) : """Retrieve the data ."""
try : with async_timeout . timeout ( 5 , loop = self . _loop ) : response = await self . _session . get ( '{}/{}/' . format ( self . url , self . sensor_id ) ) _LOGGER . debug ( "Response from luftdaten.info: %s" , response . status ) self . data = await response . json ( ) _LOGGER . debug ( sel...
def cognito_idp_user_pool_arn ( self , lookup , default = None ) : """Args : lookup : Cognito User Pool name , proto0 - cms - user - pool default : the optional value to return if lookup failed ; returns None if not set Returns : the User Pool ARN corresponding to the given lookup , else default / None"""
client = EFAwsResolver . __CLIENTS [ "cognito-idp" ] user_pool_id = self . cognito_idp_user_pool_id ( lookup , default ) if user_pool_id == default : return default response = client . describe_user_pool ( UserPoolId = user_pool_id ) if not response . has_key ( "UserPool" ) : return default return response [ "U...
def similar_jobs ( self , request , project , pk = None ) : """Get a list of jobs similar to the one selected ."""
try : repository = Repository . objects . get ( name = project ) except Repository . DoesNotExist : return Response ( { "detail" : "No project with name {}" . format ( project ) } , status = HTTP_404_NOT_FOUND ) try : job = Job . objects . get ( repository = repository , id = pk ) except ObjectDoesNotExist ...
def hatchery ( ) : """Main entry point for the hatchery program"""
args = docopt . docopt ( __doc__ ) task_list = args [ '<task>' ] if not task_list or 'help' in task_list or args [ '--help' ] : print ( __doc__ . format ( version = _version . __version__ , config_files = config . CONFIG_LOCATIONS ) ) return 0 level_str = args [ '--log-level' ] try : level_const = getattr (...
def parse_media_range ( range ) : """Parse a media - range into its component parts . Carves up a media range and returns a tuple of the ( type , subtype , params ) where ' params ' is a dictionary of all the parameters for the media range . For example , the media range ' application / * ; q = 0.5 ' would ge...
( type , subtype , params ) = parse_mime_type ( range ) params . setdefault ( 'q' , params . pop ( 'Q' , None ) ) # q is case insensitive try : if not params [ 'q' ] or not 0 <= float ( params [ 'q' ] ) <= 1 : params [ 'q' ] = '1' except ValueError : # from float ( ) params [ 'q' ] = '1' return ( type ,...
def gradient_angle ( self ) : """Angle in float degrees of line of a linear gradient . Read / Write . May be | None | , indicating the angle should be inherited from the style hierarchy . An angle of 0.0 corresponds to a left - to - right gradient . Increasing angles represent counter - clockwise rotation o...
if self . type != MSO_FILL . GRADIENT : raise TypeError ( 'Fill is not of type MSO_FILL_TYPE.GRADIENT' ) return self . _fill . gradient_angle
def l1_log_loss ( event_times , predicted_event_times , event_observed = None ) : r"""Calculates the l1 log - loss of predicted event times to true event times for * non - censored * individuals only . . . math : : 1 / N \ sum _ { i } | log ( t _ i ) - log ( q _ i ) | Parameters event _ times : a ( n , ) ar...
if event_observed is None : event_observed = np . ones_like ( event_times ) ix = event_observed . astype ( bool ) return np . abs ( np . log ( event_times [ ix ] ) - np . log ( predicted_event_times [ ix ] ) ) . mean ( )
def childrenAtPath ( self , path ) : """Get a list of children at I { path } where I { path } is a ( / ) separated list of element names that are expected to be children . @ param path : A ( / ) separated list of element names . @ type path : basestring @ return : The collection leaf nodes at the end of I {...
if self . __root is None : return [ ] if path [ 0 ] == '/' : path = path [ 1 : ] path = path . split ( '/' , 1 ) if self . getChild ( path [ 0 ] ) is None : return [ ] if len ( path ) > 1 : return self . __root . childrenAtPath ( path [ 1 ] ) else : return [ self . __root , ]
def entry_for_view ( self , view , perm_name ) : """Get registry entry for permission if ` ` view ` ` requires it . In other words , if ` ` view ` ` requires the permission specified by ` ` perm _ name ` ` , return the : class : ` Entry ` associated with the permission . If ` ` view ` ` doesn ' t require the ...
view_name = self . _get_view_name ( view ) entry = self . _get_entry ( perm_name ) if view_name in entry . views : return entry return None
def remove_term_layer ( self ) : """Removes the term layer ( if exists ) of the object ( in memory )"""
if self . term_layer is not None : this_node = self . term_layer . get_node ( ) self . root . remove ( this_node ) self . term_layer = None if self . header is not None : self . header . remove_lp ( 'terms' )
def list_vpnservices ( self , retrieve_all = True , ** kwargs ) : '''Fetches a list of all configured VPN services for a tenant'''
return self . network_conn . list_vpnservices ( retrieve_all , ** kwargs )
def get_upload_status ( self ) : """Get the status of the video that has been uploaded ."""
if self . id : return self . connection . post ( 'get_upload_status' , video_id = self . id )
def get_assistant ( filename ) : """Imports a module from filename as a string , returns the contained Assistant object"""
agent_name = os . path . splitext ( filename ) [ 0 ] try : agent_module = import_with_3 ( agent_name , os . path . join ( os . getcwd ( ) , filename ) ) except ImportError : agent_module = import_with_2 ( agent_name , os . path . join ( os . getcwd ( ) , filename ) ) for name , obj in agent_module . __dict__ . ...
def open ( self ) -> bool : """Ensures we have a connection to the email server . Returns whether or not a new connection was required ( True or False ) ."""
if self . connection : # Nothing to do if the connection is already open . return False connection_params = { 'local_hostname' : DNS_NAME . get_fqdn ( ) } if self . timeout is not None : connection_params [ 'timeout' ] = self . timeout try : self . connection = smtplib . SMTP ( self . host , self . port , *...
def get_attachment_data ( attachmentTable , sql , nameField = "ATT_NAME" , blobField = "DATA" , contentTypeField = "CONTENT_TYPE" , rel_object_field = "REL_OBJECTID" ) : """gets all the data to pass to a feature service"""
if arcpyFound == False : raise Exception ( "ArcPy is required to use this function" ) ret_rows = [ ] with arcpy . da . SearchCursor ( attachmentTable , [ nameField , blobField , contentTypeField , rel_object_field ] , where_clause = sql ) as rows : for row in rows : temp_f = os . environ [ 'temp' ] + os...
def add ( name , gid = None , ** kwargs ) : '''Add the specified group CLI Example : . . code - block : : bash salt ' * ' group . add foo 3456'''
# # # NOTE : * * kwargs isn ' t used here but needs to be included in this # # # function for compatibility with the group . present state if info ( name ) : raise CommandExecutionError ( 'Group \'{0}\' already exists' . format ( name ) ) if salt . utils . stringutils . contains_whitespace ( name ) : raise Salt...
def summary ( self , Nbest = 5 , lw = 2 , plot = True ) : """Plots the distribution of the data and Nbest distribution"""
if plot : pylab . clf ( ) self . hist ( ) self . plot_pdf ( Nbest = Nbest , lw = lw ) pylab . grid ( True ) Nbest = min ( Nbest , len ( self . distributions ) ) try : names = self . df_errors . sort_values ( by = "sumsquare_error" ) . index [ 0 : Nbest ] except : names = self . df_errors . sort ...
def add_svc_avail_path ( path ) : '''Add a path that may contain available services . Return ` ` True ` ` if added ( or already present ) , ` ` False ` ` on error . path directory to add to AVAIL _ SVR _ DIRS'''
if os . path . exists ( path ) : if path not in AVAIL_SVR_DIRS : AVAIL_SVR_DIRS . append ( path ) return True return False
def set_bfield_for_s0 ( self , s0 ) : """Set B to probe a certain harmonic number . * * Call signature * * * s0* The harmonic number to probe at the lowest frequency Returns * self * for convenience in chaining . This just proceeds from the relation ` ` nu = s nu _ c = s e B / 2 pi m _ e c ` ` . Since...
if not ( s0 > 0 ) : raise ValueError ( 'must have s0 > 0; got %r' % ( s0 , ) ) B0 = 2 * np . pi * cgs . me * cgs . c * self . in_vals [ IN_VAL_FREQ0 ] / ( cgs . e * s0 ) self . in_vals [ IN_VAL_B ] = B0 return self
def to_dict ( self ) : '''Save this component group to a dictionary .'''
d = { 'groupId' : self . group_id } members = [ ] for m in self . members : members . append ( m . to_dict ( ) ) if members : d [ 'members' ] = members return d
def _stack_list ( data , data_labels , w ) : """Construct a numpy array by stacking arrays in a list Parameter data : list of 2D arrays , element i has shape = [ voxels _ i , samples _ i ] Each element in the list contains the fMRI data of one subject for the classification task . data _ labels : list of ...
labels_stacked = utils . concatenate_not_none ( data_labels ) weights = np . empty ( ( labels_stacked . size , ) ) data_shared = [ None ] * len ( data ) curr_samples = 0 for s in range ( len ( data ) ) : if data [ s ] is not None : subject_samples = data [ s ] . shape [ 1 ] curr_samples_end = curr_s...
def delete_exchange ( self ) : """Deletes MQ exchange for this channel Needs to be defined only once ."""
mq_channel = self . _connect_mq ( ) mq_channel . exchange_delete ( exchange = self . code_name )
def define_sub_network_cycle_constraints ( subnetwork , snapshots , passive_branch_p , attribute ) : """Constructs cycle _ constraints for a particular subnetwork"""
sub_network_cycle_constraints = { } sub_network_cycle_index = [ ] matrix = subnetwork . C . tocsc ( ) branches = subnetwork . branches ( ) for col_j in range ( matrix . shape [ 1 ] ) : cycle_is = matrix . getcol ( col_j ) . nonzero ( ) [ 0 ] if len ( cycle_is ) == 0 : continue sub_network_cycle_inde...
def write_final_draw_file ( self , output_name ) : """The result of put _ everything _ together ( ) function is writen in a file . Takes : * output _ name * - name for the output file"""
finalsvg = open ( output_name + ".svg" , "w" ) finalsvg . writelines ( self . final_molecule ) finalsvg . close ( )
def out_interactions_iter ( self , nbunch = None , t = None ) : """Return an iterator over the out interactions present in a given snapshot . Edges are returned as tuples in the order ( node , neighbor ) . Parameters nbunch : iterable container , optional ( default = all nodes ) A container of nodes . The...
if nbunch is None : nodes_nbrs_succ = self . _succ . items ( ) else : nodes_nbrs_succ = [ ( n , self . _succ [ n ] ) for n in self . nbunch_iter ( nbunch ) ] for n , nbrs in nodes_nbrs_succ : for nbr in nbrs : if t is not None : if self . __presence_test ( n , nbr , t ) : ...
def _get_api_params ( api_url = None , api_version = None , api_key = None ) : '''Retrieve the API params from the config file .'''
mandrill_cfg = __salt__ [ 'config.merge' ] ( 'mandrill' ) if not mandrill_cfg : mandrill_cfg = { } return { 'api_url' : api_url or mandrill_cfg . get ( 'api_url' ) or BASE_URL , # optional 'api_key' : api_key or mandrill_cfg . get ( 'key' ) , # mandatory 'api_version' : api_version or mandrill_cfg . get ( 'api_vers...
def get_composers ( self , * args , ** kwargs ) : """Convenience method for ` get _ music _ library _ information ` with ` ` search _ type = ' composers ' ` ` . For details of other arguments , see ` that method < # soco . music _ library . MusicLibrary . get _ music _ library _ information > ` _ ."""
args = tuple ( [ 'composers' ] + list ( args ) ) return self . get_music_library_information ( * args , ** kwargs )
def create_axes ( self , axes , obj , validate = True , nan_rep = None , data_columns = None , min_itemsize = None , ** kwargs ) : """create and return the axes leagcy tables create an indexable column , indexable index , non - indexable fields Parameters : axes : a list of the axes in order to create ( nam...
# set the default axes if needed if axes is None : try : axes = _AXES_MAP [ type ( obj ) ] except KeyError : raise TypeError ( "cannot properly create the storer for: [group->{group}," "value->{value}]" . format ( group = self . group . _v_name , value = type ( obj ) ) ) # map axes to numbers ax...
def get_path_and_name ( full_name ) : """Split Whole Patch onto ' Patch ' and ' Name ' : param full _ name : < str > Full Resource Name - likes ' Root / Folder / Folder2 / Name ' : return : tuple ( Patch , Name )"""
if full_name : parts = full_name . split ( "/" ) return ( "/" . join ( parts [ 0 : - 1 ] ) , parts [ - 1 ] ) if len ( parts ) > 1 else ( "/" , full_name ) return None , None
def generate_split_tsv_lines ( fn , header ) : """Returns dicts with header - keys and psm statistic values"""
for line in generate_tsv_psms_line ( fn ) : yield { x : y for ( x , y ) in zip ( header , line . strip ( ) . split ( '\t' ) ) }
def absstart ( self ) : """Returns the absolute start of the element by including docstrings outside of the element definition if applicable ."""
if hasattr ( self , "docstart" ) and self . docstart > 0 : return self . docstart else : return self . start
def find_generator_as_statement ( node ) : """Finds a generator as a statement"""
return ( isinstance ( node , ast . Expr ) and isinstance ( node . value , ast . GeneratorExp ) )
def _apply_mask ( self , roi_mask ) : """Removes voxels outside the given mask or ROI set ."""
# TODO ensure compatible with input image # - must have < N dim and same size in moving dims . rows_to_delete = list ( ) # to allow for additional masks to be applied in the future if isinstance ( roi_mask , np . ndarray ) : # not ( roi _ mask is None or roi _ mask = = ' auto ' ) : self . _set_roi_mask ( roi_mask )...
def _af_filter ( data , in_file , out_file ) : """Soft - filter variants with AF below min _ allele _ fraction ( appends " MinAF " to FILTER )"""
min_freq = float ( utils . get_in ( data [ "config" ] , ( "algorithm" , "min_allele_fraction" ) , 10 ) ) / 100.0 logger . debug ( "Filtering MuTect2 calls with allele fraction threshold of %s" % min_freq ) ungz_out_file = "%s.vcf" % utils . splitext_plus ( out_file ) [ 0 ] if not utils . file_exists ( ungz_out_file ) a...
def _external2internal_lambda ( bound ) : """Make a lambda function which converts an single external ( constained ) parameter to a internal ( uncontrained ) parameter ."""
lower , upper = bound if lower is None and upper is None : # no constraints return lambda x : x elif upper is None : # only lower bound return lambda x : sqrt ( ( x - lower + 1. ) ** 2 - 1 ) elif lower is None : # only upper bound return lambda x : sqrt ( ( x - upper + 1. ) ** 2 - 1 ) else : return lamb...
def sudoers ( self , enable ) : """This method is used to enable / disable bash sudo commands running through the guestshell virtual service . By default sudo access is prevented due to the setting in the ' sudoers ' file . Therefore the setting must be disabled in the file to enable sudo commands . This me...
f_sudoers = "/isan/vdc_1/virtual-instance/guestshell+/rootfs/etc/sudoers" if enable is True : sed_cmd = r" 's/\(^Defaults *requiretty\)/#\1/g' " elif enable is False : sed_cmd = r" 's/^#\(Defaults *requiretty\)/\1/g' " else : raise RuntimeError ( 'enable must be True or False' ) self . guestshell ( "run bas...
def _execute ( self , ifile , process ) : """Default processing loop : param ifile : Input file object . : type ifile : file : param process : Bound method to call in processing loop . : type process : instancemethod : return : : const : ` None ` . : rtype : NoneType"""
self . _record_writer . write_records ( process ( self . _records ( ifile ) ) ) self . finish ( )
def location_path ( self , path ) : """Set the Location - Path of the response . : type path : String : param path : the Location - Path as a string"""
path = path . strip ( "/" ) tmp = path . split ( "?" ) path = tmp [ 0 ] paths = path . split ( "/" ) for p in paths : option = Option ( ) option . number = defines . OptionRegistry . LOCATION_PATH . number option . value = p self . add_option ( option )
def create_response_adu ( self , meta_data , response_pdu ) : """Build response ADU from meta data and response PDU and return it . : param meta _ data : A dict with meta data . : param request _ pdu : A bytearray containing request PDU . : return : A bytearray containing request ADU ."""
first_part_adu = struct . pack ( '>B' , meta_data [ 'unit_id' ] ) + response_pdu return first_part_adu + get_crc ( first_part_adu )
def get_multifile_object_child_location ( self , parent_location : str , child_name : str ) : """Implementation of the parent abstract method . In this mode the attribute is a file with the same prefix , separated from the parent object name by the character sequence < self . separator > : param parent _ loca...
check_var ( parent_location , var_types = str , var_name = 'parent_path' ) check_var ( child_name , var_types = str , var_name = 'item_name' ) # a child location is built by adding the separator between the child name and the parent location return parent_location + self . separator + child_name
def is_a_number ( s ) : """This takes an object and determines whether it ' s a number or a string representing a number ."""
if _s . fun . is_iterable ( s ) and not type ( s ) == str : return False try : float ( s ) return 1 except : try : complex ( s ) return 2 except : try : complex ( s . replace ( '(' , '' ) . replace ( ')' , '' ) . replace ( 'i' , 'j' ) ) return 2 ...
def propagateFrom ( self , startLayer , ** args ) : """Propagates activation through the network . Optionally , takes input layer names as keywords , and their associated activations . If input layer ( s ) are given , then propagate ( ) will return the output layer ' s activation . If there is more than one o...
for layerName in args : self [ layerName ] . copyActivations ( args [ layerName ] ) # initialize netinput : started = 0 for layer in self . layers : if layer . name == startLayer : started = 1 continue # don ' t set this one if not started : continue if layer . type != 'I...
def randomize ( self , period = None ) : """Randomize the permutation table used by the noise functions . This makes them generate a different noise pattern for the same inputs ."""
if period is not None : self . period = period perm = list ( range ( self . period ) ) perm_right = self . period - 1 for i in list ( perm ) : j = self . randint_function ( 0 , perm_right ) perm [ i ] , perm [ j ] = perm [ j ] , perm [ i ] self . permutation = tuple ( perm ) * 2
def promiscping ( net , timeout = 2 , fake_bcast = "ff:ff:ff:ff:ff:fe" , ** kargs ) : """Send ARP who - has requests to determine which hosts are in promiscuous mode promiscping ( net , iface = conf . iface )"""
ans , unans = srp ( Ether ( dst = fake_bcast ) / ARP ( pdst = net ) , filter = "arp and arp[7] = 2" , timeout = timeout , iface_hint = net , ** kargs ) # noqa : E501 ans = ARPingResult ( ans . res , name = "PROMISCPing" ) ans . display ( ) return ans , unans
def solve_with_cvxopt ( sdp , solverparameters = None ) : """Helper function to convert the SDP problem to PICOS and call CVXOPT solver , and parse the output . : param sdp : The SDP relaxation to be solved . : type sdp : : class : ` ncpol2sdpa . sdp ` ."""
P = convert_to_picos ( sdp ) P . set_option ( "solver" , "cvxopt" ) P . set_option ( "verbose" , sdp . verbose ) if solverparameters is not None : for key , value in solverparameters . items ( ) : P . set_option ( key , value ) solution = P . solve ( ) x_mat = [ np . array ( P . get_valued_variable ( 'X' ) ...
def unbind ( self , instance_id : str , binding_id : str , details : UnbindDetails ) : """Unbinding the instance see openbrokerapi documentation Raises : ErrBindingDoesNotExist : Binding does not exist ."""
# Find the instance instance = self . _backend . find ( instance_id ) # Find the binding binding = self . _backend . find ( binding_id , instance ) if not binding . isProvisioned ( ) : # The binding does not exist raise ErrBindingDoesNotExist ( ) # Delete the binding self . _backend . unbind ( binding )
def _send_request ( self , operation , url , payload , desc ) : """Send request to DCNM ."""
res = None try : payload_json = None if payload and payload != '' : payload_json = jsonutils . dumps ( payload ) self . _login ( ) desc_lookup = { 'POST' : ' creation' , 'PUT' : ' update' , 'DELETE' : ' deletion' , 'GET' : ' get' } res = requests . request ( operation , url , data = payload_...
def add_task ( self , task , parent_task_result ) : """Add a task to run with the specified result from this tasks parent ( can be None ) : param task : Task : task that should be run : param parent _ task _ result : object : value to be passed to task for setup"""
self . tasks . append ( ( task , parent_task_result ) ) self . task_id_to_task [ task . id ] = task
def get_or_create_model_key ( self ) : """Get or create key for the model . Returns ( model _ key , boolean ) tuple"""
model_cache_info = model_cache_backend . retrieve_model_cache_info ( self . model . _meta . db_table ) if not model_cache_info : return uuid . uuid4 ( ) . hex , True return model_cache_info . table_key , False
def get_subgraphs ( graph = None ) : """Given a graph of possibly disconnected components , generate all graphs of connected components . graph is a dictionary of dependencies . Keys are components , and values are sets of components on which they depend ."""
graph = graph or DEPENDENCIES keys = set ( graph ) frontier = set ( ) seen = set ( ) while keys : frontier . add ( keys . pop ( ) ) while frontier : component = frontier . pop ( ) seen . add ( component ) frontier |= set ( [ d for d in get_dependencies ( component ) if d in graph ] ) ...
def find ( self , ip ) : '''Find the abuse contact for a IP address : param ip : IPv4 or IPv6 address to check : type ip : string : returns : emails associated with IP : rtype : list : returns : none if no contact could be found : rtype : None : raises : : py : class : ` ValueError ` : if ip is not pr...
ip = ipaddr . IPAddress ( ip ) rev = reversename ( ip . exploded ) revip , _ = rev . split ( 3 ) lookup = revip . concatenate ( self . provider ) . to_text ( ) contacts = self . _get_txt_record ( lookup ) if contacts : return contacts . split ( ',' )
def create ( cls , user_id , github_id = None , name = None , ** kwargs ) : """Create the repository ."""
with db . session . begin_nested ( ) : obj = cls ( user_id = user_id , github_id = github_id , name = name , ** kwargs ) db . session . add ( obj ) return obj
def emails_parse ( emails_dict ) : """Parse the output of ` ` SESConnection . list _ verified _ emails ( ) ` ` and get a list of emails ."""
result = emails_dict [ 'ListVerifiedEmailAddressesResponse' ] [ 'ListVerifiedEmailAddressesResult' ] emails = [ email for email in result [ 'VerifiedEmailAddresses' ] ] return sorted ( emails )
def log ( self , logger = None , label = None , eager = False ) : '''Log query result consumption details to a logger . Args : logger : Any object which supports a debug ( ) method which accepts a str , such as a Python standard library logger object from the logging module . If logger is not provided or is...
if self . closed ( ) : raise ValueError ( "Attempt to call log() on a closed Queryable." ) if logger is None : return self if label is None : label = repr ( self ) if eager : return self . _create ( self . _eager_log_result ( logger , label ) ) return self . _create ( self . _generate_lazy_log_result ( ...
def zscore ( self , name , value ) : """Return the score of an element : param name : str the name of the redis key : param value : the element in the sorted set key : return : Future ( )"""
with self . pipe as pipe : return pipe . zscore ( self . redis_key ( name ) , self . valueparse . encode ( value ) )
def fetch_ticker ( self ) -> Ticker : """Fetch the market ticker ."""
return self . _fetch ( 'ticker' , self . market . code ) ( self . _ticker ) ( )
def _format_token ( self , dt , token , locale ) : """Formats a DateTime instance with a given token and locale . : param dt : The instance to format : type dt : pendulum . DateTime : param token : The token to use : type token : str : param locale : The locale to use : type locale : Locale : rtype : ...
if token in self . _DATE_FORMATS : fmt = locale . get ( "custom.date_formats.{}" . format ( token ) ) if fmt is None : fmt = self . _DEFAULT_DATE_FORMATS [ token ] return self . format ( dt , fmt , locale ) if token in self . _LOCALIZABLE_TOKENS : return self . _format_localizable_token ( dt , t...
def update ( self , entries = { } , * args , ** kwargs ) : """Update dictionary . @ example : object . update ( { ' foo ' : { ' bar ' : 1 } } )"""
if isinstance ( entries , dict ) : entries = self . _reject_reserved_keys ( entries ) for key , value in dict ( entries , * args , ** kwargs ) . items ( ) : if isinstance ( value , dict ) : self . __dict__ [ key ] = AttributeDict ( value ) else : self . __dict__ [ key ] = value self . _refre...
def send_produce_request ( self , payloads = ( ) , acks = 1 , timeout = 1000 , fail_on_error = True , callback = None ) : """Encode and send some ProduceRequests ProduceRequests will be grouped by ( topic , partition ) and then sent to a specific broker . Output is a list of responses in the same order as the...
encoder = functools . partial ( KafkaProtocol . encode_produce_request , acks = acks , timeout = timeout ) if acks == 0 : decoder = None else : decoder = KafkaProtocol . decode_produce_response resps = self . _send_broker_aware_request ( payloads , encoder , decoder ) return [ resp if not callback else callback...
def memoize ( func ) : '''Memoize aka cache the return output of a function given a specific set of arguments . . versionedited : : 2016.3.4 Added * * kwargs support .'''
cache = { } @ wraps ( func ) def _memoize ( * args , ** kwargs ) : str_args = [ ] for arg in args : if not isinstance ( arg , six . string_types ) : str_args . append ( six . text_type ( arg ) ) else : str_args . append ( arg ) args_ = ',' . join ( list ( str_args ) +...
def get_address ( self , stream ) : """Text representation of the network address of a connection stream . Notes This method is thread - safe"""
try : addr = ":" . join ( str ( part ) for part in stream . KATCPServer_address ) except AttributeError : # Something weird happened , but keep trucking addr = '<error>' self . _logger . warn ( 'Could not determine address of stream' , exc_info = True ) return addr
def as_set ( self , decode = False ) : """Return a Python set containing all the items in the collection ."""
items = self . database . smembers ( self . key ) return set ( _decode ( item ) for item in items ) if decode else items
def _render_item ( self , dstack , key , value = None , ** settings ) : """Format single tree line ."""
cur_depth = len ( dstack ) - 1 treeptrn = '' s = self . _es_text ( settings , settings [ self . SETTING_TREE_FORMATING ] ) for ds in dstack : treeptrn += ' ' + self . fmt_text ( self . tchar ( settings [ self . SETTING_TREE_STYLE ] , cur_depth , * ds ) , ** s ) + '' strptrn = "{}" if value is not None : strptrn...
def compare_commits ( self , base , head ) : """Compare two commits . : param str base : ( required ) , base for the comparison : param str head : ( required ) , compare this against base : returns : : class : ` Comparison < github3 . repos . comparison . Comparison > ` if successful , else None"""
url = self . _build_url ( 'compare' , base + '...' + head , base_url = self . _api ) json = self . _json ( self . _get ( url ) , 200 ) return Comparison ( json ) if json else None
def _get_worker_pools_names ( worker_pools : list ) : """May contain sensitive info ( like user ids ) . Use with care ."""
return FormattedText ( ) . join ( [ FormattedText ( ) . newline ( ) . normal ( " - {name}" ) . start_format ( ) . bold ( name = worker . name ) . end_format ( ) for worker in worker_pools ] )
def process ( hw_num : int , problems_to_do : Optional [ Iterable [ int ] ] = None , prefix : Optional [ Path ] = None , by_hand : Optional [ Iterable [ int ] ] = None , ) -> None : """Process the homework problems in ` ` prefix ` ` folder . Arguments hw _ num The number of this homework problems _ to _ do ...
if prefix is None : prefix = Path ( "." ) problems : Iterable [ Path ] if problems_to_do is None : # The glob syntax here means a the filename must start with # homework - , be followed the homework number , followed by a # dash , then a digit representing the problem number for this # homework number , then any nu...
def write_pa11y_config ( item ) : """The only way that pa11y will see the same page that scrapy sees is to make sure that pa11y requests the page with the same headers . However , the only way to configure request headers with pa11y is to write them into a config file . This function will create a config fi...
config = { "page" : { "headers" : item [ "request_headers" ] , } , } config_file = tempfile . NamedTemporaryFile ( mode = "w" , prefix = "pa11y-config-" , suffix = ".json" , delete = False ) json . dump ( config , config_file ) config_file . close ( ) return config_file
def objective_bounds ( self ) : """Return objective bounds Returns lower : list of floats Lower boundaries for the objectives Upper : list of floats Upper boundaries for the objectives"""
if self . ideal and self . nadir : return self . ideal , self . nadir raise NotImplementedError ( "Ideal and nadir value calculation is not yet implemented" )
def generate_synthetic_magnitudes ( aval , bval , mmin , mmax , nyears ) : '''Generates a synthetic catalogue for a specified number of years , with magnitudes distributed according to a truncated Gutenberg - Richter distribution : param float aval : a - value : param float bval : b - value : param fl...
nsamples = int ( np . round ( nyears * ( 10. ** ( aval - bval * mmin ) ) , 0 ) ) year = np . random . randint ( 0 , nyears , nsamples ) # Get magnitudes mags = generate_trunc_gr_magnitudes ( bval , mmin , mmax , nsamples ) return { 'magnitude' : mags , 'year' : np . sort ( year ) }
def label_wrap ( self , label ) : """Label text for plot ."""
wrapped_label = r"%s\n%s" % ( label , self [ label ] . name . replace ( "," , r"\n" ) ) return wrapped_label
def substructure ( mol , query , largest_only = True , ignore_hydrogen = True ) : """if mol is a substructure of the query , return True Args : mol : Compound query : Compound largest _ only : compare only largest graph molecule"""
def subset_filter ( cnt1 , cnt2 ) : diff = cnt2 diff . subtract ( cnt1 ) if any ( v < 0 for v in diff . values ( ) ) : return True if not ( len ( mol ) and len ( query ) ) : return False # two blank molecules are not isomorphic m = molutil . clone ( mol ) q = molutil . clone ( query ) if lar...
def generate ( regex , Ns ) : "Return the strings matching regex whose length is in Ns ."
return sorted ( regex_parse ( regex ) [ 0 ] ( Ns ) , key = lambda s : ( len ( s ) , s ) )
def build_service_class ( metadata ) : """Generate a service class for the service contained in the specified metadata class ."""
i = importlib . import_module ( metadata ) service = i . service env = get_jinja_env ( ) service_template = env . get_template ( 'service.py.jinja2' ) with open ( api_path ( service . name . lower ( ) ) , 'w' ) as t : t . write ( service_template . render ( service_md = service ) )
def _read_indexlist ( self , name ) : """Read a list of indexes ."""
setattr ( self , '_' + name , [ self . _timeline [ int ( i ) ] for i in self . db . lrange ( 'site:{0}' . format ( name ) , 0 , - 1 ) ] )
async def setex ( self , name , time , value ) : """Set the value of key ` ` name ` ` to ` ` value ` ` that expires in ` ` time ` ` seconds . ` ` time ` ` can be represented by an integer or a Python timedelta object ."""
if isinstance ( time , datetime . timedelta ) : time = time . seconds + time . days * 24 * 3600 return await self . execute_command ( 'SETEX' , name , time , value )
def zhuyin_to_pinyin ( s , accented = True ) : """Convert all Zhuyin syllables in * s * to Pinyin . If * accented * is ` ` True ` ` , diacritics are added to the Pinyin syllables . If it ' s ` ` False ` ` , numbers are used to indicate tone ."""
if accented : function = _zhuyin_syllable_to_accented else : function = _zhuyin_syllable_to_numbered return _convert ( s , zhon . zhuyin . syllable , function )
def put ( self , robj , w = None , dw = None , pw = None , return_body = True , if_none_match = False , timeout = None ) : """Puts a ( possibly new ) object ."""
# We could detect quorum _ controls here but HTTP ignores # unknown flags / params . params = { 'returnbody' : return_body , 'w' : w , 'dw' : dw , 'pw' : pw , 'timeout' : timeout } bucket_type = self . _get_bucket_type ( robj . bucket . bucket_type ) url = self . object_path ( robj . bucket . name , robj . key , bucket...
def add_pip_package ( self , requirement ) : """Add a Python package dependency for this topology . If the package defined by the requirement specifier is not pre - installed on the build system then the package is installed using ` pip ` and becomes part of the Streams application bundle ( ` sab ` file ) ....
self . _pip_packages . append ( str ( requirement ) ) pr = pkg_resources . Requirement . parse ( requirement ) self . exclude_packages . add ( pr . project_name )
def remove_additional_model ( self , model_list_or_dict , core_objects_dict , model_name , model_key , destroy = True ) : """Remove one unnecessary model The method will search for the first model - object out of model _ list _ or _ dict that represents no core - object in the dictionary of core - objects hande...
if model_name == "income" : self . income . prepare_destruction ( ) self . income = None return for model_or_key in model_list_or_dict : model = model_or_key if model_key is None else model_list_or_dict [ model_or_key ] found = False for core_object in core_objects_dict . values ( ) : if...
def parse_link ( link_str ) : """Parse one - - link option to add to < rs : ln > links . Input string of the form : rel , href , att1 = val1 , att2 = val2"""
atts = { } help_str = "--link option '%s' (format rel,href,att1=val1...)" % ( link_str ) try : segs = link_str . split ( ',' ) # First segments are relation and subject atts [ 'rel' ] = segs . pop ( 0 ) atts [ 'href' ] = segs . pop ( 0 ) if ( atts [ 'href' ] == '' ) : raise ClientFatalError ...
def get_grade_entry_admin_session ( self ) : """Gets the ` ` OsidSession ` ` associated with the grade entry administration service . return : ( osid . grading . GradeEntryAdminSession ) - a ` ` GradeEntryAdminSession ` ` raise : OperationFailed - unable to complete request raise : Unimplemented - ` ` suppo...
if not self . supports_grade_entry_admin ( ) : raise errors . Unimplemented ( ) # pylint : disable = no - member return sessions . GradeEntryAdminSession ( runtime = self . _runtime )
def with_name ( self , name ) : """Sets the name scope for future operations ."""
self . _head = self . _head . with_name ( name ) return self
def sendRequest ( self , name , args ) : """sends a request to the peer"""
( respEvt , id ) = self . newResponseEvent ( ) self . sendMessage ( { "id" : id , "method" : name , "params" : args } ) return respEvt
def to_bool ( s ) : """Convert string ` s ` into a boolean . ` s ` can be ' true ' , ' True ' , 1 , ' false ' , ' False ' , 0. Examples : > > > to _ bool ( " true " ) True > > > to _ bool ( " 0 " ) False > > > to _ bool ( True ) True"""
if isinstance ( s , bool ) : return s elif s . lower ( ) in [ 'true' , '1' ] : return True elif s . lower ( ) in [ 'false' , '0' ] : return False else : raise ValueError ( "Can't cast '%s' to bool" % ( s ) )
def c_str ( string ) : """" Convert a python string to C string ."""
if not isinstance ( string , str ) : string = string . decode ( 'ascii' ) return ctypes . c_char_p ( string . encode ( 'utf-8' ) )
def is_enhanced_rr_cap_valid ( self ) : """Checks is enhanced route refresh capability is enabled / valid . Checks sent and received ` Open ` messages to see if this session with peer is capable of enhanced route refresh capability ."""
if not self . recv_open_msg : raise ValueError ( 'Did not yet receive peers open message.' ) err_cap_enabled = False local_caps = self . sent_open_msg . opt_param peer_caps = self . recv_open_msg . opt_param local_cap = [ cap for cap in local_caps if cap . cap_code == BGP_CAP_ENHANCED_ROUTE_REFRESH ] peer_cap = [ c...
def suddendeathmessage ( message ) : '''suddendeathmessage returns " 突然の死 " like ascii art decorated message string . : param str message : random unicode mixed text : rtype : str'''
msg_len = message_length ( message ) header_len = msg_len // 2 + 2 footer_len = ( msg_len // 2 ) * 2 + 1 footer_pattern = cycle ( [ "Y" , "^" ] ) header = "_" + "人" * header_len + "_" footer = " ̄" for _ in range ( footer_len ) : footer += next ( footer_pattern ) footer += " ̄" middle = "> " + message + " <" return "...
def run ( self ) : """For each file in noseOfYeti / specs , output nodes to represent each spec file"""
tokens = [ ] for name , spec in ( ( "Harpoon" , HarpoonSpec ( ) . harpoon_spec ) , ( "Image" , HarpoonSpec ( ) . image_spec ) ) : section = nodes . section ( ) section [ 'names' ] . append ( name ) section [ 'ids' ] . append ( name ) header = nodes . title ( ) header += nodes . Text ( name ) sec...
def display ( self ) : '''Return device width , height , rotation'''
w , h = ( 0 , 0 ) for line in self . shell ( 'dumpsys' , 'display' ) . splitlines ( ) : m = _DISPLAY_RE . search ( line , 0 ) if not m : continue w = int ( m . group ( 'width' ) ) h = int ( m . group ( 'height' ) ) o = int ( m . group ( 'orientation' ) ) w , h = min ( w , h ) , max ( w ,...
def field ( self ) : """Returns the field name that this column will have inside the database . : return < str >"""
if not self . __field : default_field = inflection . underscore ( self . __name ) if isinstance ( self , orb . ReferenceColumn ) : default_field += '_id' self . __field = default_field return self . __field or default_field
def remove_label ( self , label , relabel = False ) : """Remove the label number . The removed label is assigned a value of zero ( i . e . , background ) . Parameters label : int The label number to remove . relabel : bool , optional If ` True ` , then the segmentation image will be relabeled such t...
self . remove_labels ( label , relabel = relabel )
def shap_values ( self , X , y = None , tree_limit = None , approximate = False ) : """Estimate the SHAP values for a set of samples . Parameters X : numpy . array , pandas . DataFrame or catboost . Pool ( for catboost ) A matrix of samples ( # samples x # features ) on which to explain the model ' s output ....
# see if we have a default tree _ limit in place . if tree_limit is None : tree_limit = - 1 if self . model . tree_limit is None else self . model . tree_limit # shortcut using the C + + version of Tree SHAP in XGBoost , LightGBM , and CatBoost if self . feature_dependence == "tree_path_dependent" and self . model ...
def run_bash_jobs ( jobs : Iterator [ Job ] , directory : PathLike = Path . cwd ( ) , dry_run : bool = False ) -> None : """Submit commands to the bash shell . This function runs the commands iteratively but handles errors in the same way as with the pbs _ commands function . A command will run for all combin...
logger . debug ( "Running commands in bash shell" ) # iterate through command groups for job in jobs : # Check shell exists if shutil . which ( job . shell ) is None : raise ProcessLookupError ( f"The shell '{job.shell}' was not found." ) failed = False for command in job : for cmd in comman...
def unicode2encode ( text , charmap ) : '''charmap : dictionary which has both encode as key , unicode as value'''
if isinstance ( text , ( list , tuple ) ) : unitxt = '' for line in text : for val , key in charmap . items ( ) : if key in line : line = line . replace ( key , val ) # end of if val in text : unitxt += line # end of for line in text : return unitx...
def repeat_read_url_request ( url , headers = None , data = None , retries = 2 , logger = None ) : '''Allows for repeated http requests up to retries additional times'''
if logger : logger . debug ( "Retrieving url content: {}" . format ( url ) ) req = urllib2 . Request ( url , data , headers = headers or { } ) return repeat_call ( lambda : urllib2 . urlopen ( req ) . read ( ) , retries )
def annotate_powerlaw ( text , exp , startx , starty , width = None , rx = 0.5 , ry = 0.5 , ** kwargs ) : r'''Added a label to the middle of a power - law annotation ( see ` ` goosempl . plot _ powerlaw ` ` ) . : arguments : * * exp * * ( ` ` float ` ` ) The power - law exponent . * * startx , starty * * ( ...
# get options / defaults endx = kwargs . pop ( 'endx' , None ) endy = kwargs . pop ( 'endy' , None ) height = kwargs . pop ( 'height' , None ) units = kwargs . pop ( 'units' , 'relative' ) axis = kwargs . pop ( 'axis' , plt . gca ( ) ) # check if axis . get_xscale ( ) != 'log' or axis . get_yscale ( ) != 'log' : ra...
async def check_mailbox ( self , selected : SelectedMailbox , * , wait_on : Event = None , housekeeping : bool = False ) -> SelectedMailbox : """Checks for any updates in the mailbox . If ` ` wait _ on ` ` is given , this method should block until either this event is signalled or the mailbox has detected updat...
...
def _try_parse_formula ( self , compound_id , s ) : """Try to parse the given compound formula string . Logs a warning if the formula could not be parsed ."""
s = s . strip ( ) if s == '' : return None try : # Do not return the parsed formula . For now it is better to keep # the original formula string unchanged in all cases . formula . Formula . parse ( s ) except formula . ParseError : logger . warning ( 'Unable to parse compound formula {}: {}' . format ( comp...
def _overlay_for_saml_metadata ( self , config , co_name ) : """Overlay configuration details like organization and contact person from the front end configuration onto the IdP configuration to support SAML metadata generation . : type config : satosa . satosa _ config . SATOSAConfig : type co _ name : str ...
for co in self . config [ self . KEY_CO ] : if co [ self . KEY_ENCODEABLE_NAME ] == co_name : break key = self . KEY_ORGANIZATION if key in co : if key not in config : config [ key ] = { } for org_key in self . KEY_ORGANIZATION_KEYS : if org_key in co [ key ] : config [ k...