signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def human ( ) : """Run a host which expects one player to connect remotely ."""
run_config = run_configs . get ( ) map_inst = maps . get ( FLAGS . map ) if not FLAGS . rgb_screen_size or not FLAGS . rgb_minimap_size : logging . info ( "Use --rgb_screen_size and --rgb_minimap_size if you want rgb " "observations." ) ports = [ FLAGS . config_port + p for p in range ( 5 ) ] # tcp + 2 * num _ play...
def flavor_access_list ( self , ** kwargs ) : '''Return a list of project IDs assigned to flavor ID'''
flavor_id = kwargs . get ( 'flavor_id' ) nt_ks = self . compute_conn ret = { flavor_id : [ ] } flavor_accesses = nt_ks . flavor_access . list ( flavor = flavor_id , ** kwargs ) for project in flavor_accesses : ret [ flavor_id ] . append ( project . tenant_id ) return ret
def walk ( fn , obj , * args , ** kwargs ) : """Recursively walk an object graph applying ` fn ` / ` args ` to objects ."""
if type ( obj ) in [ list , tuple ] : return list ( walk ( fn , o , * args ) for o in obj ) if type ( obj ) is dict : return dict ( ( walk ( fn , k , * args ) , walk ( fn , v , * args ) ) for k , v in obj . items ( ) ) return fn ( obj , * args , ** kwargs )
def _delete_record ( self , identifier = None , rtype = None , name = None , content = None ) : """Delete an existing record . If the record doesn ' t exist , does nothing ."""
if not identifier : records = self . _list_records ( rtype , name , content ) identifiers = [ record [ "id" ] for record in records ] else : identifiers = [ identifier ] LOGGER . debug ( "delete_records: %s" , identifiers ) for record_id in identifiers : self . _delete ( "/v1/domains/{0}/records/{1}" . ...
def _ruby_installed ( ret , ruby , user = None ) : '''Check to see if given ruby is installed .'''
default = __salt__ [ 'rbenv.default' ] ( runas = user ) for version in __salt__ [ 'rbenv.versions' ] ( user ) : if version == ruby : ret [ 'result' ] = True ret [ 'comment' ] = 'Requested ruby exists' ret [ 'default' ] = default == ruby break return ret
def get_interface_switchport_output_switchport_default_vlan ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) get_interface_switchport = ET . Element ( "get_interface_switchport" ) config = get_interface_switchport output = ET . SubElement ( get_interface_switchport , "output" ) switchport = ET . SubElement ( output , "switchport" ) interface_type_key = ET . SubElement ( switchport , "interfa...
def upload_progress ( request ) : """Used by Ajax calls Return the upload progress and total length values"""
if 'X-Progress-ID' in request . GET : progress_id = request . GET [ 'X-Progress-ID' ] elif 'X-Progress-ID' in request . META : progress_id = request . META [ 'X-Progress-ID' ] if progress_id : cache_key = "%s_%s" % ( request . META [ 'REMOTE_ADDR' ] , progress_id ) data = cache . get ( cache_key ) r...
def getSlicesForText ( self , retina_name , body , get_fingerprint = None , start_index = 0 , max_results = 10 ) : """Get a list of slices of the text Args : retina _ name , str : The retina name ( required ) body , str : The text to be evaluated ( required ) get _ fingerprint , bool : Configure if the fing...
resourcePath = '/text/slices' method = 'POST' queryParams = { } headerParams = { 'Accept' : 'Application/json' , 'Content-Type' : 'application/json' } postData = None queryParams [ 'retina_name' ] = retina_name queryParams [ 'start_index' ] = start_index queryParams [ 'max_results' ] = max_results queryParams [ 'get_fi...
def list_markets_by_currency ( self , currency ) : """Helper function to see which markets exist for a currency . Endpoint : / public / getmarkets Example : : > > > Bittrex ( None , None ) . list _ markets _ by _ currency ( ' LTC ' ) [ ' BTC - LTC ' , ' ETH - LTC ' , ' USDT - LTC ' ] : param currency : St...
return [ market [ 'MarketName' ] for market in self . get_markets ( ) [ 'result' ] if market [ 'MarketName' ] . lower ( ) . endswith ( currency . lower ( ) ) ]
def find ( names , dirs , file_ext ) : """Iterating a set of dirs under the static root , this method tries to find a file named like one of the names and file ext passed , and returns the storage path to the first file it encounters . Usage this method makes it possible to override static files ( such as i...
if not isinstance ( names , list ) or isinstance ( names , tuple ) : names = ( names , ) for dir_name in dirs : for name in names : path = os . path . join ( dir_name , name + file_ext ) if not path in EXISTING_PATHS : # check on file system , then cache EXISTING_PATHS [ path ] = STA...
def set_waveform_optional ( self , value , callb = None , rapid = False ) : """Convenience method to animate the light , a dictionary with the the following keys : transient , color , period , cycles , skew _ ratio , waveform , set _ hue , set _ saturation , set _ brightness , set _ kelvin This method will send...
if "color" in value and len ( value [ "color" ] ) == 4 : if rapid : self . fire_and_forget ( LightSetWaveformOptional , value , num_repeats = 1 ) else : self . req_with_ack ( LightSetWaveformOptional , value , callb = callb )
def evaluateplanarR2derivs ( Pot , R , phi = None , t = 0. ) : """NAME : evaluateplanarR2derivs PURPOSE : evaluate the second radial derivative of a ( list of ) planarPotential instance ( s ) INPUT : Pot - ( list of ) planarPotential instance ( s ) R - Cylindrical radius ( can be Quantity ) phi = azim...
from . Potential import _isNonAxi isList = isinstance ( Pot , list ) nonAxi = _isNonAxi ( Pot ) if nonAxi and phi is None : raise PotentialError ( "The (list of) planarPotential instances is non-axisymmetric, but you did not provide phi" ) if isinstance ( Pot , list ) and nu . all ( [ isinstance ( p , planarPotenti...
def get_singlerate ( self , base , code ) : """Get a single rate , used as fallback"""
try : url = self . onerate_url % ( base , code ) resp = get ( url ) resp . raise_for_status ( ) except exceptions . HTTPError as e : self . log ( logging . ERROR , "%s: problem with %s:\n%s" , self . name , url , e ) return None rate = resp . text . rstrip ( ) if rate == 'N/A' : raise RuntimeErr...
def on_security_data_node ( self , node ) : """process a securityData node - FIXME : currently not handling relateDate node"""
sid = XmlHelper . get_child_value ( node , 'security' ) farr = node . GetElement ( 'fieldData' ) dmap = defaultdict ( list ) for i in range ( farr . NumValues ) : pt = farr . GetValue ( i ) [ dmap [ f ] . append ( XmlHelper . get_child_value ( pt , f , allow_missing = 1 ) ) for f in [ 'date' ] + self . fields ]...
def per_chunk ( iterable , n = 1 , fillvalue = None ) : """From http : / / stackoverflow . com / a / 8991553/610569 > > > list ( per _ chunk ( ' abcdefghi ' , n = 2 ) ) [ ( ' a ' , ' b ' ) , ( ' c ' , ' d ' ) , ( ' e ' , ' f ' ) , ( ' g ' , ' h ' ) , ( ' i ' , None ) ] > > > list ( per _ chunk ( ' abcdefghi '...
args = [ iter ( iterable ) ] * n return zip_longest ( * args , fillvalue = fillvalue )
def symmetrize_compact_force_constants ( force_constants , primitive , level = 1 ) : """Symmetry force constants by translational and permutation symmetries Parameters force _ constants : ndarray Compact force constants . Symmetrized force constants are overwritten . dtype = double shape = ( n _ patom , n...
s2p_map = primitive . get_supercell_to_primitive_map ( ) p2s_map = primitive . get_primitive_to_supercell_map ( ) p2p_map = primitive . get_primitive_to_primitive_map ( ) permutations = primitive . get_atomic_permutations ( ) s2pp_map , nsym_list = get_nsym_list_and_s2pp ( s2p_map , p2p_map , permutations ) try : i...
def make_url ( self , method ) : """Generate a Telegram URL for this bot ."""
token = self . settings ( ) [ 'token' ] return TELEGRAM_URL . format ( token = quote ( token ) , method = quote ( method ) , )
def import_obj ( uri , mod_name = None , mod_attr_sep = '::' , attr_chain_sep = '.' , retn_mod = False , ) : """Load an object from a module . @ param uri : an uri specifying which object to load . An ` uri ` consists of two parts : module URI and attribute chain , e . g . ` a / b / c . py : : x . y . z ` or ...
if mod_attr_sep is None : mod_attr_sep = '::' uri_parts = split_uri ( uri = uri , mod_attr_sep = mod_attr_sep ) protocol , mod_uri , attr_chain = uri_parts if protocol == 'py' : mod_obj = import_name ( mod_uri ) else : if not mod_name : msg = ( 'Argument `mod_name` must be given when loading by file...
def Ttr ( x ) : """Equation for the triple point of ammonia - water mixture Parameters x : float Mole fraction of ammonia in mixture , [ mol / mol ] Returns Ttr : float Triple point temperature , [ K ] Notes Raise : class : ` NotImplementedError ` if input isn ' t in limit : * 0 ≤ x ≤ 1 Referenc...
if 0 <= x <= 0.33367 : Ttr = 273.16 * ( 1 - 0.3439823 * x - 1.3274271 * x ** 2 - 274.973 * x ** 3 ) elif 0.33367 < x <= 0.58396 : Ttr = 193.549 * ( 1 - 4.987368 * ( x - 0.5 ) ** 2 ) elif 0.58396 < x <= 0.81473 : Ttr = 194.38 * ( 1 - 4.886151 * ( x - 2 / 3 ) ** 2 + 10.37298 * ( x - 2 / 3 ) ** 3 ) elif 0.8147...
def search_payload ( self , fields = None , query = None ) : """Reset ` ` errata _ id ` ` from DB ID to ` ` errata _ id ` ` ."""
payload = super ( ContentViewFilterRule , self ) . search_payload ( fields , query ) if 'errata_id' in payload : if not hasattr ( self . errata , 'errata_id' ) : self . errata = self . errata . read ( ) payload [ 'errata_id' ] = self . errata . errata_id return payload
def get_bitmap ( self , time = None , size = 32 , store_path = None ) : """Get a bitmap of the object at a given instance of time . If time is ` None ` , ` then the bitmap is generated for the last point in time . Parameters time : int or None size : int Size in pixels . The resulting bitmap will be ( siz...
# bitmap _ width = int ( self . get _ width ( ) * size ) + 2 # bitmap _ height = int ( self . get _ height ( ) * size ) + 2 img = Image . new ( 'L' , ( size , size ) , 'black' ) draw = ImageDraw . Draw ( img , 'L' ) bb = self . get_bounding_box ( ) for stroke in self . get_sorted_pointlist ( ) : for p1 , p2 in zip ...
def logical_chassis_fwdl_status_output_cluster_fwdl_entries_fwdl_entries_blade_state ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) logical_chassis_fwdl_status = ET . Element ( "logical_chassis_fwdl_status" ) config = logical_chassis_fwdl_status output = ET . SubElement ( logical_chassis_fwdl_status , "output" ) cluster_fwdl_entries = ET . SubElement ( output , "cluster-fwdl-entries" ) fwdl_entries = ET . SubEleme...
def find_binary ( self , binary ) : """Scan and return the first path to a binary that we can find"""
if os . path . exists ( binary ) : return binary # Extract out the filename if we were given a full path binary_name = os . path . basename ( binary ) # Gather $ PATH search_paths = os . environ [ 'PATH' ] . split ( ':' ) # Extra paths to scan . . . default_paths = [ '/usr/bin' , '/bin' '/usr/local/bin' , '/usr/sbi...
def get_style_bits ( match = False , comment = False , selected = False , data = False , diff = False , user = 0 ) : """Return an int value that contains the specified style bits set . Available styles for each byte are : match : part of the currently matched search comment : user commented area selected : ...
style_bits = 0 if user : style_bits |= ( user & user_bit_mask ) if diff : style_bits |= diff_bit_mask if match : style_bits |= match_bit_mask if comment : style_bits |= comment_bit_mask if data : style_bits |= ( data_style & user_bit_mask ) if selected : style_bits |= selected_bit_mask return st...
def crop_resize_image ( image : np . ndarray , size ) -> np . ndarray : """Resize the input image . : param image : Original image which is a PIL object . : param size : Tuple of height and width to resize the image to . : return : Resized image which is a PIL object"""
width , height = image . size if width > height : left = ( width - height ) / 2 right = width - left top = 0 bottom = height else : top = ( height - width ) / 2 bottom = height - top left = 0 right = width image = image . crop ( ( left , top , right , bottom ) ) image = image . resize ( ...
def plot ( corners , f , n = 100 ) : """Plot function over a triangle ."""
import matplotlib . tri import matplotlib . pyplot as plt # discretization points def partition ( boxes , balls ) : # < https : / / stackoverflow . com / a / 36748940/353337 > def rec ( boxes , balls , parent = tuple ( ) ) : if boxes > 1 : for i in range ( balls + 1 ) : for x in ...
def run ( self ) : """Run the builder on changes"""
event_handler = Handler ( ) threads = [ ] paths = [ os . path . join ( cwd , "content" ) , os . path . join ( cwd , "templates" ) ] for i in paths : targetPath = str ( i ) self . observer . schedule ( event_handler , targetPath , recursive = True ) threads . append ( self . observer ) self . observer . star...
def get_compatible_canvas_layers ( self , category ) : """Collect layers from map canvas , compatible for the given category and selected impact function . . note : : Returns layers with keywords and layermode matching the category and compatible with the selected impact function . Also returns layers witho...
# Collect compatible layers layers = [ ] for layer in self . iface . mapCanvas ( ) . layers ( ) : try : keywords = self . keyword_io . read_keywords ( layer ) if 'layer_purpose' not in keywords : keywords = None except ( HashNotFoundError , OperationalError , NoKeywordsFoundError , K...
def private_key_type ( key_file ) : """Determines type of the private key : RSA , DSA , EC . : param key _ file : file path : type key _ file : str : return : one of " RSA " , " DSA " or " EC " : except CannotFindKeyTypeError"""
keytypes = ( ( "RSA" , RSA ) , ( "DSA" , DSA ) , ( "EC" , EC ) ) for key , ktype in keytypes : try : ktype . load_key ( key_file ) except ( RSA . RSAError , DSA . DSAError , ValueError ) : continue else : return key else : raise CannotFindKeyTypeError ( )
def getUsersWithinRole ( self , rolename , filter = None , maxCount = 20 ) : """You can use this operation to conveniently see all the user accounts to whom this role has been assigned . Inputs : rolename - name of the role filter - filter to be applied to the resultant user set maxCount - maximum number ...
uURL = self . _url + "/roles/getUsersWithinRole" params = { "f" : "json" , "rolename" : rolename , "maxCount" : maxCount } if filter is not None and isinstance ( filter , str ) : params [ 'filter' ] = filter return self . _post ( url = uURL , param_dict = params , securityHandler = self . _securityHandler , proxy_u...
def _check_docstring ( self , node_type , node , report_missing = True , confidence = None ) : """Check whether the opening and the closing of docstring on a line by themselves . Then check for epytext markups for function or method . @ param node _ type : type of node @ param node : current node of pylint"...
docstring = node . doc if docstring is None : # The node does not have a docstring . if _isInner ( node ) : # Do not check things inside a function or method . return if _isSetter ( node_type , node ) : # Setters don ' t need a docstring as they are documented in # the getter . return se...
def disable_contact_host_notifications ( self , contact ) : """Disable host notifications for a contact Format of the line that triggers function call : : DISABLE _ CONTACT _ HOST _ NOTIFICATIONS ; < contact _ name > : param contact : contact to disable : type contact : alignak . objects . contact . Contact...
if contact . host_notifications_enabled : contact . modified_attributes |= DICT_MODATTR [ "MODATTR_NOTIFICATIONS_ENABLED" ] . value contact . host_notifications_enabled = False self . send_an_element ( contact . get_update_status_brok ( ) )
def bibcode_from_url ( cls , url ) : """Given a URL , try to find the ADS bibcode . Currently : only ` ads ` URLs will work , e . g . Returns code : str or ' None ' The Bibcode if found , otherwise ' None '"""
try : code = url . split ( '/abs/' ) code = code [ 1 ] . strip ( ) return code except : return None
def check_instance_folder ( self , create = False ) : """Verify instance folder exists , is a directory , and has necessary permissions . : param : create : if ` True ` , creates directory hierarchy : raises : OSError with relevant errno if something is wrong ."""
path = Path ( self . instance_path ) err = None eno = 0 if not path . exists ( ) : if create : logger . info ( "Create instance folder: %s" , path ) path . mkdir ( 0o775 , parents = True ) else : err = "Instance folder does not exists" eno = errno . ENOENT elif not path . is_dir ...
async def register_storage_library ( storage_type : str , c_library : str , entry_point : str ) -> None : """Load a wallet storage plug - in . An indy - sdk wallet storage plug - in is a shared library ; relying parties must explicitly load it before creating or opening a wallet with the plug - in . The imple...
LOGGER . debug ( 'WalletManager.register_storage_library >>> storage_type %s, c_library %s, entry_point %s' , storage_type , c_library , entry_point ) try : stg_lib = CDLL ( c_library ) result = stg_lib [ entry_point ] ( ) if result : LOGGER . debug ( 'WalletManager.register_storage_library <!< indy...
def parse ( self , filename ) : """. reads 1 file . if there is a compilation error , print a warning . get root cursor and recurse . for each STRUCT _ DECL , register a new struct type . for each UNION _ DECL , register a new union type . for each TYPEDEF _ DECL , register a new alias / typdef to the und...
index = Index . create ( ) self . tu = index . parse ( filename , self . flags , options = self . tu_options ) if not self . tu : log . warning ( "unable to load input" ) return if len ( self . tu . diagnostics ) > 0 : for x in self . tu . diagnostics : log . warning ( x . spelling ) if x . ...
def set_dialect ( dialect ) : '''set the MAVLink dialect to work with . For example , set _ dialect ( " ardupilotmega " )'''
global mavlink , current_dialect from . generator import mavparse if 'MAVLINK20' in os . environ : wire_protocol = mavparse . PROTOCOL_2_0 modname = "pymavlink.dialects.v20." + dialect elif mavlink is None or mavlink . WIRE_PROTOCOL_VERSION == "1.0" or not 'MAVLINK09' in os . environ : wire_protocol = mavpa...
def GetSoapXMLForComplexType ( self , type_name , value ) : """Return an XML string representing a SOAP complex type . Args : type _ name : The name of the type with namespace prefix if necessary . value : A python dictionary to hydrate the type instance with . Returns : A string containing the SOAP XML f...
element = self . schema . get_element ( '{%s}%s' % ( self . _namespace_override , type_name ) ) result_element = self . _element_maker ( element . qname . localname ) element_value = element ( ** value ) element . type . render ( result_element , element_value ) data = lxml . etree . tostring ( result_element ) . strip...
def parse_params ( self , y = None , y_target = None , batch_size = 1 , confidence = 0 , learning_rate = 5e-3 , binary_search_steps = 5 , max_iterations = 1000 , abort_early = True , initial_const = 1e-2 , clip_min = 0 , clip_max = 1 ) : """: param y : ( optional ) A tensor with the true labels for an untargeted ...
# ignore the y and y _ target argument self . batch_size = batch_size self . confidence = confidence self . learning_rate = learning_rate self . binary_search_steps = binary_search_steps self . max_iterations = max_iterations self . abort_early = abort_early self . initial_const = initial_const self . clip_min = clip_m...
def _eval_once ( saver , summary_writer , top_1_op , top_5_op , summary_op ) : """Runs Eval once . Args : saver : Saver . summary _ writer : Summary writer . top _ 1 _ op : Top 1 op . top _ 5 _ op : Top 5 op . summary _ op : Summary op ."""
with tf . Session ( ) as sess : ckpt = tf . train . get_checkpoint_state ( FLAGS . checkpoint_dir ) if ckpt and ckpt . model_checkpoint_path : print ( "ckpt.model_checkpoint_path: {0}" . format ( ckpt . model_checkpoint_path ) ) saver . restore ( sess , ckpt . model_checkpoint_path ) # A...
def pop_front ( self ) : '''Remove the first element from of the list .'''
backend = self . backend return backend . execute ( backend . structure ( self ) . pop_front ( ) , self . value_pickler . loads )
def link ( self , content , link , title = '' ) : """Emit a link , potentially remapped based on our embed or static rules"""
link = links . resolve ( link , self . _search_path , self . _config . get ( 'absolute' ) ) return '{}{}</a>' . format ( utils . make_tag ( 'a' , { 'href' : link , 'title' : title if title else None } ) , content )
def generate_candidates ( freq_set , k ) : """Generate candidates for an iteration . Use this only for k > = 2."""
single_set = { ( i , ) for i in set ( flatten ( freq_set ) ) } # TO DO generating all combinations gets very slow for large documents . # Is there a way of doing this without exhaustively searching all combinations ? cands = [ flatten ( f ) for f in combinations ( single_set , k ) ] return [ cand for cand in cands if v...
def _TSKFileTimeCopyToStatTimeTuple ( self , tsk_file , time_value ) : """Copies a SleuthKit file object time value to a stat timestamp tuple . Args : tsk _ file ( pytsk3 . File ) : TSK file . time _ value ( str ) : name of the time value . Returns : tuple [ int , int ] : number of seconds since 1970-01-0...
if ( not tsk_file or not tsk_file . info or not tsk_file . info . meta or not tsk_file . info . fs_info ) : raise errors . BackEndError ( 'Missing TSK File .info, .info.meta. or .info.fs_info' ) stat_time = getattr ( tsk_file . info . meta , time_value , None ) stat_time_nano = None if self . _file_system_type in s...
def solve_limited ( self , assumptions = [ ] ) : """Solve internal formula using given budgets for conflicts and propagations ."""
if self . glucose : if self . use_timer : start_time = time . clock ( ) # saving default SIGINT handler def_sigint_handler = signal . signal ( signal . SIGINT , signal . SIG_DFL ) self . status = pysolvers . glucose41_solve_lim ( self . glucose , assumptions ) # recovering default SIGINT han...
def fn_available_argcount ( callable ) : """Returns the number of explicit non - keyword arguments that the callable can be called with . Bound methods are called with an implicit first argument , so this takes that into account . Excludes * args and * * kwargs declarations ."""
fn = get_fn_or_method ( callable ) if _inspect . isfunction ( fn ) : return fn . __code__ . co_argcount else : # method if fn . __self__ is None : return fn . __func__ . __code__ . co_argcount else : return fn . __func__ . __code__ . co_argcount - 1
def create_client_event ( self , parent , client_event , retry = google . api_core . gapic_v1 . method . DEFAULT , timeout = google . api_core . gapic_v1 . method . DEFAULT , metadata = None , ) : """Report events issued when end user interacts with customer ' s application that uses Cloud Talent Solution . You m...
# Wrap the transport method to add retry and timeout logic . if "create_client_event" not in self . _inner_api_calls : self . _inner_api_calls [ "create_client_event" ] = google . api_core . gapic_v1 . method . wrap_method ( self . transport . create_client_event , default_retry = self . _method_configs [ "CreateCl...
def init_widget ( self ) : """Initialize the underlying widget ."""
super ( AndroidViewAnimator , self ) . init_widget ( ) d = self . declaration if d . animate_first_view : self . set_animate_first_view ( d . animate_first_view ) if d . displayed_child : self . set_displayed_child ( d . displayed_child )
def remove ( self , contact_id , session ) : '''taobao . logistics . address . remove 删除卖家地址库 用此接口删除卖家地址库'''
request = TOPRequest ( 'taobao.logistics.address.remove' ) request [ 'contact_id' ] = contact_id self . create ( self . execute ( request , session ) ) return self . address_result
def compile ( self , # type : ignore manager_container , container : 'Container' , # type : ignore verbose : bool = False ) -> CompilationOutcome : """See ` Compiler . compile `"""
return self . __compile ( manager_container , container , self . __command , verbose )
def url_scan ( self , url , opts , functionality , enabled_functionality , hide_progressbar ) : """This is the main function called whenever a URL needs to be scanned . This is called when a user specifies an individual CMS , or after CMS identification has taken place . This function is called for individual ...
self . out . debug ( 'base_plugin_internal.url_scan -> %s' % str ( url ) ) if isinstance ( url , tuple ) : url , host_header = url else : url , host_header = self . _process_host_line ( url ) url = common . repair_url ( url ) if opts [ 'follow_redirects' ] : url , host_header = self . determine_redirect ( u...
def _set_fcoe_interface_bind ( self , v , load = False ) : """Setter method for fcoe _ interface _ bind , mapped from YANG variable / interface / fcoe / fcoe _ interface _ bind ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ fcoe _ interface _ bind is cons...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = fcoe_interface_bind . fcoe_interface_bind , is_container = 'container' , presence = False , yang_name = "fcoe-interface-bind" , rest_name = "bind" , parent = self , path_helper = self . _path_helper , extmethods = self . _ext...
def create ( self , object_name , size = 0 , hash = None , extra = None , meta_data = None ) : """create a new object : param object _ name : : param size : : param hash : : param extra : : param meta _ data : : return : Object"""
obj = BaseObject ( container = self . container , driver = self . driver , name = object_name , size = size , hash = hash , extra = extra , meta_data = meta_data ) return Object ( obj = obj )
def _append_national_number ( self , national_number ) : """Combines the national number with any prefix ( IDD / + and country code or national prefix ) that was collected . A space will be inserted between them if the current formatting template indicates this to be suitable ."""
prefix_before_nn_len = len ( self . _prefix_before_national_number ) if ( self . _should_add_space_after_national_prefix and prefix_before_nn_len > 0 and self . _prefix_before_national_number [ - 1 ] != _SEPARATOR_BEFORE_NATIONAL_NUMBER ) : # We want to add a space after the national prefix if the national # prefix for...
def update_label ( self , old_label , new_label , callback = dummy_progress_cb ) : """Replace ' old _ label ' by ' new _ label ' on all the documents . Takes care of updating the index ."""
current = 0 total = self . index . get_nb_docs ( ) self . index . start_update_label ( old_label , new_label ) while True : ( op , doc ) = self . index . continue_update_label ( ) if op == 'end' : break callback ( current , total , self . LABEL_STEP_UPDATING , doc ) current += 1 self . index . e...
def multi_post ( self , urls , query_params = None , data = None , to_json = True , send_as_file = False ) : """Issue multiple POST requests . Args : urls - A string URL or list of string URLs query _ params - None , a dict , or a list of dicts representing the query params data - None , a dict or string , ...
return self . _multi_request ( MultiRequest . _VERB_POST , urls , query_params , data , to_json = to_json , send_as_file = send_as_file , )
def get_schema_field ( schema , field ) : """Get the schema field of a model field : param Schema schema : a marshmallow schema : param str field : the name of the model field : return str : the name of the field in the schema"""
schema_fields_to_model = { key : get_model_field ( schema , key ) for ( key , value ) in schema . _declared_fields . items ( ) } for key , value in schema_fields_to_model . items ( ) : if value == field : return key raise Exception ( "Couldn't find schema field from {}" . format ( field ) )
def seconds_to_str_fromatter ( _format ) : """Accepted format directives : % i % s % m % h"""
# check directives are correct if _format == "%S" : def _fromatter ( seconds ) : return "{:.2f}" . format ( seconds ) elif _format == "%I" : def _fromatter ( seconds ) : return "{0}" . format ( int ( seconds * 1000 ) ) else : _format = _format . replace ( "%h" , "{hrs:02d}" ) _format = _...
def fit_traptransit ( ts , fs , p0 ) : """Fits trapezoid model to provided ts , fs"""
pfit , success = leastsq ( traptransit_resid , p0 , args = ( ts , fs ) ) if success not in [ 1 , 2 , 3 , 4 ] : raise NoFitError # logging . debug ( ' success = { } ' . format ( success ) ) return pfit
def neurons ( self ) : """Return list of neuron indices . Parameters None Returns list list of neuron indices See also sqlite3 . connect . cursor"""
self . cursor . execute ( 'SELECT DISTINCT neuron FROM spikes ORDER BY neuron' ) sel = self . cursor . fetchall ( ) return np . array ( sel ) . flatten ( )
def gcd ( vector ) : """Calculate the greatest common divisor ( GCD ) of a sequence of numbers . The sequence can be a list of numbers or a Numpy vector of numbers . The computations are carried out with a precision of 1E - 12 if the objects are not ` fractions < https : / / docs . python . org / 3 / library ...
# pylint : disable = C1801 if not len ( vector ) : return None if len ( vector ) == 1 : return vector [ 0 ] if len ( vector ) == 2 : return pgcd ( vector [ 0 ] , vector [ 1 ] ) current_gcd = pgcd ( vector [ 0 ] , vector [ 1 ] ) for element in vector [ 2 : ] : current_gcd = pgcd ( current_gcd , element )...
def get_servo_temperature ( self ) : """Gets the current temperature of Herkulex Args : none Returns : int : the current temperature register of Herkulex Raises : SerialException : Error occured while opening serial port"""
data = [ ] data . append ( 0x09 ) data . append ( self . servoid ) data . append ( RAM_READ_REQ ) data . append ( TEMPERATURE_RAM ) data . append ( BYTE2 ) send_data ( data ) rxdata = [ ] try : rxdata = SERPORT . read ( 13 ) return ord ( rxdata [ 9 ] ) except HerkulexError : raise HerkulexError ( "Could not...
def setEncoder ( self , encoder ) : """Sets the client ' s encoder ` ` encoder ` ` should be an instance of a ` ` json . JSONEncoder ` ` class"""
if not encoder : self . _encoder = json . JSONEncoder ( ) else : self . _encoder = encoder self . _encode = self . _encoder . encode
def unflatten ( d , key_as_tuple = True , delim = '.' , list_of_dicts = None , deepcopy = True ) : r"""unflatten dictionary with keys as tuples or delimited strings Parameters d : dict key _ as _ tuple : bool if true , keys are tuples , else , keys are delimited strings delim : str if keys are strings ,...
if not d : return d if deepcopy : try : d = copy . deepcopy ( d ) except Exception : warnings . warn ( 'error in deepcopy, so using references to input dict' ) if key_as_tuple : result = d . pop ( ( ) ) if ( ) in d else { } else : result = d . pop ( '' ) if '' in d else { } for key ,...
def save_current ( self ) : """Save current editor . If the editor . file . path is None , a save as dialog will be shown ."""
if self . current_widget ( ) is not None : editor = self . current_widget ( ) self . _save ( editor )
def locationFromElement ( self , element ) : """Find the MutatorMath location of this element , either by name or from a child element ."""
elementLocation = None for locationElement in element . findall ( '.location' ) : elementLocation = self . readLocationElement ( locationElement ) break return elementLocation
def close ( self ) : """Closes the internal connection ."""
self . cancel ( ) self . logger . debug ( "Closing AMQP connection" ) try : self . connection . close ( ) except Exception , eee : self . logger . warning ( "Received an error while trying to close AMQP connection: " + str ( eee ) )
def get_code_language ( self ) : """This is largely copied from bokeh . sphinxext . bokeh _ plot . run"""
js_source = self . get_js_source ( ) if self . options . get ( "include_html" , False ) : resources = get_sphinx_resources ( include_bokehjs_api = True ) html_source = BJS_HTML . render ( css_files = resources . css_files , js_files = resources . js_files , bjs_script = js_source ) return [ html_source , "h...
def generate_environment ( ) : """Generate the environment in ` ` / tmp ` ` and run the ZEO server process in another thread ."""
global TMP_PATH TMP_PATH = tempfile . mkdtemp ( ) # write ZEO server config to temp directory zeo_conf_path = os . path . join ( TMP_PATH , "zeo.conf" ) with open ( zeo_conf_path , "w" ) as f : f . write ( Template ( data_context ( "zeo.conf" ) ) . substitute ( path = TMP_PATH , server = ZEO_SERVER , port = ZEO_POR...
def get_or_connect ( self , address , authenticator = None ) : """Gets the existing connection for a given address . If it does not exist , the system will try to connect asynchronously . In this case , it returns a Future . When the connection is established at some point in time , it can be retrieved by using...
if address in self . connections : return ImmediateFuture ( self . connections [ address ] ) else : with self . _new_connection_mutex : if address in self . _pending_connections : return self . _pending_connections [ address ] else : authenticator = authenticator or self ...
def wait_for_jobs ( jobs ) : """Waits for all the jobs to be runnning . Args : jobs ( list ) : list of the python - grid5000 jobs to wait for Raises : Exception : if one of the job gets in error state ."""
all_running = False while not all_running : all_running = True time . sleep ( 5 ) for job in jobs : job . refresh ( ) scheduled = getattr ( job , "scheduled_at" , None ) if scheduled is not None : logger . info ( "Waiting for %s on %s [%s]" % ( job . uid , job . site , _d...
def _map_exercise_row_to_dict ( self , row ) : """Convert dictionary keys from raw CSV Exercise format to ricecooker keys ."""
row_cleaned = _clean_dict ( row ) license_id = row_cleaned [ CONTENT_LICENSE_ID_KEY ] if license_id : license_dict = dict ( license_id = row_cleaned [ CONTENT_LICENSE_ID_KEY ] , description = row_cleaned . get ( CONTENT_LICENSE_DESCRIPTION_KEY , None ) , copyright_holder = row_cleaned . get ( CONTENT_LICENSE_COPYRI...
def refresh_role ( self , role , file_hierarchy ) : """Checks and refreshes ( if needed ) all assistants with given role . Args : role : role of assistants to refresh file _ hierarchy : hierarchy as returned by devassistant . yaml _ assistant _ loader . YamlAssistantLoader . get _ assistants _ file _ hierarch...
if role not in self . cache : self . cache [ role ] = { } was_change = self . _refresh_hierarchy_recursive ( self . cache [ role ] , file_hierarchy ) if was_change : cf = open ( self . cache_file , 'w' ) yaml . dump ( self . cache , cf , Dumper = Dumper ) cf . close ( )
def orbit_fit_residuals ( discoveries , blockID = 'O13AE' ) : """Brett : What are relevant and stunning are the actual orbit fit residuals for orbits with d ( a ) / a < 1 % . I would be happy with a simple histogram of all those numbers , although the ' tail ' ( probably blended and not yet completely flagged )...
ra_residuals = [ ] dec_residuals = [ ] ressum = [ ] for i , orbit in enumerate ( discoveries ) : if ( orbit . da / orbit . a ) < 0.01 : print i , len ( discoveries ) , orbit . observations [ 0 ] . provisional_name , orbit . da / orbit . a res = orbit . residuals . split ( '\n' ) for r in res...
def get_without_invoice ( self ) : """Returns transactions that don ' t have an invoice . We filter out transactions that have children , because those transactions never have invoices - their children are the ones that would each have one invoice ."""
qs = Transaction . objects . filter ( children__isnull = True , invoice__isnull = True ) return qs
def integer ( self , rule , ** kwargs ) : """Implementation of : py : func : ` pynspect . traversers . RuleTreeTraverser . integer ` interface ."""
rule . value = int ( rule . value ) return rule
def _get_all ( self ) : '''return all items'''
rowid = 0 while True : SQL_SELECT_MANY = 'SELECT rowid, * FROM %s WHERE rowid > ? LIMIT ?;' % self . _table self . _cursor . execute ( SQL_SELECT_MANY , ( rowid , ITEMS_PER_REQUEST ) ) items = self . _cursor . fetchall ( ) if len ( items ) == 0 : break for item in items : rowid = ite...
def javascript ( filename , type = 'text/javascript' ) : '''A simple shortcut to render a ` ` script ` ` tag to a static javascript file'''
if '?' in filename and len ( filename . split ( '?' ) ) is 2 : filename , params = filename . split ( '?' ) return '<script type="%s" src="%s?%s"></script>' % ( type , staticfiles_storage . url ( filename ) , params ) else : return '<script type="%s" src="%s"></script>' % ( type , staticfiles_storage . url ...
def propagate ( self , request : Request , clientName ) : """Broadcast a PROPAGATE to all other nodes : param request : the REQUEST to propagate"""
if self . requests . has_propagated ( request , self . name ) : logger . trace ( "{} already propagated {}" . format ( self , request ) ) else : with self . metrics . measure_time ( MetricsName . SEND_PROPAGATE_TIME ) : self . requests . add_propagate ( request , self . name ) propagate = self ....
def guid_check_convert ( guid , allow_none = False ) : """Take a GUID in the form of hex string " 32 " or " 8-4-4-4-12 " . Returns hex string " 32 " or raises ValueError : badly formed hexadecimal UUID string"""
if isinstance ( guid , string_types ) : return ensure_unicode ( UUID ( guid ) . hex ) elif guid is None and allow_none : return None else : raise ValueError ( 'guid must be a string' )
def do_alias ( self , args : argparse . Namespace ) -> None : """Manage aliases"""
func = getattr ( args , 'func' , None ) if func is not None : # Call whatever sub - command function was selected func ( self , args ) else : # No sub - command was provided , so call help self . do_help ( 'alias' )
def absent ( name , keys = None , user = None , gnupghome = None , ** kwargs ) : '''Ensure GPG public key is absent in keychain name The unique name or keyid for the GPG public key . keys The keyId or keyIds to add to the GPG keychain . user Remove GPG keys from the specified user ' s keychain gnupgho...
ret = { 'name' : name , 'result' : True , 'changes' : { } , 'comment' : [ ] } _current_keys = __salt__ [ 'gpg.list_keys' ] ( ) current_keys = [ ] for key in _current_keys : current_keys . append ( key [ 'keyid' ] ) if not keys : keys = name if isinstance ( keys , six . string_types ) : keys = [ keys ] for k...
def load ( self , rel_path = None ) : """Add data _ sources to layer and open files with data for the data _ source ."""
for k , v in self . layer . iteritems ( ) : self . add ( k , v [ 'module' ] , v . get ( 'package' ) ) filename = v . get ( 'filename' ) path = v . get ( 'path' ) if filename : # default path for data is in . . / data if not path : path = rel_path else : path = os ...
def set_custom ( self , gmin , gmu , gsigma ) : """Set a minimum lengtha , and then the gaussian distribution parameters for cutting For any sequence longer than the minimum the guassian parameters will be used"""
self . _gauss_min = gmin self . _gauss_mu = gmu self . _gauss_sigma = gsigma
def adjacent ( self , rng2 ) : """Test for adjacency . : param rng2: : param use _ direction : false by default : param type : GenomicRange : param type : use _ direction"""
if self . chr != rng2 . chr : return False if self . direction != rng2 . direction and use_direction : return False if self . end == rng2 . start - 1 : return True if self . start - 1 == rng2 . end : return True return False
def estimate_column_means ( self , X , observed , row_means , row_scales ) : """column _ center [ j ] = sum { i in observed [ : , j ] } { (1 / row _ scale [ i ] ) * ( X [ i , j ] ) - row _ center [ i ] ) sum { i in observed [ : , j ] } { 1 / row _ scale [ i ] }"""
n_rows , n_cols = X . shape row_means = np . asarray ( row_means ) if len ( row_means ) != n_rows : raise ValueError ( "Expected length %d but got shape %s" % ( n_rows , row_means . shape ) ) column_means = np . zeros ( n_cols , dtype = X . dtype ) X = X - row_means . reshape ( ( n_rows , 1 ) ) row_weights = 1.0 / ...
def add_required_resources ( resources ) : """Add default or empty values for required resources referenced in CWL"""
required = [ [ "variation" , "cosmic" ] , [ "variation" , "clinvar" ] , [ "variation" , "dbsnp" ] , [ "variation" , "lcr" ] , [ "variation" , "polyx" ] , [ "variation" , "encode_blacklist" ] , [ "variation" , "gc_profile" ] , [ "variation" , "germline_het_pon" ] , [ "variation" , "train_hapmap" ] , [ "variation" , "tra...
def _mk_connectivity ( self , section , i12 , j1 , j2 ) : """Helper function for _ mk _ adjacency _ matrix . Calculates the drainage neighbors and proportions based on the direction . This deals with non - flat regions in the image . In this case , each pixel can only drain to either 1 or two neighbors ."""
shp = np . array ( section . shape ) - 1 facets = self . facets for ii , facet in enumerate ( facets ) : e1 = facet [ 1 ] e2 = facet [ 2 ] I = section [ 1 : - 1 , 1 : - 1 ] == ii j1 [ 1 : - 1 , 1 : - 1 ] [ I ] = i12 [ 1 + e1 [ 0 ] : shp [ 0 ] + e1 [ 0 ] , 1 + e1 [ 1 ] : shp [ 1 ] + e1 [ 1 ] ] [ I ] ...
def _add_nec_args ( self , payload ) : """Adds ' limit ' and ' created _ utc ' arguments to the payload as necessary ."""
if self . _limited ( payload ) : # Do nothing I guess ? Not sure how paging works on this endpoint . . . return if 'limit' not in payload : payload [ 'limit' ] = self . max_results_per_request if 'sort' not in payload : # Getting weird results if this is not made explicit . Unclear why . payload [ 'sort' ] ...
def export_flow_process_data ( params , process ) : """Creates a new SequenceFlow XML element for given edge parameters and adds it to ' process ' element . : param params : dictionary with edge parameters , : param process : object of Element class , representing BPMN XML ' process ' element ( root for sequenc...
output_flow = eTree . SubElement ( process , consts . Consts . sequence_flow ) output_flow . set ( consts . Consts . id , params [ consts . Consts . id ] ) output_flow . set ( consts . Consts . name , params [ consts . Consts . name ] ) output_flow . set ( consts . Consts . source_ref , params [ consts . Consts . sourc...
def deleteAllActivationKeys ( server ) : '''Delete all activation keys from Spacewalk CLI Example : . . code - block : : bash salt - run spacewalk . deleteAllActivationKeys spacewalk01 . domain . com'''
try : client , key = _get_session ( server ) except Exception as exc : err_msg = 'Exception raised when connecting to spacewalk server ({0}): {1}' . format ( server , exc ) log . error ( err_msg ) return { 'Error' : err_msg } activation_keys = client . activationkey . listActivationKeys ( key ) deleted_...
def precondition ( self ) : """Check if the number of plurals in the two languages is the same ."""
return self . tlang . nplurals == self . slang . nplurals and super ( PrintfValidator , self ) . precondition ( )
def main ( args = None ) : """Extract protein - coding genes and store in tab - delimited text file . Parameters args : argparse . Namespace object , optional The argument values . If not specified , the values will be obtained by parsing the command line arguments using the ` argparse ` module . Returns ...
vinfo = sys . version_info if not vinfo >= ( 2 , 7 ) : raise SystemError ( 'Python interpreter version >= 2.7 required, ' 'found %d.%d instead.' % ( vinfo . major , vinfo . minor ) ) if args is None : # parse command - line arguments parser = get_argument_parser ( ) args = parser . parse_args ( ) input_file...
def upsert ( self , * fields ) : """Update or Insert this document depending on whether it exists or not . The presense of an ` _ id ` value in the document is used to determine if the document exists . NOTE : This method is not the same as specifying the ` upsert ` flag when calling MongoDB . When called f...
# If no ` _ id ` is provided then we insert the document if not self . _id : return self . insert ( ) # If an ` _ id ` is provided then we need to check if it exists before # performing the ` upsert ` . if self . count ( { '_id' : self . _id } ) == 0 : self . insert ( ) else : self . update ( * fields )
def set_contour_properties ( contour_file_path ) : """Set the X , Y , RGB , ROMAN attributes of the contour layer . : param contour _ file _ path : Path of the contour layer . : type contour _ file _ path : str : raise : InvalidLayerError if anything is amiss with the layer ."""
LOGGER . debug ( 'Set_contour_properties requested for %s.' % contour_file_path ) layer = QgsVectorLayer ( contour_file_path , 'mmi-contours' , "ogr" ) if not layer . isValid ( ) : raise InvalidLayerError ( contour_file_path ) layer . startEditing ( ) # Now loop through the db adding selected features to mem layer ...
def _no_answer_do_retry ( self , pk , pattern ) : """Resend packets that we have not gotten answers to"""
logger . info ( 'Resending for pattern %s' , pattern ) # Set the timer to None before trying to send again self . send_packet ( pk , expected_reply = pattern , resend = True )
def _resample_nnresample2 ( s , up , down , beta = 5.0 , L = 16001 , axis = 0 ) : # type : ( np . ndarray , float , float , float , int , int ) - > np . ndarray """Taken from https : / / github . com / jthiem / nnresample Resample a signal from rate " down " to rate " up " Parameters x : array _ like The da...
# check if a resampling filter with the chosen parameters already exists params = ( up , down , beta , L ) if params in _precomputed_filters . keys ( ) : # if so , use it . filt = _precomputed_filters [ params ] else : # if not , generate filter , store it , use it filt = _nnresample_compute_filt ( up , down , ...
def forward_packet ( self , writer , packet , raw_packet ) : """Forward packet from client to RFLink ."""
peer = writer . get_extra_info ( 'peername' ) log . debug ( ' %s:%s: forwarding data: %s' , peer [ 0 ] , peer [ 1 ] , packet ) if 'command' in packet : packet_id = serialize_packet_id ( packet ) command = packet [ 'command' ] ack = yield from self . protocol . send_command_ack ( packet_id , command ) if...
def reconnect ( self ) : '''Connected the stream if needed . Coroutine .'''
if self . _connection . closed ( ) : self . _connection . reset ( ) yield from self . _connection . connect ( )
def end_grouping ( self ) : """Raises IndexError when no group is open ."""
close = self . _open . pop ( ) if not close : return if self . _open : self . _open [ - 1 ] . extend ( close ) elif self . _undoing : self . _redo . append ( close ) else : self . _undo . append ( close ) self . notify ( )