signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_fields ( self ) : """Get the required fields for serializing the result ."""
fields = self . Meta . fields exclude = self . Meta . exclude ignore_fields = self . Meta . ignore_fields indices = self . Meta . index_classes declared_fields = copy . deepcopy ( self . _declared_fields ) prefix_field_names = len ( indices ) > 1 field_mapping = OrderedDict ( ) # overlapping fields on multiple indices ...
def filter_data ( data , filter_dict ) : """filter a data dictionary for values only matching the filter"""
for key , match_string in filter_dict . items ( ) : if key not in data : logger . warning ( "{0} doesn't match a top level key" . format ( key ) ) continue values = data [ key ] matcher = re . compile ( match_string ) if isinstance ( values , list ) : values = [ v for v in values...
def create_notification_channel ( self , callback_url , calendar_ids = ( ) ) : """Create a new channel for receiving push notifications . : param string callback _ url : The url that will receive push notifications . Must not be longer than 128 characters and should be HTTPS . : param tuple calendar _ ids : L...
data = { 'callback_url' : callback_url } if calendar_ids : data [ 'filters' ] = { 'calendar_ids' : calendar_ids } return self . request_handler . post ( 'channels' , data = data ) . json ( ) [ 'channel' ]
def graphics ( self ) -> typing . List [ Graphic ] : """Return the graphics attached to this data item . . . versionadded : : 1.0 Scriptable : Yes"""
return [ Graphic ( graphic ) for graphic in self . __display_item . graphics ]
def generate_synthetic_observation_trajectory ( self , length , initial_Pi = None ) : """Generate a synthetic realization of observables . Parameters length : int Length of synthetic state trajectory to be generated . initial _ Pi : np . array of shape ( nstates , ) , optional , default = None The initial...
# First , generate synthetic state trajetory . s_t = self . generate_synthetic_state_trajectory ( length , initial_Pi = initial_Pi ) # Next , generate observations from these states . o_t = self . output_model . generate_observation_trajectory ( s_t ) return [ o_t , s_t ]
def get_app_model_classes ( self ) : """Helper method that returns a list of model classes for the current app ."""
models = [ ] for m in self . models : mod , cls = m . rsplit ( '.' , 1 ) mod = import_module ( mod ) models . append ( getattr ( mod , cls ) ) return models
def get_link ( href , value = None , ** kwargs ) : """Returns a well - formed link . If href is None / empty , returns an empty string : param href : value to be set for attribute href : param value : the text to be displayed . If None , the href itself is used : param kwargs : additional attributes and value...
if not href : return "" anchor_value = value and value or href attr = render_html_attributes ( ** kwargs ) return '<a href="{}" {}>{}</a>' . format ( href , attr , anchor_value )
def get_assets_by_record_type ( self , asset_record_type = None ) : """Gets an ` ` AssetList ` ` containing the given asset record ` ` Type ` ` . In plenary mode , the returned list contains all known assets or an error results . Otherwise , the returned list may contain only those assets that are accessible ...
return AssetList ( self . _provider_session . get_assets_by_record_type ( asset_record_type ) , self . _config_map )
def _convert_service_properties_to_xml ( logging , hour_metrics , minute_metrics , cors , target_version = None , delete_retention_policy = None , static_website = None ) : '''< ? xml version = " 1.0 " encoding = " utf - 8 " ? > < StorageServiceProperties > < Logging > < Version > version - number < / Version...
service_properties_element = ETree . Element ( 'StorageServiceProperties' ) # Logging if logging : logging_element = ETree . SubElement ( service_properties_element , 'Logging' ) ETree . SubElement ( logging_element , 'Version' ) . text = logging . version ETree . SubElement ( logging_element , 'Delete' ) ....
def init_git_pillar ( opts ) : '''Clear out the ext pillar caches , used when the master starts'''
ret = [ ] for opts_dict in [ x for x in opts . get ( 'ext_pillar' , [ ] ) ] : if 'git' in opts_dict : try : pillar = salt . utils . gitfs . GitPillar ( opts , opts_dict [ 'git' ] , per_remote_overrides = git_pillar . PER_REMOTE_OVERRIDES , per_remote_only = git_pillar . PER_REMOTE_ONLY , global_...
def login ( ) : '''Log in as administrator You can use wither basic auth or form based login ( via POST ) . : param username : The administrator ' s username : type username : string : param password : The administrator ' s password : type password : string'''
username = None password = None next = flask . request . args . get ( 'next' ) auth = flask . request . authorization if flask . request . method == 'POST' : username = flask . request . form [ 'username' ] password = flask . request . form [ 'password' ] if auth and auth . type == 'basic' : username = auth...
def trim_occluded_throats ( network , mask = 'all' ) : r"""Remove throats with zero area from the network and also remove pores that are isolated ( as a result or otherwise ) Parameters network : OpenPNM Network Object mask : string Applies routine only to pores and throats with this label"""
occluded_ts = network [ 'throat.area' ] == 0 if sp . sum ( occluded_ts ) > 0 : occluded_ts *= network [ "throat." + mask ] trim ( network = network , throats = occluded_ts )
def place_limit_order ( self , side : Side , amount : Number , price : Number ) -> Order : """Place a limit order ."""
return self . place_order ( side , OrderType . LIMIT , amount , price )
def get_value ( self , source ) : """Apply self . convert to the source . The parameter passed to convert depends on self . source _ name . If source _ name is given , self . convert ( getattr ( source , source _ name ) ) is called , otherwise self . convert ( source ) is called ."""
if self . source_name is None : present , value = True , self . convert ( source ) converted = True else : present , value = has_value ( source , self . source_name ) converted = False if not present or value is None : if self . is_required : raise ValueError ( "required value not present" )...
def add_pool_member ( hostname , username , password , name , member ) : '''A function to connect to a bigip device and add a new member to an existing pool . hostname The host / address of the bigip device username The iControl REST username password The iControl REST password name The name of the ...
# for states if isinstance ( member , dict ) : # check for state alternative name ' member _ state ' , replace with state if 'member_state' in member . keys ( ) : member [ 'state' ] = member . pop ( 'member_state' ) # replace underscore with dash for key in member : new_key = key . replace (...
def _save_file_and_pos ( self ) : """Save current position into file"""
if not self . _pos_changed : return with open ( self . pos_storage_filename , 'w+' ) as f : _pos = '%s:%s' % ( self . _log_file , self . _log_pos ) _logger . debug ( 'Saving position %s to file %s' % ( _pos , self . pos_storage_filename ) ) f . write ( _pos ) self . _pos_changed = False
async def getNodesBy ( self , full , valu = None , cmpr = '=' ) : '''The main function for retrieving nodes by prop . Args : full ( str ) : The property / tag name . valu ( obj ) : A lift compatible value for the type . cmpr ( str ) : An optional alternate comparator . Yields : ( synapse . lib . node . ...
if self . debug : await self . printf ( f'get nodes by: {full} {cmpr} {valu!r}' ) # special handling for by type ( * type = ) here . . . if cmpr == '*type=' : async for node in self . _getNodesByType ( full , valu = valu ) : yield node return if full . startswith ( '#' ) : async for node in self...
def get_route_edge_attributes ( G , route , attribute = None , minimize_key = 'length' , retrieve_default = None ) : """Get a list of attribute values for each edge in a path . Parameters G : networkx multidigraph route : list list of nodes in the path attribute : string the name of the attribute to get...
attribute_values = [ ] for u , v in zip ( route [ : - 1 ] , route [ 1 : ] ) : # if there are parallel edges between two nodes , select the one with the # lowest value of minimize _ key data = min ( G . get_edge_data ( u , v ) . values ( ) , key = lambda x : x [ minimize_key ] ) if attribute is None : at...
def has_target ( alias , target ) : '''Return true if the alias / target is set CLI Example : . . code - block : : bash salt ' * ' aliases . has _ target alias target'''
if target == '' : raise SaltInvocationError ( 'target can not be an empty string' ) aliases = list_aliases ( ) if alias not in aliases : return False if isinstance ( target , list ) : target = ', ' . join ( target ) return target == aliases [ alias ]
def multipart_encoder ( ** kwargs ) : """initialize MultipartEncoder with uploading fields ."""
def get_filetype ( file_path ) : file_type = filetype . guess ( file_path ) if file_type : return file_type . mime else : return "text/html" fields_dict = { } for key , value in kwargs . items ( ) : if os . path . isabs ( value ) : _file_path = value is_file = True el...
def get_mimetype ( path ) : """Guesses the mime type of a file . If mime type cannot be detected , plain text is assumed . : param path : path of the file : return : the corresponding mime type ."""
filename = os . path . split ( path ) [ 1 ] mimetype = mimetypes . guess_type ( filename ) [ 0 ] if mimetype is None : mimetype = 'text/x-plain' _logger ( ) . debug ( 'mimetype detected: %s' , mimetype ) return mimetype
def OnFind ( self , event ) : """Find functionality , called from toolbar , returns find position"""
# Search starts in next cell after the current one gridpos = list ( self . grid . actions . cursor ) text , flags = event . text , event . flags findpos = self . grid . actions . find ( gridpos , text , flags ) if findpos is None : # If nothing is found mention it in the statusbar and return statustext = _ ( "'{tex...
def simxPackFloats ( floatList ) : '''Please have a look at the function description / documentation in the V - REP user manual'''
if sys . version_info [ 0 ] == 3 : s = bytes ( ) for i in range ( len ( floatList ) ) : s = s + struct . pack ( '<f' , floatList [ i ] ) s = bytearray ( s ) else : s = '' for i in range ( len ( floatList ) ) : s += struct . pack ( '<f' , floatList [ i ] ) return s
def get_goea_nts_prt ( self , fldnames = None , ** usr_kws ) : """Return list of namedtuples removing fields which are redundant or verbose ."""
kws = usr_kws . copy ( ) if 'not_fldnames' not in kws : kws [ 'not_fldnames' ] = [ 'goterm' , 'parents' , 'children' , 'id' ] if 'rpt_fmt' not in kws : kws [ 'rpt_fmt' ] = True return self . get_goea_nts_all ( fldnames , ** kws )
def set_session ( self , headers = None ) : """Init session with default or custom headers Args : headers : A dict of headers ( default None , thus using the default header to init the session )"""
if headers is None : headers = { 'User-Agent' : ( 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3)' ' AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/48.0.2564.116 Safari/537.36' ) } elif not isinstance ( headers , dict ) : raise TypeError ( '"headers" must be a dict object' ) self . session = Session ( self ....
def _restore_auto_increment ( self , table ) : """restore the auto increment value for the table to what it was previously"""
query , seq_table , seq_column , seq_name = self . _get_auto_increment_info ( table ) if query : queries = [ query , "select nextval('{}')" . format ( seq_name ) ] return self . _run_queries ( queries )
def who_likes ( obj ) : """Usage : { % who _ likes obj as var % }"""
return Like . objects . filter ( receiver_content_type = ContentType . objects . get_for_model ( obj ) , receiver_object_id = obj . pk )
def parse_cropbox ( cropbox ) : """Returns x , y , x2 , y2 tuple for cropping ."""
if isinstance ( cropbox , six . text_type ) : return tuple ( [ int ( x . strip ( ) ) for x in cropbox . split ( ',' ) ] ) else : return tuple ( cropbox )
def __do_case_6_work ( d_w , d_u , case_1 , case_2 , case_3 , dfs_data ) : """Encapsulates the work that will be done for case 6 of _ _ embed _ frond , since it gets used in more than one place ."""
# - - We should only ever see u - cases 1 and 3 if case_2 : # - - We should never get here return False comp_d_w = abs ( d_w ) # - - Add the frond to the right side __insert_frond_RF ( d_w , d_u , dfs_data ) # - - Add uw to Rm m = dfs_data [ 'FG' ] [ 'm' ] Rm = R ( m , dfs_data ) if comp_d_w < Rm [ 'x' ] : Rm [...
def album_infos ( self , album_id ) : """: param album _ id : : return : { code : int , album : { album }"""
action = uri + '/album/' + str ( album_id ) data = self . request ( 'GET' , action ) if data [ 'code' ] == 200 : return data [ 'album' ]
def cmd_devid ( args ) : '''show parameters'''
params = mestate . mlog . params k = sorted ( params . keys ( ) ) for p in k : if p . startswith ( 'COMPASS_DEV_ID' ) : mp_util . decode_devid ( params [ p ] , p ) if p . startswith ( 'INS_' ) and p . endswith ( '_ID' ) : mp_util . decode_devid ( params [ p ] , p )
def pattern ( name , pattern ) : """Function to put a name on a pyparsing pattern . Just for ease of debugging / tracing parse errors ."""
pattern . setName ( name ) astracing . maybe_trace ( pattern ) return pattern
def sky2pix ( self , pos ) : """Convert sky coordinates into pixel coordinates . Parameters pos : ( float , float ) The ( ra , dec ) sky coordinates ( degrees ) Returns pixel : ( float , float ) The ( x , y ) pixel coordinates"""
pixel = self . wcs . wcs_world2pix ( [ pos ] , 1 ) # wcs and pyfits have oposite ideas of x / y return [ pixel [ 0 ] [ 1 ] , pixel [ 0 ] [ 0 ] ]
def _handle_sigint ( self , signum : int , frame : Any ) -> None : """Shutdown after processing current task ."""
logger . warning ( "Catched SIGINT" ) self . shutdown ( )
def _validate_annotation ( self , annotation ) : '''Ensures that the annotation has the right fields .'''
required_keys = set ( self . _required_keys ) keys = set ( key for key , val in annotation . items ( ) if val ) missing_keys = required_keys . difference ( keys ) if missing_keys : error = 'Annotation missing required fields: {0}' . format ( missing_keys ) raise AnnotationError ( error )
def appendAssayToStudy ( assay , studyNum , pathToISATABFile ) : """This function appends an Assay object to a study in an ISA file Typically , you should use the exploreISA function to check the contents of the ISA file and retrieve the assay and study number you are interested in ! : param assay : The Assay...
from isatools import isatab try : isa = isatab . load ( pathToISATABFile , skip_load_tables = True ) std = isa . studies [ studyNum - 1 ] lngth = len ( std . assays ) base = os . path . basename ( assay . filename ) fname = os . path . splitext ( base ) [ 0 ] fname = fname + str ( lngth ) ex...
def process_ekb_file ( fname ) : """Processes an EKB file produced by CWMS . Parameters fname : str Path to the EKB file to process . Returns cp : indra . sources . cwms . CWMSProcessor A CWMSProcessor , which contains a list of INDRA statements in its statements attribute ."""
# Process EKB XML file into statements with open ( fname , 'rb' ) as fh : ekb_str = fh . read ( ) . decode ( 'utf-8' ) return process_ekb ( ekb_str )
def _AddOption ( self , name ) : """Add an option to this Value . Args : name : ( str ) , the name of the Option to add . Raises : TextFSMTemplateError : If option is already present or the option does not exist ."""
# Check for duplicate option declaration if name in [ option . name for option in self . options ] : raise TextFSMTemplateError ( 'Duplicate option "%s"' % name ) # Create the option object try : option = self . _options_cls . GetOption ( name ) ( self ) except AttributeError : raise TextFSMTemplateError ( ...
def _partial_extraction_fixed ( self , idx , extra_idx = 0 ) : """Private method for a single extraction on a fixed - type tab file"""
myarray = np . array ( [ ] ) with open ( self . abspath ) as fobj : contents = fobj . readlines ( ) [ idx + extra_idx : ] for line in contents : try : vals = re . findall ( r' *[\w\-\+\.]*' , line ) temp = np . array ( [ float ( val ) for val in vals if val not in ( '' , ' ' ...
def run ( items , background = None ) : """Detect copy number variations from tumor / normal samples using Battenberg ."""
paired = vcfutils . get_paired_bams ( [ x [ "align_bam" ] for x in items ] , items ) if not paired or not paired . normal_bam : logger . warn ( "Battenberg only works on paired tumor/normal inputs, skipping %s" % dd . get_sample_name ( items [ 0 ] ) ) batout = None elif not tz . get_in ( [ "genome_resources" , ...
def netconf_config_change_changed_by_server_or_user_by_user_session_id ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) netconf_config_change = ET . SubElement ( config , "netconf-config-change" , xmlns = "urn:ietf:params:xml:ns:yang:ietf-netconf-notifications" ) changed_by = ET . SubElement ( netconf_config_change , "changed-by" ) server_or_user = ET . SubElement ( changed_by , "server-or-user" ) by_u...
def get_object ( connection , object_meta_data : dict , dirname : str ) : """Download object from objectstore . object _ meta _ data is an object retured when using ' get _ full _ container _ list '"""
return connection . get_object ( dirname , object_meta_data [ 'name' ] ) [ 1 ]
def initialize_plot ( self , ranges = None ) : """Initializes a new plot object with the last available frame ."""
# Get element key and ranges for frame fig = self . generate_plot ( self . keys [ - 1 ] , ranges ) self . drawn = True return fig
def set ( self , name : str , value : str ) -> None : """重写请求中的 header , 不推荐使用"""
name = name . casefold ( ) self . _headers [ name ] = value
def _get_upstream ( self ) : """Return the remote and remote merge branch for the current branch"""
if not self . _remote or not self . _branch : branch = self . branch_name if not branch : raise Scm . LocalException ( 'Failed to determine local branch' ) def get_local_config ( key ) : value = self . _check_output ( [ 'config' , '--local' , '--get' , key ] , raise_type = Scm . LocalExcepti...
def get_field_class ( qs , field_name ) : """Given a queryset and a field name , it will return the field ' s class"""
try : return qs . model . _meta . get_field ( field_name ) . __class__ . __name__ # while annotating , it ' s possible that field does not exists . except FieldDoesNotExist : return None
def gethost ( self , ip_addr ) : """Do reverse lookup on an ip address"""
# Handle silly fake ipv6 addresses try : if ip_addr [ : 7 ] == '::ffff:' : ip_addr = ip_addr [ 7 : ] except TypeError : pass if ip_addr [ 0 ] in string . letters : return ip_addr try : return self . hostsmap [ ip_addr ] except KeyError : pass try : name = socket . gethostbyaddr ( ip_addr...
def update ( self , callback_method = values . unset , callback_url = values . unset , friendly_name = values . unset ) : """Update the TriggerInstance : param unicode callback _ method : The HTTP method to use to call callback _ url : param unicode callback _ url : The URL we call when the trigger fires : pa...
data = values . of ( { 'CallbackMethod' : callback_method , 'CallbackUrl' : callback_url , 'FriendlyName' : friendly_name , } ) payload = self . _version . update ( 'POST' , self . _uri , data = data , ) return TriggerInstance ( self . _version , payload , account_sid = self . _solution [ 'account_sid' ] , sid = self ....
def window ( self , windowDuration , slideDuration = None ) : """Return a new DStream in which each RDD contains all the elements in seen in a sliding window of time over this DStream . @ param windowDuration : width of the window ; must be a multiple of this DStream ' s batching interval @ param slideDurat...
self . _validate_window_param ( windowDuration , slideDuration ) d = self . _ssc . _jduration ( windowDuration ) if slideDuration is None : return DStream ( self . _jdstream . window ( d ) , self . _ssc , self . _jrdd_deserializer ) s = self . _ssc . _jduration ( slideDuration ) return DStream ( self . _jdstream . ...
def _symm_current ( C ) : """To get rid of NaNs produced by _ scalar2array , symmetrize operators where C _ ijkl = C _ klij"""
nans = np . isnan ( C ) C [ nans ] = np . einsum ( 'klij' , C ) [ nans ] return C
def get_user_push_restrictions ( self ) : """: calls : ` GET / repos / : owner / : repo / branches / : branch / protection / restrictions / users < https : / / developer . github . com / v3 / repos / branches > ` _ : rtype : : class : ` github . PaginatedList . PaginatedList ` of : class : ` github . NamedUser . ...
return github . PaginatedList . PaginatedList ( github . NamedUser . NamedUser , self . _requester , self . protection_url + "/restrictions/users" , None )
def _set_preferred_infinite ( self , v , load = False ) : """Setter method for preferred _ infinite , mapped from YANG variable / interface / fortygigabitethernet / ipv6 / ipv6 _ nd _ ra / ipv6 _ intf _ cmds / nd / prefix / lifetime / preferred / preferred _ infinite ( empty ) If this variable is read - only ( co...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = YANGBool , is_leaf = True , yang_name = "preferred-infinite" , rest_name = "infinite" , parent = self , choice = ( u'ch-preferred-type' , u'ca-preferred-infinite' ) , path_helper = self . _path_helper , extmethods = self . _e...
def visit_emptynode ( self , node , parent ) : """visit an EmptyNode node by returning a fresh instance of it"""
return nodes . EmptyNode ( getattr ( node , "lineno" , None ) , getattr ( node , "col_offset" , None ) , parent )
def download ( url , file_handle , chunk_size = 1024 ) : """Downloads a given URL to a specific file . Parameters url : str URL to download . file _ handle : file Where to save the downloaded URL ."""
r = requests . get ( url , stream = True ) total_length = r . headers . get ( 'content-length' ) if total_length is None : maxval = UnknownLength else : maxval = int ( total_length ) name = file_handle . name with progress_bar ( name = name , maxval = maxval ) as bar : for i , chunk in enumerate ( r . iter_...
def _calcOnAxisFactor ( self , aLocation , deltaAxis , deltasOnSameAxis , deltaLocation ) : """Calculate the on - axis factors ."""
if deltaAxis == "origin" : f = 0 v = 0 else : f = aLocation [ deltaAxis ] v = deltaLocation [ deltaAxis ] i = [ ] iv = { } for value in deltasOnSameAxis : iv [ Location ( value ) [ deltaAxis ] ] = 1 i = sorted ( iv . keys ( ) ) r = 0 B , M , A = [ ] , [ ] , [ ] mA , mB , mM = None , None , None for ...
def to_dict ( self ) : """Return the information from the pedigree file as a dictionary . family id is key and a list with dictionarys for each individual as value . Returns : families ( dict ) : A dictionary with the families"""
self . logger . debug ( "Return the information as a dictionary" ) families = { } for family_id in self . families : family = [ ] for individual_id in self . families [ family_id ] . individuals : individual = self . families [ family_id ] . individuals [ individual_id ] family . append ( indivi...
def get_shop ( self , shop_id = 0 ) : """查询门店的WiFi信息 http : / / mp . weixin . qq . com / wiki / 15 / bcfb5d4578ea818b89913472cf2bbf8f . html : param shop _ id : 门店 ID : return : 返回的 JSON 数据包"""
res = self . _post ( 'shop/get' , data = { 'shop_id' : shop_id , } , result_processor = lambda x : x [ 'data' ] ) return res
def AddToFileNameTable ( self , fileName , showID ) : """Add entry to FileName table . If the file name and show id combination already exists in the table a fatal error is raised . Parameters fileName : string File name . showID : int Show id ."""
goodlogging . Log . Info ( "DB" , "Adding filename string match '{0}'={1} to database" . format ( fileName , showID ) , verbosity = self . logVerbosity ) currentValues = self . SearchFileNameTable ( fileName ) if currentValues is None : self . _ActionDatabase ( "INSERT INTO FileName (FileName, ShowID) VALUES (?,?)"...
def app_cache_restorer ( ) : """A context manager that restore model cache state as it was before entering context ."""
state = _app_cache_deepcopy ( apps . __dict__ ) try : yield state finally : with apps_lock ( ) : apps . __dict__ = state # Rebind the app registry models cache to # individual app config ones . for app_conf in apps . get_app_configs ( ) : app_conf . models = apps . al...
def profile_cancel ( self , query_id , timeout = 10 ) : """Cancel the query that has the given queryid . : param query _ id : The UUID of the query in standard UUID format that Drill assigns to each query . : param timeout : int : return : pydrill . client . Result"""
result = Result ( * self . perform_request ( ** { 'method' : 'GET' , 'url' : '/profiles/cancel/{0}' . format ( query_id ) , 'params' : { 'request_timeout' : timeout } } ) ) return result
def insert_instance ( instance , table , ** kwargs ) : """Inserts an object ' s values into a given table , will not populate Nonetype values @ param instance : Instance of an object to insert @ param table : Table in which to insert instance values @ return : ID of the last inserted row"""
instancedict = instance . __dict__ . copy ( ) instancedictclone = instancedict . copy ( ) # Remove all Nonetype values for k , v in instancedictclone . iteritems ( ) : if v is None : instancedict . pop ( k ) keys , values = CoyoteDb . get_insert_fields_and_values_from_dict ( instancedict ) sql = """INSERT I...
def simxReadStringStream ( clientID , signalName , operationMode ) : '''Please have a look at the function description / documentation in the V - REP user manual'''
signalLength = ct . c_int ( ) ; signalValue = ct . POINTER ( ct . c_ubyte ) ( ) if ( sys . version_info [ 0 ] == 3 ) and ( type ( signalName ) is str ) : signalName = signalName . encode ( 'utf-8' ) ret = c_ReadStringStream ( clientID , signalName , ct . byref ( signalValue ) , ct . byref ( signalLength ) , operati...
def kwargs ( self ) : """combine GET and POST params to be passed to the controller"""
kwargs = dict ( self . query_kwargs ) kwargs . update ( self . body_kwargs ) return kwargs
def vcenter_discovery_ignore_delete_all_response_always ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) vcenter = ET . SubElement ( config , "vcenter" , xmlns = "urn:brocade.com:mgmt:brocade-vswitch" ) id_key = ET . SubElement ( vcenter , "id" ) id_key . text = kwargs . pop ( 'id' ) discovery = ET . SubElement ( vcenter , "discovery" ) ignore_delete_all_response = ET . SubElement ( disc...
def get_job_definition ( self , identifier ) : """Get job defintiion by name or ARN : param identifier : Name or ARN : type identifier : str : return : Job definition or None : rtype : JobDefinition or None"""
env = self . get_job_definition_by_arn ( identifier ) if env is None : env = self . get_job_definition_by_name ( identifier ) return env
def _loadSources ( self ) : """creates a trigdict and populates it with data from self . autorityFiles"""
self . confstems = { } self . sourceDict = newtrigdict . Trigdict ( ) for fName in self . authorityFiles : self . _loadOneSource ( fName ) # We want to allow naked bibstems in references , too for stem in self . sourceDict . values ( ) : cleanStem = stem . replace ( "." , "" ) . upper ( ) self . _addPub ( s...
def write ( self , data ) : """Write data to the stream : data : the data to write to the stream : returns : None"""
if self . padded : # flush out any remaining bits first if len ( self . _bits ) > 0 : self . _flush_bits_to_stream ( ) self . _stream . write ( data ) else : # nothing to do here if len ( data ) == 0 : return bits = bytes_to_bits ( data ) self . write_bits ( bits )
def is_noise ( self ) : """Is this module just noise ? ( too common either at top or bottom of the graph ) ."""
noise = self . args [ 'noise_level' ] if not ( self . in_degree and self . out_degree ) : return self . degree > noise return False
def count_substring_occurrences ( text : str , subtext : str ) -> int : """Determine the number of occurrences of a specific substring within a given string . Overlapping instances are included . Examples : > > > count _ substring _ occurrences ( ' ' , ' a ' ) > > > count _ substring _ occurrences ( ' aaa ' ,...
return sum ( 1 for i in range ( len ( text ) - len ( subtext ) + 1 ) if text [ i : i + len ( subtext ) ] == subtext )
def permission_request_approve_link ( context , perm ) : """Renders a html link to the approve view of the given permission request . Returns no content if the request - user has no permission to delete foreign permissions ."""
user = context [ 'request' ] . user if user . is_authenticated ( ) : if user . has_perm ( 'authority.approve_permission_requests' ) : return base_link ( context , perm , 'authority-approve-permission-request' ) return { 'url' : None }
def parse_devicelist ( data_str ) : """Parse the BT Home Hub 5 data format ."""
p = HTMLTableParser ( ) p . feed ( data_str ) known_devices = p . tables [ 9 ] devices = { } for device in known_devices : if len ( device ) == 5 and device [ 2 ] != '' : devices [ device [ 2 ] ] = device [ 1 ] return devices
def synopsis ( case_id ) : """Update the case synopsis ."""
text = request . form [ 'text' ] case_obj = app . db . case ( case_id ) app . db . update_synopsis ( case_obj , text ) return redirect ( request . referrer )
def optimize_orientations ( fwtour , clm , phase , cpus ) : """Optimize the orientations of contigs by using heuristic flipping ."""
# Prepare input files tour_contigs = clm . active_contigs tour = clm . tour oo = clm . oo print_tour ( fwtour , tour , "FLIPALL{}" . format ( phase ) , tour_contigs , oo , signs = clm . signs ) tag1 = clm . flip_whole ( tour ) print_tour ( fwtour , tour , "FLIPWHOLE{}" . format ( phase ) , tour_contigs , oo , signs = c...
def round ( value , decimal = None , digits = None , places = None ) : """: param value : THE VALUE TO ROUND : param decimal : NUMBER OF DECIMAL PLACES TO ROUND ( NEGATIVE IS LEFT - OF - DECIMAL ) : param digits : ROUND TO SIGNIFICANT NUMBER OF digits : param places : SAME AS digits : return :"""
value = float ( value ) if value == 0.0 : return "0" digits = coalesce ( digits , places ) if digits != None : left_of_decimal = int ( math . ceil ( math . log10 ( abs ( value ) ) ) ) decimal = digits - left_of_decimal right_of_decimal = max ( decimal , 0 ) format = "{:." + text_type ( right_of_decimal ) + ...
def raise_for_status ( self ) : '''Raise Postmark - specific HTTP errors . If there isn ' t one , the standard HTTP error is raised . HTTP 401 raises : class : ` UnauthorizedError ` HTTP 422 raises : class : ` UnprocessableEntityError ` HTTP 500 raises : class : ` InternalServerError `'''
if self . status_code == 401 : raise UnauthorizedError ( self . _requests_response ) elif self . status_code == 422 : raise UnprocessableEntityError ( self . _requests_response ) elif self . status_code == 500 : raise InternalServerError ( self . _requests_response ) return self . _requests_response . raise...
def parse_content_type ( header ) : """Parse the " Content - Type " header ."""
typ = subtyp = None ; options = { } typ , pos = expect_re ( re_token , header , 0 ) _ , pos = expect_lit ( '/' , header , pos ) subtyp , pos = expect_re ( re_token , header , pos ) ctype = header [ : pos ] if subtyp else '' while pos < len ( header ) : _ , pos = accept_ws ( header , pos ) _ , pos = expect_lit (...
def update_campaign_metadata_list ( self , campaign_id , ** kwargs ) : # noqa : E501 """List all campaign device metadata # noqa : E501 Get campaign device metadata . # noqa : E501 This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass asynchronous = True ...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'asynchronous' ) : return self . update_campaign_metadata_list_with_http_info ( campaign_id , ** kwargs ) # noqa : E501 else : ( data ) = self . update_campaign_metadata_list_with_http_info ( campaign_id , ** kwargs ) # noqa : E501 return ...
def weight_variable ( shape ) : """weight _ variable generates a weight variable of a given shape ."""
initial = tf . truncated_normal ( shape , stddev = 0.1 ) return tf . Variable ( initial )
def contribute_to_class ( self , cls , name ) : """Swap out any reference to ` ` KeywordsField ` ` with the ` ` KEYWORDS _ FIELD _ string ` ` field in ` ` search _ fields ` ` ."""
super ( KeywordsField , self ) . contribute_to_class ( cls , name ) string_field_name = list ( self . fields . keys ( ) ) [ 0 ] % self . related_field_name if hasattr ( cls , "search_fields" ) and name in cls . search_fields : try : weight = cls . search_fields [ name ] except TypeError : # search _ fie...
import math def calculate_geometric_series_sum ( first_term : int , series_len : int , ratio : int ) -> int : """Function to calculate the sum of a geometric progression series . Args : first _ term ( int ) : The first term in the geometric progression series . series _ len ( int ) : The number of terms in th...
sum_series = ( first_term * ( 1 - math . pow ( ratio , series_len ) ) ) / ( 1 - ratio ) return sum_series
def firsthash ( frame , removedupes = False ) : '''Hashes the first time step . Only will work as long as the hash can fit in a uint64. Parameters : frame : first frame . Keywords : removedups : specify duplicates for the given frame . Returns a dictionary of everything needed to generate hashes from ...
# hashes must have i8 available # overwise , we ' ll have overflow def avgdiff ( d ) : d = np . sort ( d ) ; d = d [ 1 : ] - d [ : - 1 ] ret = np . average ( d [ np . nonzero ( d ) ] ) ; if np . isnan ( ret ) : return 1.0 ; return ret ; def hasextent ( l , eps = 1e-10 ) : # will I one day ma...
def _get_validation_labels ( val_path ) : """Returns labels for validation . Args : val _ path : path to TAR file containing validation images . It is used to retrieve the name of pictures and associate them to labels . Returns : dict , mapping from image name ( str ) to label ( str ) ."""
labels_path = tfds . core . get_tfds_path ( _VALIDATION_LABELS_FNAME ) with tf . io . gfile . GFile ( labels_path ) as labels_f : labels = labels_f . read ( ) . strip ( ) . split ( '\n' ) with tf . io . gfile . GFile ( val_path , 'rb' ) as tar_f_obj : tar = tarfile . open ( mode = 'r:' , fileobj = tar_f_obj ) ...
def type_with_ranges ( self , tchain , p_elem , rangekw , gen_data ) : """Handle types with ' range ' or ' length ' restrictions . ` tchain ` is the chain of type definitions from which the ranges may need to be extracted . ` rangekw ` is the statement keyword determining the range type ( either ' range ' or ...
ranges = self . get_ranges ( tchain , rangekw ) if not ranges : return p_elem . subnode ( gen_data ( ) ) if len ( ranges ) > 1 : p_elem = SchemaNode . choice ( p_elem ) p_elem . occur = 2 for r in ranges : d_elem = gen_data ( ) for p in self . range_params ( r , rangekw ) : d_elem . subnode ...
def _on_stream_disconnect ( self , stream ) : """Respond to disconnection of a local stream by propagating DEL _ ROUTE for any contexts we know were attached to it ."""
# During a stream crash it is possible for disconnect signal to fire # twice , in which case ignore the second instance . routes = self . _routes_by_stream . pop ( stream , None ) if routes is None : return LOG . debug ( '%r: %r is gone; propagating DEL_ROUTE for %r' , self , stream , routes ) for target_id in rout...
def add_log_fields ( self , fields : Dict [ str , Any ] ) : """Add the provided log fields If a key is already present , then it is ignored . : param fields : the log fields to add"""
self . _log_fields . add_fields ( fields )
def execute ( self ) : """Main method to call to run the worker"""
self . prepare_models ( ) self . prepare_worker ( ) if self . options . print_options : self . print_options ( ) self . run ( )
def get_filename_from_url ( url ) : """Get a filename from a URL . > > > from planet . api import utils > > > urls = [ . . . ' https : / / planet . com / ' , . . . ' https : / / planet . com / path / to / ' , . . . ' https : / / planet . com / path / to / example . tif ' , . . . ' https : / / planet . c...
path = urlparse ( url ) . path name = path [ path . rfind ( '/' ) + 1 : ] return name or None
def maskname ( mask ) : """Returns the event name associated to mask . IN _ ISDIR is appended to the result when appropriate . Note : only one event is returned , because only one event can be raised at a given time . @ param mask : mask . @ type mask : int @ return : event name . @ rtype : str"""
ms = mask name = '%s' if mask & IN_ISDIR : ms = mask - IN_ISDIR name = '%s|IN_ISDIR' return name % EventsCodes . ALL_VALUES [ ms ]
def read2dict ( cls , filename , info ) : """Read the control parameters from the given path ( and its auxiliary paths , where appropriate ) and store them in the given | dict | object ` info ` . Note that the | dict | ` info ` can be used to feed information into the execution of control files . Use this m...
if not filename . endswith ( '.py' ) : filename += '.py' path = os . path . join ( cls . _workingpath , filename ) try : if path not in cls . _registry : with open ( path ) as file_ : cls . _registry [ path ] = file_ . read ( ) exec ( cls . _registry [ path ] , { } , info ) except BaseEx...
def resize_image_folder ( bucket , key_prefix , pil_size ) : """This function resizes all the images in a folder"""
con = boto . connect_s3 ( ) b = con . get_bucket ( bucket ) for key in b . list ( key_prefix ) : key = b . get_key ( key . name ) if 'image' not in key . content_type : continue size = key . get_metadata ( 'size' ) if size == str ( pil_size ) : continue with tempfile . TemporaryFile ...
def dist_docs ( ) : "create a documentation bundle"
dist_dir = path ( "dist" ) docs_package = path ( "%s/%s-%s-docs.zip" % ( dist_dir . abspath ( ) , options . setup . name , options . setup . version ) ) dist_dir . exists ( ) or dist_dir . makedirs ( ) docs_package . exists ( ) and docs_package . remove ( ) sh ( r'cd build/apidocs && zip -qr9 %s .' % ( docs_package , )...
def offset ( self , offset ) : """Apply an OFFSET to the query and return the newly resulting Query ."""
query = self . _copy ( ) query . _offset = offset return query
def read_namespaced_resource_quota_status ( self , name , namespace , ** kwargs ) : # noqa : E501 """read _ namespaced _ resource _ quota _ status # noqa : E501 read status of the specified ResourceQuota # noqa : E501 This method makes a synchronous HTTP request by default . To make an asynchronous HTTP reque...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . read_namespaced_resource_quota_status_with_http_info ( name , namespace , ** kwargs ) # noqa : E501 else : ( data ) = self . read_namespaced_resource_quota_status_with_http_info ( name , namespace , ** kwargs ) # ...
def getproxies_environment ( ) : """Return a dictionary of scheme - > proxy server URL mappings . Scan the environment for variables named < scheme > _ proxy ; this seems to be the standard convention . If you need a different way , you can pass a proxies dictionary to the [ Fancy ] URLopener constructor ."...
proxies = { } for name , value in os . environ . items ( ) : name = name . lower ( ) if value and name [ - 6 : ] == '_proxy' : proxies [ name [ : - 6 ] ] = value return proxies
def _node_add_with_peer_list ( self , child_self , child_other ) : '''_ node _ add _ with _ peer _ list Low - level api : Apply delta child _ other to child _ self when child _ self is the peer of child _ other . Element child _ self and child _ other are list nodes . Element child _ self will be modified dur...
parent_self = child_self . getparent ( ) s_node = self . device . get_schema_node ( child_self ) if child_other . get ( operation_tag ) != 'delete' and child_other . get ( operation_tag ) != 'remove' and s_node . get ( 'ordered-by' ) == 'user' and child_other . get ( insert_tag ) is not None : if child_other . get ...
def clear_cache ( self ) : """Clear all kinds of internal caches to release resources . Currently persistent commands will be interrupted . : return : self"""
for cmd in ( self . cat_file_all , self . cat_file_header ) : if cmd : cmd . __del__ ( ) self . cat_file_all = None self . cat_file_header = None return self
def set_render_manager ( self , agent : BaseAgent ) : """Sets the render manager for the agent . : param agent : An instance of an agent ."""
rendering_manager = self . game_interface . renderer . get_rendering_manager ( self . index , self . team ) agent . _set_renderer ( rendering_manager )
def lss ( inlist ) : """Squares each value in the passed list , adds up these squares and returns the result . Usage : lss ( inlist )"""
ss = 0 for item in inlist : ss = ss + item * item return ss
def flatten ( sequence , levels = 1 ) : """Example : > > > nested = [ [ 1,2 ] , [ [ 3 ] ] ] > > > list ( flatten ( nested ) ) [1 , 2 , [ 3 ] ]"""
if levels == 0 : for x in sequence : yield x else : for x in sequence : for y in flatten ( x , levels - 1 ) : yield y
def _piped_realign_gatk ( data , region , cl , out_base_file , tmp_dir , prep_params ) : """Perform realignment with GATK , using input commandline . GATK requires writing to disk and indexing before realignment ."""
broad_runner = broad . runner_from_config ( data [ "config" ] ) pa_bam = "%s-prealign%s" % os . path . splitext ( out_base_file ) if not utils . file_exists ( pa_bam ) : with file_transaction ( data , pa_bam ) as tx_out_file : cmd = "{cl} -o {tx_out_file}" . format ( ** locals ( ) ) do . run ( cmd ,...