signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _get_cursor ( self , n_retries = 1 ) : """Returns a context manager for obtained from a single or pooled connection , and sets the PostgreSQL search _ path to the schema specified in the connection URL . Although * connections * are threadsafe , * cursors * are bound to connections and are * not * threa...
n_tries_rem = n_retries + 1 while n_tries_rem > 0 : try : conn = self . _pool . getconn ( ) if self . pooling else self . _conn # autocommit = True obviates closing explicitly conn . autocommit = True cur = conn . cursor ( cursor_factory = psycopg2 . extras . DictCursor ) cur...
def debug_async ( self , conn_id , cmd_name , cmd_args , progress_callback , callback ) : """Asynchronously complete a named debug command . The command name and arguments are passed to the underlying device adapter and interpreted there . If the command is long running , progress _ callback may be used to pr...
callback ( conn_id , self . id , False , None , "Debug commands are not supported by this DeviceAdapter" )
def create_ipsecpolicy ( name , profile = None , ** kwargs ) : '''Creates a new IPsecPolicy CLI Example : . . code - block : : bash salt ' * ' neutron . create _ ipsecpolicy ipsecpolicy - name transform _ protocol = esp auth _ algorithm = sha1 encapsulation _ mode = tunnel encryption _ algorithm = aes - 1...
conn = _auth ( profile ) return conn . create_ipsecpolicy ( name , ** kwargs )
def update ( self , table_name , where_slice , new_values ) : """where _ slice - A Data WHICH WILL BE USED TO MATCH ALL IN table eg { " id " : 42} new _ values - A dict WITH COLUMN NAME , COLUMN VALUE PAIRS TO SET"""
new_values = quote_param ( new_values ) where_clause = SQL_AND . join ( [ quote_column ( k ) + "=" + quote_value ( v ) if v != None else quote_column ( k ) + SQL_IS_NULL for k , v in where_slice . items ( ) ] ) command = ( "UPDATE " + quote_column ( table_name ) + "\n" + "SET " + sql_list ( [ quote_column ( k ) + "=" +...
def get_next_step ( self ) : """Find the proper step when user clicks the Next button . : returns : The step to be switched to . : rtype : WizardStep instance or None"""
subcategory = self . parent . step_kw_subcategory . selected_subcategory ( ) is_raster = is_raster_layer ( self . parent . layer ) has_classifications = get_classifications ( subcategory [ 'key' ] ) # Vector if not is_raster : return self . parent . step_kw_field # Raster and has classifications elif has_classifica...
async def apply_commandline ( self , cmdline ) : """interprets a command line string i . e . , splits it into separate command strings , instanciates : class : ` Commands < alot . commands . Command > ` accordingly and applies then in sequence . : param cmdline : command line to interpret : type cmdline :...
# remove initial spaces cmdline = cmdline . lstrip ( ) # we pass Commands one by one to ` self . apply _ command ` . # To properly call them in sequence , even if they trigger asyncronous # code ( return Deferreds ) , these applications happen in individual # callback functions which are then used as callback chain to ...
def run_directive ( self , name , arguments = None , options = None , content = None ) : """Generate directive node given arguments . Parameters name : str name of directive . arguments : list list of positional arguments . options : dict key value arguments . content : content content of the dire...
if options is None : options = { } if content is None : content = [ ] if arguments is None : arguments = [ ] direc , _ = directive ( name , self . language , self . document ) direc = direc ( name = name , arguments = arguments , options = options , content = content , lineno = self . node . line , content_...
def getRow ( self , key ) : """Get a row by value of the indexing columns . If the index is not specified , gets the only row of a dataframe with no indexing columns . Args : key : Tuple representing the index of the desired row . Returns : The row ."""
return Row ( self . _impl . getRow ( Tuple ( key ) . _impl ) )
def from_dict ( self , data ) : """Fill the current object with information from the specification"""
if "model" in data : model = data [ "model" ] self . description = model [ "description" ] if "description" in model else None self . package = model [ "package" ] if "package" in model else None self . extends = model [ "extends" ] if "extends" in model else [ ] self . entity_name = model [ "entity...
def get_filters ( self ) : """Returns a collection of momentjs filters"""
return dict ( moment_format = self . format , moment_calendar = self . calendar , moment_fromnow = self . from_now , )
def reference ( self , symbol , count = 1 ) : """However , if referenced , ensure that the counter is applied to the catch symbol ."""
if symbol == self . catch_symbol : self . catch_symbol_usage += count else : self . parent . reference ( symbol , count )
def make_regex ( separator ) : """Utility function to create regexp for matching escaped separators in strings ."""
return re . compile ( r'(?:' + re . escape ( separator ) + r')?((?:[^' + re . escape ( separator ) + r'\\]|\\.)+)' )
def replace ( cls , fileobj , old_pages , new_pages ) : """Replace old _ pages with new _ pages within fileobj . old _ pages must have come from reading fileobj originally . new _ pages are assumed to have the ' same ' data as old _ pages , and so the serial and sequence numbers will be copied , as will the...
if not len ( old_pages ) or not len ( new_pages ) : raise ValueError ( "empty pages list not allowed" ) # Number the new pages starting from the first old page . first = old_pages [ 0 ] . sequence for page , seq in izip ( new_pages , xrange ( first , first + len ( new_pages ) ) ) : page . sequence = seq pag...
def split_string ( str_src , spliters = None , elim_empty = False ) : # type : ( AnyStr , Union [ AnyStr , List [ AnyStr ] , None ] , bool ) - > List [ AnyStr ] """Split string by split character space ( ' ' ) and indent ( ' \t ' ) as default Examples : > > > StringClass . split _ string ( ' exec - ini test . i...
if is_string ( spliters ) : spliters = [ spliters ] if spliters is None or not spliters : spliters = [ ' ' , '\t' ] dest_strs = list ( ) src_strs = [ str_src ] while True : old_dest_strs = src_strs [ : ] for s in spliters : for src_s in src_strs : temp_strs = src_s . split ( s ) ...
def discover_by_file ( self , start_filepath , top_level_directory = None ) : """Run test discovery on a single file . Parameters start _ filepath : str The module file in which to start test discovery . top _ level _ directory : str The path to the top - level directoy of the project . This is the pare...
start_filepath = os . path . abspath ( start_filepath ) start_directory = os . path . dirname ( start_filepath ) if top_level_directory is None : top_level_directory = find_top_level_directory ( start_directory ) logger . debug ( 'Discovering tests in file: start_filepath=%r, ' 'top_level_directory=' , start_filepa...
def get_all_profiles ( store = 'local' ) : '''Gets all properties for all profiles in the specified store Args : store ( str ) : The store to use . This is either the local firewall policy or the policy defined by local group policy . Valid options are : - lgpo - local Default is ` ` local ` ` Retur...
return { 'Domain Profile' : get_all_settings ( profile = 'domain' , store = store ) , 'Private Profile' : get_all_settings ( profile = 'private' , store = store ) , 'Public Profile' : get_all_settings ( profile = 'public' , store = store ) }
def delete ( self , symbol , date_range = None ) : """Delete all chunks for a symbol . Which are , for the moment , fully contained in the passed in date _ range . Parameters symbol : ` str ` symbol name for the item date _ range : ` date . DateRange ` DateRange to delete ticks in"""
query = { SYMBOL : symbol } date_range = to_pandas_closed_closed ( date_range ) if date_range is not None : assert date_range . start and date_range . end query [ START ] = { '$gte' : date_range . start } query [ END ] = { '$lte' : date_range . end } else : # delete metadata on complete deletion self . ...
def get_models ( self , uniprot_acc ) : """Return all available models for a UniProt accession number . Args : uniprot _ acc ( str ) : UniProt ACC / ID Returns : dict : All available models in SWISS - MODEL for this UniProt entry"""
if uniprot_acc in self . all_models : return self . all_models [ uniprot_acc ] else : log . error ( '{}: no SWISS-MODELs available' . format ( uniprot_acc ) ) return None
def assemble_tlg_author_filepaths ( ) : """Reads TLG index and builds a list of absolute filepaths ."""
plaintext_dir_rel = '~/cltk_data/greek/text/tlg/plaintext/' plaintext_dir = os . path . expanduser ( plaintext_dir_rel ) filepaths = [ os . path . join ( plaintext_dir , x + '.TXT' ) for x in TLG_INDEX ] return filepaths
def create_streaming_endpoint ( access_token , name , description = "New Streaming Endpoint" , scale_units = "1" ) : '''Create Media Service Streaming Endpoint . Args : access _ token ( str ) : A valid Azure authentication token . name ( str ) : A Media Service Streaming Endpoint Name . description ( str ) ...
path = '/StreamingEndpoints' endpoint = '' . join ( [ ams_rest_endpoint , path ] ) body = '{ \ "Id":null, \ "Name":"' + name + '", \ "Description":"' + description + '", \ "Created":"0001-01-01T00:00:00", \ "LastModified":"0001-01-01T00:00:00", \ "State":null, \ "HostName":null, \ "ScaleUnits":"' + scal...
def fit ( self , vxvv , vxvv_err = None , pot = None , radec = False , lb = False , customsky = False , lb_to_customsky = None , pmllpmbb_to_customsky = None , tintJ = 10 , ntintJ = 1000 , integrate_method = 'dopr54_c' , ** kwargs ) : """NAME : fit PURPOSE : fit an Orbit to data using the current orbit as the...
pot = flatten_potential ( pot ) _check_potential_dim ( self , pot ) _check_consistent_units ( self , pot ) return self . _orb . fit ( vxvv , vxvv_err = vxvv_err , pot = pot , radec = radec , lb = lb , customsky = customsky , lb_to_customsky = lb_to_customsky , pmllpmbb_to_customsky = pmllpmbb_to_customsky , tintJ = tin...
def _template ( node_id , value = None ) : "Check if a template is assigned to it and render that with the value"
result = [ ] select_template_from_node = fetch_query_string ( 'select_template_from_node.sql' ) try : result = db . execute ( text ( select_template_from_node ) , node_id = node_id ) template_result = result . fetchone ( ) result . close ( ) if template_result and template_result [ 'name' ] : te...
def _format_comments ( ret , comments ) : '''DRY code for joining comments together and conditionally adding a period at the end , and adding this comment string to the state return dict .'''
if isinstance ( comments , six . string_types ) : ret [ 'comment' ] = comments else : ret [ 'comment' ] = '. ' . join ( comments ) if len ( comments ) > 1 : ret [ 'comment' ] += '.' return ret
def _get_fd ( fileobj ) : """Get a descriptor out of a file object . : param fileobj : An integer ( existing descriptor ) or any object having the ` fileno ( ) ` method . : raises ValueError : if the descriptor cannot be obtained or if the descriptor is invalid : returns : file descriptor number"""
if isinstance ( fileobj , int ) : fd = fileobj else : try : fd = fileobj . fileno ( ) except AttributeError : fd = None if fd is None or fd < 0 : raise ValueError ( "invalid fileobj: {!r}" . format ( fileobj ) ) return fd
def _getZoomLevelRange ( self , resolution , unit = 'meters' ) : "Return lower and higher zoom level given a resolution"
assert unit in ( 'meters' , 'degrees' ) if unit == 'meters' and self . unit == 'degrees' : resolution = resolution / self . metersPerUnit elif unit == 'degrees' and self . unit == 'meters' : resolution = resolution * EPSG4326_METERS_PER_UNIT lo = 0 hi = len ( self . RESOLUTIONS ) while lo < hi : mid = ( lo ...
def jarsign ( storepass , keypass , keystore , source , alias , path = None ) : """Uses Jarsign to sign an apk target file using the provided keystore information . : param storepass ( str ) - keystore storepass : param keypass ( str ) - keystore keypass : param keystore ( str ) - keystore file path : param...
cmd = [ 'jarsigner' , '-verbose' , '-storepass' , storepass , '-keypass' , keypass , '-keystore' , keystore , source , alias ] common . run_cmd ( cmd , log = 'jarsign.log' , cwd = path )
def routingAreaUpdateRequest ( PTmsiSignature_presence = 0 , GprsTimer_presence = 0 , DrxParameter_presence = 0 , TmsiStatus_presence = 0 ) : """ROUTING AREA UPDATE REQUEST Section 9.4.14"""
a = TpPd ( pd = 0x3 ) b = MessageType ( mesType = 0x8 ) # 00001000 c = UpdateTypeAndCiphKeySeqNr ( ) e = RoutingAreaIdentification ( ) f = MsNetworkCapability ( ) packet = a / b / c / e / f if PTmsiSignature_presence is 1 : g = PTmsiSignature ( ieiPTS = 0x19 ) packet = packet / g if GprsTimer_presence is 1 : ...
def env ( client , paths , opt ) : """Renders a shell snippet based on paths in a Secretfile"""
old_prefix = False old_prefix = opt . prefix and not ( opt . add_prefix or opt . add_suffix or not opt . merge_path ) if old_prefix : LOG . warning ( "the prefix option is deprecated " "please use" "--no-merge-path --add-prefix $OLDPREFIX_ instead" ) elif opt . prefix : LOG . warning ( "the prefix option is dep...
def flush ( self , using = None , ** kwargs ) : """Preforms a flush operation on the index . Any additional keyword arguments will be passed to ` ` Elasticsearch . indices . flush ` ` unchanged ."""
return self . _get_connection ( using ) . indices . flush ( index = self . _name , ** kwargs )
def VxLANTunnelState_originator_switch_info_switchIpV6Address ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) VxLANTunnelState = ET . SubElement ( config , "VxLANTunnelState" , xmlns = "http://brocade.com/ns/brocade-notification-stream" ) originator_switch_info = ET . SubElement ( VxLANTunnelState , "originator-switch-info" ) switchIpV6Address = ET . SubElement ( originator_switch_info , "swi...
def progress ( status_code ) : """Translate PROGRESS status codes from GnuPG to messages ."""
lookup = { 'pk_dsa' : 'DSA key generation' , 'pk_elg' : 'Elgamal key generation' , 'primegen' : 'Prime generation' , 'need_entropy' : 'Waiting for new entropy in the RNG' , 'tick' : 'Generic tick without any special meaning - still working.' , 'starting_agent' : 'A gpg-agent was started.' , 'learncard' : 'gpg-agent or ...
def update_records ( self , records , scope_identifier , hub_name , plan_id , timeline_id ) : """UpdateRecords . : param : class : ` < VssJsonCollectionWrapper > < azure . devops . v5_0 . task . models . VssJsonCollectionWrapper > ` records : : param str scope _ identifier : The project GUID to scope the reques...
route_values = { } if scope_identifier is not None : route_values [ 'scopeIdentifier' ] = self . _serialize . url ( 'scope_identifier' , scope_identifier , 'str' ) if hub_name is not None : route_values [ 'hubName' ] = self . _serialize . url ( 'hub_name' , hub_name , 'str' ) if plan_id is not None : route_...
def close ( self ) : """Closes the lvm handle . Usually you would never need to use this method unless you are trying to do operations using the ctypes function wrappers in conversion . py * Raises : * * HandleError"""
if self . handle : q = lvm_quit ( self . handle ) if q != 0 : raise HandleError ( "Failed to close LVM handle." ) self . __handle = None
def bump ( self , kind = None , prerelease = None , inplace = True ) : '''Increment the version and / or pre - release value Parameters kind : str Increment the version . Can be ` ` major ` ` , ` ` minor ` ` , or ` ` patch ` ` , corresponding to the three segments of the version number ( in order ) . A va...
if kind is not None : # if already in pre - release and we want to move to pre - release , # increment version + prerelease if self . prerelease and prerelease : new_prerelease = self . _increment_prerelease ( None , prerelease ) new_version = self . _increment_version ( self . version , kind ) ...
def get_corpus_reader ( corpus_name : str = None , language : str = None ) -> CorpusReader : """Corpus reader factory method : param corpus _ name : the name of the supported corpus , available as : [ package ] . SUPPORTED _ CORPORA : param langugage : the language for search in : return : NLTK compatible cor...
BASE = '~/cltk_data/{}/text' . format ( language ) root = os . path . join ( os . path . expanduser ( BASE ) , corpus_name ) if not os . path . exists ( root ) or corpus_name not in SUPPORTED_CORPORA . get ( language ) : raise ValueError ( 'Specified corpus data not found, please install {} for language: {}' . form...
def upload ( self , file_descriptor , settings ) : """Загружает файл в облако : param file _ descriptor : открытый дескриптор : param settings : настройки загрузки : rtype : requests . Response"""
multipart_form_data = { 'file' : file_descriptor } params = { "settings" : json . dumps ( settings ) } dr = self . __app . native_api_call ( 'media' , 'upload' , params , self . __options , True , multipart_form_data , False , http_path = "/api/meta/v1/" , http_method = 'POST' , connect_timeout_sec = 60 * 10 ) return j...
def loads ( cls , pickle_string ) : """Equivalent to pickle . loads except that the HoloViews trees is restored appropriately ."""
cls . load_counter_offset = StoreOptions . id_offset ( ) val = pickle . loads ( pickle_string ) cls . load_counter_offset = None return val
def neg_loglik ( self , beta ) : """Creates the negative log likelihood of the model Parameters beta : np . array Contains untransformed starting values for latent variables Returns The negative log logliklihood of the model"""
_ , _ , _ , F , v = self . _model ( self . data , beta ) loglik = 0.0 for i in range ( 0 , self . data . shape [ 0 ] ) : loglik += np . linalg . slogdet ( F [ : , : , i ] ) [ 1 ] + np . dot ( v [ i ] , np . dot ( np . linalg . pinv ( F [ : , : , i ] ) , v [ i ] ) ) return - ( - ( ( self . data . shape [ 0 ] / 2 ) *...
def md_to_pdf ( input_name , output_name ) : """Converts an input MarkDown file to a PDF of the given output name . Parameters input _ name : String Relative file location of the input file to where this function is being called . output _ name : String Relative file location of the output file to where t...
if output_name [ - 4 : ] == '.pdf' : os . system ( "pandoc " + input_name + " -o " + output_name ) else : os . system ( "pandoc " + input_name + " -o " + output_name + ".pdf" )
def initialize_state ( self ) : """Call this to initialize the state of the UI after everything has been connected ."""
if self . __hardware_source : self . __data_item_states_changed_event_listener = self . __hardware_source . data_item_states_changed_event . listen ( self . __data_item_states_changed ) self . __acquisition_state_changed_event_listener = self . __hardware_source . acquisition_state_changed_event . listen ( self...
def list_cidr_ips ( cidr ) : '''Get a list of IP addresses from a CIDR . CLI example : : salt myminion netaddress . list _ cidr _ ips 192.168.0.0/20'''
ips = netaddr . IPNetwork ( cidr ) return [ six . text_type ( ip ) for ip in list ( ips ) ]
def _logjacobian ( self ) : """Calculates the logjacobian of the current parameters ."""
if self . sampling_transforms is None : logj = 0. else : logj = self . sampling_transforms . logjacobian ( ** self . current_params ) return logj
def scene_name ( sequence_number , scene_id , name ) : """Create a scene . name message"""
return MessageWriter ( ) . string ( "scene.name" ) . uint64 ( sequence_number ) . uint32 ( scene_id ) . string ( name ) . get ( )
def _add_sensor ( self , sensor ) : """Add a new sensor to the tree . Parameters sensor : : class : ` katcp . Sensor ` object New sensor to add to the tree ."""
self . _parent_to_children [ sensor ] = set ( ) self . _child_to_parents [ sensor ] = set ( )
def _update_alignment ( self , alignment ) : """Updates vertical text alignment button Parameters alignment : String in [ " top " , " middle " , " right " ] \t Switches button to untoggled if False and toggled if True"""
states = { "top" : 2 , "middle" : 0 , "bottom" : 1 } self . alignment_tb . state = states [ alignment ] self . alignment_tb . toggle ( None ) self . alignment_tb . Refresh ( )
def send_heartbeat ( self ) : """Todo"""
self . logger . debug ( "heartbeat " + str ( self . t . sequence ) ) self . t . ws . send ( json . dumps ( { 'op' : self . t . HEARTBEAT , 'd' : self . t . sequence } ) )
def _maybe_start_instance ( instance ) : """Starts instance if it ' s stopped , no - op otherwise ."""
if not instance : return if instance . state [ 'Name' ] == 'stopped' : instance . start ( ) while True : print ( f"Waiting for {instance} to start." ) instance . reload ( ) if instance . state [ 'Name' ] == 'running' : break time . sleep ( 10 )
def run ( self , ** options ) : """Override runserver ' s entry point to bring Gunicorn on . A large portion of code in this method is copied from ` django . core . management . commands . runserver ` ."""
shutdown_message = options . get ( 'shutdown_message' , '' ) self . stdout . write ( "Performing system checks...\n\n" ) self . check ( display_num_errors = True ) self . check_migrations ( ) now = datetime . datetime . now ( ) . strftime ( r'%B %d, %Y - %X' ) if six . PY2 : now = now . decode ( get_system_encoding...
def read_unicode ( path , encoding , encoding_errors ) : """Return the contents of a file as a unicode string ."""
try : f = open ( path , 'rb' ) return make_unicode ( f . read ( ) , encoding , encoding_errors ) finally : f . close ( )
def metric_get ( self , project , metric_name ) : """API call : retrieve a metric resource . : type project : str : param project : ID of the project containing the metric . : type metric _ name : str : param metric _ name : the name of the metric : rtype : dict : returns : The metric object returned fr...
path = "projects/%s/metrics/%s" % ( project , metric_name ) metric_pb = self . _gapic_api . get_log_metric ( path ) # NOTE : LogMetric message type does not have an ` ` Any ` ` field # so ` MessageToDict ` ` can safely be used . return MessageToDict ( metric_pb )
def mean ( attrs , inputs , proto_obj ) : """Mean of all the input tensors ."""
concat_input = [ symbol . expand_dims ( op_input , axis = 0 ) for op_input in inputs ] concat_sym = symbol . concat ( * concat_input , dim = 0 ) mean_sym = symbol . mean ( concat_sym , axis = 0 ) return mean_sym , attrs , inputs
def signed_raw ( self ) -> str : """Return Revocation signed raw document string : return :"""
if not isinstance ( self . identity , Identity ) : raise MalformedDocumentError ( "Can not return full revocation document created from inline" ) raw = self . raw ( ) signed = "\n" . join ( self . signatures ) signed_raw = raw + signed + "\n" return signed_raw
def when ( self , case_expr , result_expr ) : """Add a new case - result pair . Parameters case : Expr Expression to equality - compare with base expression . Must be comparable with the base . result : Expr Value when the case predicate evaluates to true . Returns builder : CaseBuilder"""
case_expr = ir . as_value_expr ( case_expr ) result_expr = ir . as_value_expr ( result_expr ) if not rlz . comparable ( self . base , case_expr ) : raise TypeError ( 'Base expression and passed case are not ' 'comparable' ) cases = list ( self . cases ) cases . append ( case_expr ) results = list ( self . results )...
def build_bsub_command ( command_template , lsf_args ) : """Build and return a lsf batch command template The structure will be ' bsub - s < key > < value > < command _ template > ' where < key > and < value > refer to items in lsf _ args"""
if command_template is None : return "" full_command = 'bsub -o {logfile}' for key , value in lsf_args . items ( ) : full_command += ' -%s' % key if value is not None : full_command += ' %s' % value full_command += ' %s' % command_template return full_command
def bgread ( stream , blockSizeLimit = 65535 , pollTime = .03 , closeStream = True ) : '''bgread - Start a thread which will read from the given stream in a non - blocking fashion , and automatically populate data in the returned object . @ param stream < object > - A stream on which to read . Socket , file , etc...
try : pollTime = float ( pollTime ) except ValueError : raise ValueError ( 'Provided poll time must be a float.' ) if not hasattr ( stream , 'read' ) and not hasattr ( stream , 'recv' ) : raise ValueError ( 'Cannot read off provided stream, does not implement "read" or "recv"' ) if blockSizeLimit is not Non...
def apply_correlation ( self , sites , imt , residuals , stddev_intra = 0 ) : """Apply correlation to randomly sampled residuals . : param sites : : class : ` ~ openquake . hazardlib . site . SiteCollection ` residuals were sampled for . : param imt : Intensity measure type object , see : mod : ` openquak...
# intra - event residual for a single relization is a product # of lower - triangle decomposed correlation matrix and vector # of N random numbers ( where N is equal to number of sites ) . # we need to do that multiplication once per realization # with the same matrix and different vectors . try : corma = self . ca...
def reset ( self ) : """Remove all annotations from window ."""
self . idx_annotations . setText ( 'Load Annotation File...' ) self . idx_rater . setText ( '' ) self . annot = None self . dataset_markers = None # remove dataset marker self . idx_marker . clearContents ( ) self . idx_marker . setRowCount ( 0 ) # remove summary statistics w1 = self . idx_summary . takeAt ( 1 ) . widg...
def settle ( self , channel_identifier : ChannelID , transferred_amount : TokenAmount , locked_amount : TokenAmount , locksroot : Locksroot , partner : Address , partner_transferred_amount : TokenAmount , partner_locked_amount : TokenAmount , partner_locksroot : Locksroot , given_block_identifier : BlockSpecification ,...
log_details = { 'channel_identifier' : channel_identifier , 'token_network' : pex ( self . address ) , 'node' : pex ( self . node_address ) , 'partner' : pex ( partner ) , 'transferred_amount' : transferred_amount , 'locked_amount' : locked_amount , 'locksroot' : encode_hex ( locksroot ) , 'partner_transferred_amount' ...
def predicates ( G : Graph , n : Node ) -> Set [ TriplePredicate ] : """redicates ( G , n ) is the set of predicates in neigh ( G , n ) . predicates ( G , n ) = predicatesOut ( G , n ) ∪ predicatesIn ( G , n )"""
return predicatesOut ( G , n ) | predicatesIn ( G , n )
def domains ( request ) : """A page with number of services and layers faceted on domains ."""
url = '' query = '*:*&facet=true&facet.limit=-1&facet.pivot=domain_name,service_id&wt=json&indent=true&rows=0' if settings . SEARCH_TYPE == 'elasticsearch' : url = '%s/select?q=%s' % ( settings . SEARCH_URL , query ) if settings . SEARCH_TYPE == 'solr' : url = '%s/solr/hypermap/select?q=%s' % ( settings . SEARC...
def waitForCompletion ( self ) : """Wait for all threads to complete their work The worker threads are told to quit when they receive a task that is a tuple of ( None , None ) . This routine puts as many of those tuples in the task queue as there are threads . As soon as a thread receives one of these tuple...
for x in range ( self . numberOfThreads ) : self . taskQueue . put ( ( None , None ) ) for t in self . threadList : # print " attempting to join % s " % t . getName ( ) t . join ( )
def get_lr_scheduler ( scheduler_type : str , updates_per_checkpoint : int , learning_rate_half_life : int , learning_rate_reduce_factor : float , learning_rate_reduce_num_not_improved : int , learning_rate_schedule : Optional [ List [ Tuple [ float , int ] ] ] = None , learning_rate_warmup : Optional [ int ] = 0 ) -> ...
check_condition ( learning_rate_schedule is None or scheduler_type == C . LR_SCHEDULER_FIXED_STEP , "Learning rate schedule can only be used with '%s' learning rate scheduler." % C . LR_SCHEDULER_FIXED_STEP ) if scheduler_type is None : return None if scheduler_type == C . LR_SCHEDULER_FIXED_RATE_INV_SQRT_T : r...
def get_nested_dicts_with_key_containing_value ( parent_dict : dict , key , value ) : """Return all nested dictionaries that contain a key with a specific value . A sub - case of NestedLookup ."""
references = [ ] NestedLookup ( parent_dict , references , NestedLookup . key_value_containing_value_factory ( key , value ) ) return ( document for document , _ in references )
def value ( self , value ) : """set the value"""
# for the indep direction we also allow a string which points to one # of the other available dimensions # TODO : support c , fc , ec ? if isinstance ( value , common . basestring ) and value in [ 'x' , 'y' , 'z' ] : # we ' ll cast just to get rid of any python2 unicodes self . _value = str ( value ) dimension ...
def smsc ( self , smscNumber ) : """Set the default SMSC number to use when sending SMS messages"""
if smscNumber != self . _smscNumber : if self . alive : self . write ( 'AT+CSCA="{0}"' . format ( smscNumber ) ) self . _smscNumber = smscNumber
def get_bounds ( self ) : """Extracts the bounds of all the inputs of the domain of the * model *"""
bounds = [ ] for variable in self . space_expanded : bounds += variable . get_bounds ( ) return bounds
def _strip_commas ( cls , kw ) : "Strip out any leading / training commas from the token"
kw = kw [ : - 1 ] if kw [ - 1 ] == ',' else kw return kw [ 1 : ] if kw [ 0 ] == ',' else kw
def rouwenhorst ( rho , sigma , N ) : """Approximate an AR1 process by a finite markov chain using Rouwenhorst ' s method . : param rho : autocorrelation of the AR1 process : param sigma : conditional standard deviation of the AR1 process : param N : number of states : return [ nodes , P ] : equally spaced ...
from numpy import sqrt , linspace , array , zeros sigma = float ( sigma ) if N == 1 : nodes = array ( [ 0.0 ] ) transitions = array ( [ [ 1.0 ] ] ) return [ nodes , transitions ] p = ( rho + 1 ) / 2 q = p nu = sqrt ( ( N - 1 ) / ( 1 - rho ** 2 ) ) * sigma nodes = linspace ( - nu , nu , N ) sig_a = sigma n =...
def send_reset_password_instructions ( user ) : # type : ( User ) - > None """Send the reset password instructions email for the specified user . : param user : The user to send the instructions to"""
token = generate_reset_password_token ( user ) url = url_for ( "login.reset_password" , token = token ) reset_link = request . url_root [ : - 1 ] + url subject = _ ( "Password reset instruction for {site_name}" ) . format ( site_name = current_app . config . get ( "SITE_NAME" ) ) mail_template = "password_reset_instruc...
def get_feature_state ( self , feature_id , user_scope ) : """GetFeatureState . [ Preview API ] Get the state of the specified feature for the given user / all - users scope : param str feature _ id : Contribution id of the feature : param str user _ scope : User - Scope at which to get the value . Should be ...
route_values = { } if feature_id is not None : route_values [ 'featureId' ] = self . _serialize . url ( 'feature_id' , feature_id , 'str' ) if user_scope is not None : route_values [ 'userScope' ] = self . _serialize . url ( 'user_scope' , user_scope , 'str' ) response = self . _send ( http_method = 'GET' , loc...
def create ( self ) : """Create an instance of the Access Control Service with the typical starting settings ."""
self . service . create ( ) # Set environment variables for immediate use predix . config . set_env_value ( self . use_class , 'uri' , self . _get_uri ( ) ) predix . config . set_env_value ( self . use_class , 'zone_id' , self . _get_zone_id ( ) )
def _get_project_name ( args ) : """Get project name ."""
name = args . get ( 0 ) puts ( "" ) while not name : name = raw_input ( "What is the project's short directory name? (e.g. my_project) " ) return name
def read_lsm_eventlist ( fh ) : """Read LSM events from file and return as list of ( time , type , text ) ."""
count = struct . unpack ( '<II' , fh . read ( 8 ) ) [ 1 ] events = [ ] while count > 0 : esize , etime , etype = struct . unpack ( '<IdI' , fh . read ( 16 ) ) etext = bytes2str ( stripnull ( fh . read ( esize - 16 ) ) ) events . append ( ( etime , etype , etext ) ) count -= 1 return events
def parse ( self , instrs ) : """Parse an IR instruction ."""
instrs_reil = [ ] try : for instr in instrs : instr_lower = instr . lower ( ) # If the instruction to parsed is not in the cache , # parse it and add it to the cache . if instr_lower not in self . _cache : self . _cache [ instr_lower ] = instruction . parseString ( instr_...
def resolve ( self , executor , targets , classpath_products , confs = None , extra_args = None , invalidate_dependents = False ) : """Resolves external classpath products ( typically jars ) for the given targets . : API : public : param executor : A java executor to run ivy with . : type executor : : class :...
confs = confs or ( 'default' , ) targets_by_sets = JarDependencyManagement . global_instance ( ) . targets_by_artifact_set ( targets ) results = [ ] for artifact_set , target_subset in targets_by_sets . items ( ) : results . append ( self . _resolve_subset ( executor , target_subset , classpath_products , confs = c...
def transition_matrix ( C , reversible = False , mu = None , method = 'auto' , ** kwargs ) : r"""Estimate the transition matrix from the given countmatrix . Parameters C : numpy ndarray or scipy . sparse matrix Count matrix reversible : bool ( optional ) If True restrict the ensemble of transition matrice...
if issparse ( C ) : sparse_input_type = True elif isdense ( C ) : sparse_input_type = False else : raise NotImplementedError ( 'C has an unknown type.' ) if method == 'dense' : sparse_computation = False elif method == 'sparse' : sparse_computation = True elif method == 'auto' : # heuristically dete...
def build_arch ( self , arch ) : '''Run any build tasks for the Recipe . By default , this checks if any build _ archname methods exist for the archname of the current architecture , and runs them if so .'''
build = "build_{}" . format ( arch . arch ) if hasattr ( self , build ) : getattr ( self , build ) ( )
def l2_log_loss ( event_times , predicted_event_times , event_observed = None ) : r"""Calculates the l2 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 ) ) * * 2 Parameters event _ times : a ( n ...
if event_observed is None : event_observed = np . ones_like ( event_times ) ix = event_observed . astype ( bool ) return np . power ( np . log ( event_times [ ix ] ) - np . log ( predicted_event_times [ ix ] ) , 2 ) . mean ( )
def setVisible ( self , value ) : """Override Qt method to stops timers if widget is not visible ."""
if self . timer is not None : if value : self . timer . start ( self . _interval ) else : self . timer . stop ( ) super ( BaseTimerStatus , self ) . setVisible ( value )
def GetPathFromLink ( resource_link , resource_type = '' ) : """Gets path from resource link with optional resource type : param str resource _ link : : param str resource _ type : : return : Path from resource link with resource type appended ( if provided ) . : rtype : str"""
resource_link = TrimBeginningAndEndingSlashes ( resource_link ) if IsNameBased ( resource_link ) : # Replace special characters in string using the % xx escape . For example , space ( ' ' ) would be replaced by % 20 # This function is intended for quoting the path section of the URL and excludes ' / ' to be quoted as t...
def concat_ast ( asts : Sequence [ DocumentNode ] ) -> DocumentNode : """Concat ASTs . Provided a collection of ASTs , presumably each from different files , concatenate the ASTs together into batched AST , useful for validating many GraphQL source files which together represent one conceptual application .""...
return DocumentNode ( definitions = list ( chain . from_iterable ( document . definitions for document in asts ) ) )
def instagram_user_recent_media ( parser , token ) : """Tag for getting data about recent media of an user . : param parser : : param token : : return :"""
try : tagname , username = token . split_contents ( ) return InstagramUserRecentMediaNode ( username ) except ValueError : raise template . TemplateSyntaxError ( "%r tag requires a single argument" % token . contents . split ( ) [ 0 ] )
def create_ipython_exports ( self ) : """. . warning : : this feature is experimental and is currently not enabled by default ! Use with caution ! Creates attributes for all classes , methods and fields on the Analysis object itself . This makes it easier to work with Analysis module in an iPython shell . Cla...
# TODO : it would be fun to have the classes organized like the packages . I . e . you could do dx . CLASS _ xx . yyy . zzz for cls in self . get_classes ( ) : name = "CLASS_" + bytecode . FormatClassToPython ( cls . name ) if hasattr ( self , name ) : log . warning ( "Already existing class {}!" . form...
def on_release ( self , event ) : 'on release we reset the press data'
if self . press is None : return # print ( self . press ) x0 , y0 , btn = self . press if btn == 1 : color = 'r' elif btn == 2 : color = 'b' # noqa # plt . axes ( self . ax ) # plt . plot ( x0 , y0) # button Mapping btn = self . button_map [ btn ] self . set_seeds ( y0 , x0 , self . actual_slice , btn ) # s...
def get_least_common_subsumer ( self , from_tid , to_tid ) : """Returns the deepest common subsumer among two terms @ type from _ tid : string @ param from _ tid : one term id @ type to _ tid : string @ param to _ tid : another term id @ rtype : string @ return : the term identifier of the common subsum...
termid_from = self . terminal_for_term . get ( from_tid ) termid_to = self . terminal_for_term . get ( to_tid ) path_from = self . paths_for_terminal [ termid_from ] [ 0 ] path_to = self . paths_for_terminal [ termid_to ] [ 0 ] common_nodes = set ( path_from ) & set ( path_to ) if len ( common_nodes ) == 0 : return...
def evaluations ( ty , pv , useScipy = True ) : """evaluations ( ty , pv , useScipy ) - > ( ACC , MSE , SCC ) ty , pv : list , tuple or ndarray useScipy : convert ty , pv to ndarray , and use scipy functions for the evaluation Calculate accuracy , mean squared error and squared correlation coefficient using...
if scipy != None and useScipy : return evaluations_scipy ( scipy . asarray ( ty ) , scipy . asarray ( pv ) ) if len ( ty ) != len ( pv ) : raise ValueError ( "len(ty) must be equal to len(pv)" ) total_correct = total_error = 0 sumv = sumy = sumvv = sumyy = sumvy = 0 for v , y in zip ( pv , ty ) : if y == v ...
def merge ( self , grid = None , merge_points = True , inplace = False , main_has_priority = True ) : """Join one or many other grids to this grid . Grid is updated in - place by default . Can be used to merge points of adjcent cells when no grids are input . Parameters grid : vtk . UnstructuredGrid or li...
append_filter = vtk . vtkAppendFilter ( ) append_filter . SetMergePoints ( merge_points ) if not main_has_priority : append_filter . AddInputData ( self ) if isinstance ( grid , vtki . UnstructuredGrid ) : append_filter . AddInputData ( grid ) elif isinstance ( grid , list ) : grids = grid for grid in g...
def serialize ( self , data , investigation_time ) : """Serialize a collection of stochastic event sets to XML . : param data : A dictionary src _ group _ id - > list of : class : ` openquake . commonlib . calc . Rupture ` objects . Each Rupture should have the following attributes : * ` rupid ` * ` eve...
with open ( self . dest , 'wb' ) as fh : root = et . Element ( 'nrml' ) ses_container = et . SubElement ( root , 'ruptureCollection' ) ses_container . set ( 'investigationTime' , str ( investigation_time ) ) for grp_id in sorted ( data ) : attrs = dict ( id = grp_id , tectonicRegion = data [ grp...
def _to_inline_css ( self , style ) : """Return inline CSS from CSS key / values"""
return "; " . join ( [ '{}: {}' . format ( convert_style_key ( k ) , v ) for k , v in style . items ( ) ] )
def bodvcd ( bodyid , item , maxn ) : """Fetch from the kernel pool the double precision values of an item associated with a body , where the body is specified by an integer ID code . http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / bodvcd _ c . html : param bodyid : Body ID c...
bodyid = ctypes . c_int ( bodyid ) item = stypes . stringToCharP ( item ) dim = ctypes . c_int ( ) values = stypes . emptyDoubleVector ( maxn ) maxn = ctypes . c_int ( maxn ) libspice . bodvcd_c ( bodyid , item , maxn , ctypes . byref ( dim ) , values ) return dim . value , stypes . cVectorToPython ( values )
def coefficients ( self ) : """All of the coefficient arrays This property is the concatenation of the results from : func : ` terms . Term . get _ real _ coefficients ` and : func : ` terms . Term . get _ complex _ coefficients ` but it will always return a tuple of length 6 , even if ` ` alpha _ complex _...
vector = self . get_parameter_vector ( include_frozen = True ) pars = self . get_all_coefficients ( vector ) if len ( pars ) != 6 : raise ValueError ( "there must be 6 coefficient blocks" ) if any ( len ( p . shape ) != 1 for p in pars ) : raise ValueError ( "coefficient blocks must be 1D" ) if len ( pars [ 0 ]...
def _bindDomain ( self , domain_name , create = False , block = True ) : """Return the Boto Domain object representing the SDB domain of the given name . If the domain does not exist and ` create ` is True , it will be created . : param str domain _ name : the name of the domain to bind to : param bool create...
log . debug ( "Binding to job store domain '%s'." , domain_name ) retryargs = dict ( predicate = lambda e : no_such_sdb_domain ( e ) or sdb_unavailable ( e ) ) if not block : retryargs [ 'timeout' ] = 15 for attempt in retry_sdb ( ** retryargs ) : with attempt : try : return self . db . get_...
def insert ( self , ** kwargs ) : """Insert commands at the beginning of the sequence . This is provided because certain commands have to come first ( such as user creation ) , but may be need to beadded after other commands have already been specified . Later calls to insert put their commands before those...
for k , v in six . iteritems ( kwargs ) : self . commands . insert ( 0 , { k : v } ) return self
def parse_type ( parser ) : # type : ( Parser ) - > Union [ NamedType , NonNullType , ListType ] """Handles the ' Type ' : TypeName , ListType , and NonNullType parsing rules ."""
start = parser . token . start if skip ( parser , TokenKind . BRACKET_L ) : ast_type = parse_type ( parser ) expect ( parser , TokenKind . BRACKET_R ) ast_type = ast . ListType ( type = ast_type , loc = loc ( parser , start ) ) # type : ignore else : ast_type = parse_named_type ( parser ) if skip ( pars...
def parse_findPeaks ( self , f ) : """Parse HOMER findPeaks file headers ."""
parsed_data = dict ( ) s_name = f [ 's_name' ] for l in f [ 'f' ] : # Start of data if l . strip ( ) and not l . strip ( ) . startswith ( '#' ) : break # Automatically parse header lines by = symbol s = l [ 2 : ] . split ( '=' ) if len ( s ) > 1 : k = s [ 0 ] . strip ( ) . replace ( ' ' ...
def cwise ( tf_fn , xs , output_dtype = None , grad_function = None , name = None ) : """Component - wise operation with no broadcasting . Args : tf _ fn : a component - wise function taking n tf . Tensor inputs and producing a tf . Tensor output xs : n Tensors output _ dtype : an optional dtype grad _ ...
return slicewise ( tf_fn , xs , output_dtype = output_dtype , splittable_dims = xs [ 0 ] . shape . dims , grad_function = grad_function , name = name or "cwise" )
def get_limits ( self ) : """Return all known limits for this service , as a dict of their names to : py : class : ` ~ . AwsLimit ` objects . : returns : dict of limit names to : py : class : ` ~ . AwsLimit ` objects : rtype : dict"""
logger . debug ( "Gathering %s's limits from AWS" , self . service_name ) if self . limits : return self . limits limits = { } limits [ 'Trails Per Region' ] = AwsLimit ( 'Trails Per Region' , self , 5 , self . warning_threshold , self . critical_threshold , limit_type = self . aws_type ) limits [ 'Event Selectors ...
def get_bank_hierarchy_design_session ( self , proxy ) : """Gets the session designing bank hierarchies . arg : proxy ( osid . proxy . Proxy ) : a proxy return : ( osid . assessment . BankHierarchyDesignSession ) - a ` ` BankHierarchySession ` ` raise : NullArgument - ` ` proxy ` ` is ` ` null ` ` raise :...
if not self . supports_bank_hierarchy_design ( ) : raise errors . Unimplemented ( ) # pylint : disable = no - member return sessions . BankHierarchyDesignSession ( proxy = proxy , runtime = self . _runtime )
def save_hdf ( self , filename , path = '' , overwrite = False , append = False ) : """Writes all info necessary to recreate object to HDF file Saves table of photometry in DataFrame Saves model specification , spectroscopy , parallax to attrs"""
if os . path . exists ( filename ) : store = pd . HDFStore ( filename ) if path in store : store . close ( ) if overwrite : os . remove ( filename ) elif not append : raise IOError ( '{} in {} exists. Set either overwrite or append option.' . format ( path , file...
def fancy_handler ( signum , frame , spinner ) : """Signal handler , used to gracefully shut down the ` ` spinner ` ` instance when specified signal is received by the process running the ` ` spinner ` ` . ` ` signum ` ` and ` ` frame ` ` are mandatory arguments . Check ` ` signal . signal ` ` function for mo...
spinner . red . fail ( "✘" ) spinner . stop ( ) sys . exit ( 0 )