signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def email_addresses2marc ( self , key , value ) : """Populate the 595 MARCXML field . Also populates the 371 field as a side effect ."""
m_or_o = 'm' if value . get ( 'current' ) else 'o' element = { m_or_o : value . get ( 'value' ) } if value . get ( 'hidden' ) : return element else : self . setdefault ( '371' , [ ] ) . append ( element ) return None
def account_get ( self , key ) : """Get account number for the * * public key * * : param key : Public key to get account for : type key : str : raises : : py : exc : ` nano . rpc . RPCException ` > > > rpc . account _ get ( . . . key = " 3068BB1CA04525BB0E416C485FE6A67FD52540227D267CC8B6E8DA958A7FA039" ...
key = self . _process_value ( key , 'publickey' ) payload = { "key" : key } resp = self . call ( 'account_get' , payload ) return resp [ 'account' ]
def run_steps ( args : argparse . Namespace ) : """Run all steps required to complete task . Called directly from main ."""
logging . basicConfig ( level = logging . INFO , format = "sockeye.autopilot: %(message)s" ) # (1 ) Establish task logging . info ( "=== Start Autopilot ===" ) # Listed task if args . task : task = TASKS [ args . task ] logging . info ( "Task: %s" , task . description ) logging . info ( "URL: %s" , task . u...
def connect_to_wifi ( self , ssid , password = None ) : """[ Test Agent ] Connect to * ssid * with * password *"""
cmd = 'am broadcast -a testagent -e action CONNECT_TO_WIFI -e ssid %s -e password %s' % ( ssid , password ) self . adb . shell_cmd ( cmd )
def rankdata ( inlist ) : """Ranks the data in inlist , dealing with ties appropritely . Assumes a 1D inlist . Adapted from Gary Perlman ' s | Stat ranksort . Usage : rankdata ( inlist ) Returns : a list of length equal to inlist , containing rank scores"""
n = len ( inlist ) svec , ivec = shellsort ( inlist ) sumranks = 0 dupcount = 0 newlist = [ 0 ] * n for i in range ( n ) : sumranks = sumranks + i dupcount = dupcount + 1 if i == n - 1 or svec [ i ] != svec [ i + 1 ] : averank = sumranks / float ( dupcount ) + 1 for j in range ( i - dupcount...
def init ( celf , * , loop = None , unregister = None , message = None ) : "for consistency with other classes that don ’ t want caller to instantiate directly ."
return celf ( loop = loop , unregister = unregister , message = message , )
def new_socket ( ) : """Create a new socket with OS - specific parameters Try to set SO _ REUSEPORT for BSD - flavored systems if it ' s an option . Catches errors if not ."""
new_sock = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) new_sock . setsockopt ( socket . SOL_SOCKET , socket . SO_REUSEADDR , 1 ) try : # noinspection PyUnresolvedReferences reuseport = socket . SO_REUSEPORT except AttributeError : pass else : try : new_sock . setsockopt ( socket . SO...
def increment_counter ( self , id , counter_name , increment = 1 , id_name = 'id' , ** kwargs ) : """Atomically increments a counter attribute in the item identified by ` ` id ` ` . You must specify the name of the attribute as ` ` counter _ name ` ` and , optionally , the ` ` increment ` ` which defaults to ` ...
response = self . _new_response ( ) if self . _check_supported_op ( 'increment_counter' , response ) : params = { 'Key' : { id_name : id } , 'UpdateExpression' : 'set #ctr = #ctr + :val' , 'ExpressionAttributeNames' : { "#ctr" : counter_name } , 'ExpressionAttributeValues' : { ':val' : decimal . Decimal ( increment...
def get_go2obj ( self , goids ) : """Return GO Terms for each user - specified GO ID . Note missing GO IDs ."""
goids = goids . intersection ( self . go2obj . keys ( ) ) if len ( goids ) != len ( goids ) : goids_missing = goids . difference ( goids ) print ( " {N} MISSING GO IDs: {GOs}" . format ( N = len ( goids_missing ) , GOs = goids_missing ) ) return { go : self . go2obj [ go ] for go in goids }
def get ( self , * args , ** kwargs ) : """wraps the default get ( ) and deals with encoding"""
value , stat = super ( XClient , self ) . get ( * args , ** kwargs ) try : if value is not None : value = value . decode ( encoding = "utf-8" ) except UnicodeDecodeError : pass return ( value , stat )
def _get_entries_for_calculation ( self ) : """Ignores entries flagged with ignoreForCalculation"""
mgr = self . _get_provider_manager ( 'Grading' ) # what about the Proxy ? if not mgr . supports_gradebook_column_lookup ( ) : raise errors . OperationFailed ( 'Grading does not support GradebookColumn lookup' ) gradebook_id = Id ( self . _my_map [ 'assignedGradebookIds' ] [ 0 ] ) lookup_session = mgr . get_grade_en...
def search ( self , fields = None , query = None , filters = None ) : """Search for entities . At its simplest , this method searches for all entities of a given kind . For example , to ask for all : class : ` nailgun . entities . LifecycleEnvironment ` entities : : LifecycleEnvironment ( ) . search ( ) V...
# Goals : # * Be tolerant of missing values . It ' s reasonable for the server to # return an incomplete set of attributes for each search result . # * Use as many returned values as possible . There ' s no point in # letting returned data go to waste . This implies that we must . . . # * . . . parse irregular server r...
def removeProductFrom ( self , userstore ) : """Uninstall all the powerups this product references and remove the Installation item from the user ' s store . Doesn ' t remove the actual powerups currently , but / should / reactivate them if this product is reinstalled ."""
def uninstall ( ) : # this is probably highly insufficient , but i don ' t know the # requirements i = userstore . findFirst ( Installation , Installation . types == self . types ) i . uninstall ( ) i . deleteFromStore ( ) userstore . transact ( uninstall )
def mappedPolygon ( self , polygon , path = None , percent = 0.5 ) : """Maps the inputed polygon to the inputed path used when drawing items along the path . If no specific path is supplied , then this object ' s own path will be used . It will rotate and move the polygon according to the inputed percentage . : p...
translatePerc = percent anglePerc = percent # we don ' t want to allow the angle percentage greater than 0.85 # or less than 0.05 or we won ' t get a good rotation angle if 0.95 <= anglePerc : anglePerc = 0.98 elif anglePerc <= 0.05 : anglePerc = 0.05 if not path : path = self . path ( ) if not ( path and p...
def send_message ( self , room_id , text_content , msgtype = "m.text" , timestamp = None ) : """Perform PUT / rooms / $ room _ id / send / m . room . message Args : room _ id ( str ) : The room ID to send the event in . text _ content ( str ) : The m . text body to send . timestamp ( int ) : Set origin _ se...
return self . send_message_event ( room_id , "m.room.message" , self . get_text_body ( text_content , msgtype ) , timestamp = timestamp )
def talk_back ( self , message ) : """that ' s what she said : Tells you some things she actually said . : )"""
quote = self . get_quote ( ) if quote : self . reply ( "Actually, she said things like this: \n%s" % quote )
def bbox ( self ) : """BBox"""
return self . left , self . top , self . right , self . bottom
def sync ( self , graph_commons ) : """Synchronize local and remote representations ."""
if self [ 'id' ] is None : return remote_graph = graph_commons . graphs ( self [ 'id' ] ) # TODO : less forceful , more elegant self . edges = remote_graph . edges self . nodes = remote_graph . nodes self . node_types = remote_graph . node_types self . edge_types = remote_graph . edge_types self . _edges = dict ( (...
def create_tutorial_layout ( self ) : """layout for example tutorial"""
lexer , _ , _ = get_lexers ( self . shell_ctx . lexer , None , None ) layout_full = HSplit ( [ FloatContainer ( Window ( BufferControl ( input_processors = self . input_processors , lexer = lexer , preview_search = Always ( ) ) , get_height = get_height ) , [ Float ( xcursor = True , ycursor = True , content = Completi...
def make_idx ( f , lb , ub ) : """This is a little utility function to replace an oft - called set of operations Parameters f : 1d array A frequency axis along which we want to slice lb : float Defines the upper bound of slicing ub : float Defines the lower bound of slicing Returns idx : a slice...
idx0 = np . argmin ( np . abs ( f - lb ) ) idx1 = np . argmin ( np . abs ( f - ub ) ) # Determine which should be on which side if f [ 0 ] > f [ 1 ] : direction = - 1 else : direction = 1 if direction == - 1 : idx = slice ( idx1 , idx0 ) elif direction == 1 : idx = slice ( idx0 , idx1 ) return idx
def register_epsf ( self , epsf ) : """Register and scale ( in flux ) the input ` ` epsf ` ` to the star . Parameters epsf : ` EPSFModel ` The ePSF to register . Returns data : ` ~ numpy . ndarray ` A 2D array of the registered / scaled ePSF ."""
yy , xx = np . indices ( self . shape , dtype = np . float ) xx = epsf . _oversampling [ 0 ] * ( xx - self . cutout_center [ 0 ] ) yy = epsf . _oversampling [ 1 ] * ( yy - self . cutout_center [ 1 ] ) return ( self . flux * np . prod ( epsf . _oversampling ) * epsf . evaluate ( xx , yy , flux = 1.0 , x_0 = 0.0 , y_0 = ...
def blackbox_and_coarse_grain ( blackbox , coarse_grain ) : """Validate that a coarse - graining properly combines the outputs of a blackboxing ."""
if blackbox is None : return for box in blackbox . partition : # Outputs of the box outputs = set ( box ) & set ( blackbox . output_indices ) if coarse_grain is None and len ( outputs ) > 1 : raise ValueError ( 'A blackboxing with multiple outputs per box must be ' 'coarse-grained.' ) if ( coars...
def duration ( self ) : """The duration of this stimulus : returns : float - - duration in seconds"""
durs = [ ] for track in self . _segments : durs . append ( sum ( [ comp . duration ( ) for comp in track ] ) ) return max ( durs )
def tempoAdjust4 ( self , tempoFactor ) : """Adjust tempo by aggregating active basal cell votes for pre vs . post - > if vote total = 0 ( tied ) , use result of last vote - > if two wrong scale decisions in a row , use max / min tempo in opposite direction : param tempoFactor : scaling signal to MC clock fro...
late_votes = ( len ( self . adtm . getNextBasalPredictedCells ( ) ) - len ( self . apicalIntersect ) ) * - 1 early_votes = len ( self . apicalIntersect ) votes = late_votes + early_votes print ( 'vote tally' , votes ) if votes > 0 : newScale = 0.5 print 'speed up' elif votes < 0 : newScale = 2 print 'sl...
def prepare_kwargs ( all_kwargs , class_init_kwargs ) : '''Filter out the kwargs used for the init of the class and the kwargs used to invoke the command required . all _ kwargs All the kwargs the Execution Function has been invoked . class _ init _ kwargs The kwargs of the ` ` _ _ init _ _ ` ` of the cla...
fun_kwargs = { } init_kwargs = { } for karg , warg in six . iteritems ( all_kwargs ) : if karg not in class_init_kwargs : if warg is not None : fun_kwargs [ karg ] = warg continue if warg is not None : init_kwargs [ karg ] = warg return init_kwargs , fun_kwargs
def load_globals ( self , filename , hdu_index = 0 , bkgin = None , rmsin = None , beam = None , verb = False , rms = None , bkg = None , cores = 1 , do_curve = True , mask = None , lat = None , psf = None , blank = False , docov = True , cube_index = None ) : """Populate the global _ data object by loading or calc...
# don ' t reload already loaded data if self . global_data . img is not None : return img = FitsImage ( filename , hdu_index = hdu_index , beam = beam , cube_index = cube_index ) beam = img . beam debug = logging . getLogger ( 'Aegean' ) . isEnabledFor ( logging . DEBUG ) if mask is None : self . global_data . ...
def set_to_default ( section , key ) : """Set the value of the given seciton and key to default : param section : the section of a configspec : type section : section : param key : a key of the section : type key : str : returns : None : raises : None"""
section [ key ] = section . default_values . get ( key , section [ key ] )
def integral_element ( mu , pdf ) : '''Returns an array of elements of the integrand dP = p ( mu ) dmu for a density p ( mu ) defined at sample values mu ; samples need not be equally spaced . Uses a simple trapezium rule . Number of dP elements is 1 - ( number of mu samples ) .'''
dmu = mu [ 1 : ] - mu [ : - 1 ] bin_mean = ( pdf [ 1 : ] + pdf [ : - 1 ] ) / 2. return dmu * bin_mean
def from_vrep ( config , vrep_host = '127.0.0.1' , vrep_port = 19997 , scene = None , tracked_objects = [ ] , tracked_collisions = [ ] , id = None , shared_vrep_io = None ) : """Create a robot from a V - REP instance . : param config : robot configuration ( either the path to the json or directly the dictionary )...
if shared_vrep_io is None : vrep_io = VrepIO ( vrep_host , vrep_port ) else : vrep_io = shared_vrep_io vreptime = vrep_time ( vrep_io ) pypot_time . time = vreptime . get_time pypot_time . sleep = vreptime . sleep if isinstance ( config , basestring ) : with open ( config ) as f : config = json . lo...
def mime_type ( self , path ) : """Get mime - type from filename"""
name , ext = os . path . splitext ( path ) return MIME_TYPES [ ext ]
def register_area ( self , area_code , index , userdata ) : """Shares a memory area with the server . That memory block will be visible by the clients ."""
size = ctypes . sizeof ( userdata ) logger . info ( "registering area %s, index %s, size %s" % ( area_code , index , size ) ) size = ctypes . sizeof ( userdata ) return self . library . Srv_RegisterArea ( self . pointer , area_code , index , ctypes . byref ( userdata ) , size )
def FromTextFormat ( cls , text ) : """Parse this object from a text representation ."""
tmp = cls . protobuf ( ) # pylint : disable = not - callable text_format . Merge ( text , tmp ) return cls . FromSerializedString ( tmp . SerializeToString ( ) )
def create ( cls , bucket , key , size , chunk_size ) : """Create a new object in a bucket ."""
bucket = as_bucket ( bucket ) if bucket . locked : raise BucketLockedError ( ) # Validate chunk size . if not cls . is_valid_chunksize ( chunk_size ) : raise MultipartInvalidChunkSize ( ) # Validate max theoretical size . if not cls . is_valid_size ( size , chunk_size ) : raise MultipartInvalidSize ( ) # Va...
def file_object_supports_binary ( fp ) : # type : ( BinaryIO ) - > bool '''A function to check whether a file - like object supports binary mode . Parameters : fp - The file - like object to check for binary mode support . Returns : True if the file - like object supports binary mode , False otherwise .'''
if hasattr ( fp , 'mode' ) : return 'b' in fp . mode # Python 3 if sys . version_info >= ( 3 , 0 ) : return isinstance ( fp , ( io . RawIOBase , io . BufferedIOBase ) ) # Python 2 return isinstance ( fp , ( cStringIO . OutputType , cStringIO . InputType , io . RawIOBase , io . BufferedIOBase ) )
def get_nowait ( self , name , default = _MISSING , autoremove = False ) : """Get the value of a key if it is already set . This method allows you to check if a key has already been set without blocking . If the key has not been set you will get the default value you pass in or KeyError ( ) if no default is p...
self . _ensure_declared ( name ) try : future = self . _data [ name ] if future . done ( ) : return future . result ( ) if default is _MISSING : raise KeyError ( "Key {} has not been assigned a value and no default given" . format ( name ) ) return default finally : if autoremove : ...
def startup_gce_instance ( instance_name , project , zone , username , machine_type , image , public_key , disk_name = None ) : """For now , jclouds is broken for GCE and we will have static slaves in Jenkins . Use this to boot them ."""
log_green ( "Started..." ) log_yellow ( "...Creating GCE Jenkins Slave Instance..." ) instance_config = get_gce_instance_config ( instance_name , project , zone , machine_type , image , username , public_key , disk_name ) operation = _get_gce_compute ( ) . instances ( ) . insert ( project = project , zone = zone , body...
def is_hosting_device_reachable ( self , hosting_device ) : """Check the hosting device which hosts this resource is reachable . If the resource is not reachable , it is added to the backlog . * heartbeat revision We want to enqueue all hosting - devices into the backlog for monitoring purposes adds key /...
ret_val = False hd = hosting_device hd_id = hosting_device [ 'id' ] hd_mgmt_ip = hosting_device [ 'management_ip_address' ] dead_hd_list = self . get_dead_hosting_devices_info ( ) if hd_id in dead_hd_list : LOG . debug ( "Hosting device: %(hd_id)s@%(ip)s is already marked as" " Dead. It is assigned as non-reachable...
def get_callable_name ( c ) : """Get a human - friendly name for the given callable . : param c : The callable to get the name for : type c : callable : rtype : unicode"""
if hasattr ( c , 'name' ) : return six . text_type ( c . name ) elif hasattr ( c , '__name__' ) : return six . text_type ( c . __name__ ) + u'()' else : return six . text_type ( c )
def _get_limit_and_offset ( page , page_size ) : """Returns a 0 - indexed offset and limit based on page and page _ size for a MySQL query ."""
if page < 1 : raise ValueError ( 'page must be >= 1' ) limit = page_size offset = ( page - 1 ) * page_size return limit , offset
def _create_action ( factory_self , action_model , resource_name , service_context , is_load = False ) : """Creates a new method which makes a request to the underlying AWS service ."""
# Create the action in in this closure but before the ` ` do _ action ` ` # method below is invoked , which allows instances of the resource # to share the ServiceAction instance . action = AIOServiceAction ( action_model , factory = factory_self , service_context = service_context ) # A resource ' s ` ` load ` ` metho...
def from_arrays ( cls , arrays , name = None , ** kwargs ) : """Creates a new instance of self from the given ( list of ) array ( s ) . This is done by calling numpy . rec . fromarrays on the given arrays with the given kwargs . The type of the returned array is cast to this class , and the name ( if provided...
obj = numpy . rec . fromarrays ( arrays , ** kwargs ) . view ( type = cls ) obj . name = name return obj
def user_terms_updated ( sender , ** kwargs ) : """Called when user terms and conditions is changed - to force cache clearing"""
LOGGER . debug ( "User T&C Updated Signal Handler" ) if kwargs . get ( 'instance' ) . user : cache . delete ( 'tandc.not_agreed_terms_' + kwargs . get ( 'instance' ) . user . get_username ( ) )
def perc ( arr , p = 95 , ** kwargs ) : """Create symmetric percentiles , with ` ` p ` ` coverage ."""
offset = ( 100 - p ) / 2 return np . percentile ( arr , ( offset , 100 - offset ) , ** kwargs )
def qteMakeWidgetActive ( self , widgetObj : QtGui . QWidget ) : """Give keyboard focus to ` ` widgetObj ` ` . If ` ` widgetObj ` ` is * * None * * then the internal focus state is reset , but the focus manger will automatically activate the first available widget again . | Args | * ` ` widgetObj ` ` ( * ...
# Void the active widget information . if widgetObj is None : self . _qteActiveWidget = None return # Ensure that this applet is an ancestor of ` ` widgetObj ` ` # inside the Qt hierarchy . if qteGetAppletFromWidget ( widgetObj ) is not self : msg = 'The specified widget is not inside the current applet.' ...
def route_path ( self , path ) : '''Hacky function that ' s presently only useful for testing , gets the view that handles the given path . Later may be incorporated into the URL routing'''
path = path . strip ( '/' ) name , _ , subpath = path . partition ( '/' ) for service in singletons . settings . load_all ( 'SERVICES' ) : if service . SERVICE_NAME == name : # Found service ! break else : return [ ] , None # found no service for partial_url , view in service . urls . items ( ) : pa...
def setup_bash_in_container ( builddir , _container , outfile , shell ) : """Setup a bash environment inside a container . Creates a new chroot , which the user can use as a bash to run the wanted projects inside the mounted container , that also gets returned afterwards ."""
with local . cwd ( builddir ) : # Switch to bash inside uchroot print ( "Entering bash inside User-Chroot. Prepare your image and " "type 'exit' when you are done. If bash exits with a non-zero" "exit code, no new container will be stored." ) store_new_container = True try : run_in_container ( shell...
def ensure_object_is_string ( item , title ) : """Checks that the item is a string . If not , raises ValueError ."""
assert isinstance ( title , str ) if not isinstance ( item , str ) : msg = "{} must be a string. {} passed instead." raise TypeError ( msg . format ( title , type ( item ) ) ) return None
def get_option ( self , key ) : """Return the current value of the option ` key ` ( string ) . Instance method , only refers to current instance ."""
return self . _options . get ( key , self . _default_options [ key ] )
def compute_ecc_hash ( ecc_manager , hasher , buf , max_block_size , rate , message_size = None , as_string = False ) : '''Split a string in blocks given max _ block _ size and compute the hash and ecc for each block , and then return a nice list with both for easy processing .'''
result = [ ] # If required parameters were not provided , we compute them if not message_size : ecc_params = compute_ecc_params ( max_block_size , rate , hasher ) message_size = ecc_params [ "message_size" ] # Split the buffer string in blocks ( necessary for Reed - Solomon encoding because it ' s limited to 25...
def match ( fullname1 , fullname2 , strictness = 'default' , options = None ) : """Takes two names and returns true if they describe the same person . : param string fullname1 : first human name : param string fullname2 : second human name : param string strictness : strictness settings to use : param dict ...
if options is not None : settings = deepcopy ( SETTINGS [ strictness ] ) deep_update_dict ( settings , options ) else : settings = SETTINGS [ strictness ] name1 = Name ( fullname1 ) name2 = Name ( fullname2 ) return name1 . deep_compare ( name2 , settings )
def prt_gene_aart_details ( self , geneids , prt = sys . stdout ) : """For each gene , print ASCII art which represents its associated GO IDs ."""
_go2nt = self . sortobj . grprobj . go2nt patgene = self . datobj . kws [ "fmtgene2" ] patgo = self . datobj . kws [ "fmtgo2" ] itemid2name = self . datobj . kws . get ( "itemid2name" ) chr2i = self . datobj . get_chr2idx ( ) for geneid in geneids : gos_gene = self . gene2gos [ geneid ] symbol = "" if itemid2na...
def to_gremlin ( self ) : """Return a unicode object with the Gremlin representation of this block ."""
self . validate ( ) if len ( self . start_class ) == 1 : # The official Gremlin documentation claims that this approach # is generally faster than the one below , since it makes using indexes easier . # http : / / gremlindocs . spmallette . documentup . com / # filter / has start_class = list ( self . start_class )...
def complete ( self ) : """Mark a multipart object as complete ."""
if Part . count ( self ) != self . last_part_number + 1 : raise MultipartMissingParts ( ) with db . session . begin_nested ( ) : self . completed = True self . file . readable = True self . file . writable = False return self
def _key ( self ) : """A tuple key that uniquely describes this field . Used to compute this instance ' s hashcode and evaluate equality . Returns : tuple : The contents of this : class : ` ~ google . cloud . bigquery . schema . SchemaField ` ."""
return ( self . _name , self . _field_type . upper ( ) , self . _mode . upper ( ) , self . _description , self . _fields , )
def add_scheduling_block ( config , schema_path = None ) : """Add a Scheduling Block to the Configuration Database . The configuration dictionary must match the schema defined in in the schema _ path variable at the top of the function . Args : config ( dict ) : Scheduling Block instance request configurati...
if schema_path is None : schema_path = os . path . join ( os . path . dirname ( __file__ ) , 'sbi_post.json' ) schema = load_schema ( schema_path ) jsonschema . validate ( config , schema ) # Add the scheduling block to the database # ( This is done as a single k / v pair here but would probably be # expanded to a ...
def _init_from_npy2d ( self , mat , missing ) : """Initialize data from a 2 - D numpy matrix ."""
if len ( mat . shape ) != 2 : raise ValueError ( 'Input numpy.ndarray must be 2 dimensional' ) data = np . array ( mat . reshape ( mat . size ) , dtype = np . float32 ) self . handle = ctypes . c_void_p ( ) _check_call ( _LIB . XGDMatrixCreateFromMat ( data . ctypes . data_as ( ctypes . POINTER ( ctypes . c_float )...
async def verify_docker_image_task ( chain , link ) : """Verify the docker image Link . Args : chain ( ChainOfTrust ) : the chain we ' re operating on . link ( LinkOfTrust ) : the task link we ' re checking ."""
errors = [ ] # workerType worker_type = get_worker_type ( link . task ) if worker_type not in chain . context . config [ 'valid_docker_image_worker_types' ] : errors . append ( "{} is not a valid docker-image workerType!" . format ( worker_type ) ) raise_on_errors ( errors )
def get_table ( self , dbname , tbl_name ) : """Parameters : - dbname - tbl _ name"""
self . send_get_table ( dbname , tbl_name ) return self . recv_get_table ( )
def get_vnetwork_hosts_input_vcenter ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) get_vnetwork_hosts = ET . Element ( "get_vnetwork_hosts" ) config = get_vnetwork_hosts input = ET . SubElement ( get_vnetwork_hosts , "input" ) vcenter = ET . SubElement ( input , "vcenter" ) vcenter . text = kwargs . pop ( 'vcenter' ) callback = kwargs . pop ( 'callback' , self . _ca...
def post ( method , hmc , uri , uri_parms , body , logon_required , wait_for_completion ) : """Operation : Reorder User Patterns ."""
assert wait_for_completion is True # synchronous operation console_uri = '/api/console' try : console = hmc . lookup_by_uri ( console_uri ) except KeyError : raise InvalidResourceError ( method , uri ) check_required_fields ( method , uri , body , [ 'user-pattern-uris' ] ) new_order_uris = body [ 'user-pattern-...
def changeset ( python_data : LdapObject , d : dict ) -> Changeset : """Generate changes object for ldap object ."""
table : LdapObjectClass = type ( python_data ) fields = table . get_fields ( ) changes = Changeset ( fields , src = python_data , d = d ) return changes
def switch_delete_record_for_userid ( self , userid ) : """Remove userid switch record from switch table ."""
with get_network_conn ( ) as conn : conn . execute ( "DELETE FROM switch WHERE userid=?" , ( userid , ) ) LOG . debug ( "Switch record for user %s is removed from " "switch table" % userid )
def connect_button ( instance , prop , widget ) : """Connect a button with a callback method Parameters instance : object The class instance that the callback method is attached to prop : str The name of the callback method widget : QtWidget The Qt widget to connect . This should implement the ` ` cli...
widget . clicked . connect ( getattr ( instance , prop ) )
def _get_YYTfactor ( self , Y ) : """find a matrix L which satisfies LLT = YYT . Note that L may have fewer columns than Y ."""
N , D = Y . shape if ( N >= D ) : return Y . view ( np . ndarray ) else : return jitchol ( tdot ( Y ) )
def _read ( self , limit = 1000 ) : '''Return all the responses read'''
# It ' s important to know that it may return no responses or multiple # responses . It depends on how the buffering works out . First , read from # the socket for sock in self . socket ( ) : if sock is None : # Race condition . Connection has been closed . return [ ] try : packet = sock . recv ...
def visitInlineShapeExpression ( self , ctx : ShExDocParser . InlineShapeExpressionContext ) : """inlineShapeExpression : inlineShapeOr"""
expr_parser = ShexShapeExpressionParser ( self . context ) expr_parser . visitChildren ( ctx ) self . expression . valueExpr = expr_parser . expr
def _get_backend ( ) : """Returns the actual django cache object johnny is configured to use . This relies on the settings only ; the actual active cache can theoretically be changed at runtime ."""
enabled = [ n for n , c in sorted ( CACHES . items ( ) ) if c . get ( 'JOHNNY_CACHE' , False ) ] if len ( enabled ) > 1 : warn ( "Multiple caches configured for johnny-cache; using %s." % enabled [ 0 ] ) if enabled : return get_cache ( enabled [ 0 ] ) if CACHE_BACKEND : backend = get_cache ( CACHE_BACKEND )...
def _click_resolve_command ( root , parts ) : """Return the click command and the left over text given some vargs ."""
location = root incomplete = '' for part in parts : incomplete = part if not part [ 0 : 2 ] . isalnum ( ) : continue try : next_location = location . get_command ( click . Context ( location ) , part ) if next_location is not None : location = next_location in...
async def server_call_async ( method , server , loop : asyncio . AbstractEventLoop = asyncio . get_event_loop ( ) , timeout = DEFAULT_TIMEOUT , verify_ssl = True , ** parameters ) : """Makes an asynchronous call to an un - authenticated method on a server . : param method : The method name . : param server : Th...
if method is None : raise Exception ( "A method name must be specified" ) if server is None : raise Exception ( "A server (eg. my3.geotab.com) must be specified" ) parameters = api . process_parameters ( parameters ) return await _query ( server , method , parameters , timeout = timeout , verify_ssl = verify_ss...
def reset ( self , indices = None ) : """Reset the batch of environments . Args : indices : The batch indices of the environments to reset . Returns : Batch tensor of the new observations ."""
return tf . cond ( tf . cast ( tf . reduce_sum ( indices + 1 ) , tf . bool ) , lambda : self . _reset_non_empty ( indices ) , lambda : tf . cast ( 0 , self . observ_dtype ) )
def learn ( self , numEpochs , batchsize ) : """Train the classifier for a given number of epochs , with a given batchsize"""
for epoch in range ( numEpochs ) : print ( 'epoch %d' % epoch ) indexes = np . random . permutation ( self . trainsize ) for i in range ( 0 , self . trainsize , batchsize ) : x = Variable ( self . x_train [ indexes [ i : i + batchsize ] ] ) t = Variable ( self . y_train [ indexes [ i : i + b...
def checkout ( self , repo_dir , shared_dir , ** kwargs ) : """This function checks out code from a Git SCM server ."""
del kwargs args = [ ] for checkout_fn in _CHECKOUT_ARG_BUILDERS : args . extend ( checkout_fn ( shared_dir , repo_dir , self . _args ) ) return args
def read_hdf5_flag ( h5f , path = None , gpstype = LIGOTimeGPS ) : """Read a ` DataQualityFlag ` object from an HDF5 file or group ."""
# extract correct group dataset = _get_flag_group ( h5f , path ) # read dataset active = SegmentList . read ( dataset [ 'active' ] , format = 'hdf5' , gpstype = gpstype ) try : known = SegmentList . read ( dataset [ 'known' ] , format = 'hdf5' , gpstype = gpstype ) except KeyError as first_keyerror : try : ...
def wait ( self ) : """Return a deferred that will be fired when the event is fired ."""
d = defer . Deferred ( ) if self . _result is None : self . _waiters . append ( d ) else : self . _fire_deferred ( d ) return d
def get_current_user ( ) : """Return the current username for the logged in user : rtype : str"""
if pwd is None : return getpass . getuser ( ) else : try : return pwd . getpwuid ( os . getuid ( ) ) [ 0 ] except KeyError as error : LOGGER . error ( 'Could not get logged-in user: %s' , error )
def _get_config_value ( profile , config_name ) : '''Helper function that returns a profile ' s configuration value based on the supplied configuration name . profile The profile name that contains configuration information . config _ name The configuration item ' s name to use to return configuration val...
config = __salt__ [ 'config.option' ] ( profile ) if not config : raise CommandExecutionError ( 'Authentication information could not be found for the ' '\'{0}\' profile.' . format ( profile ) ) config_value = config . get ( config_name ) if config_value is None : raise CommandExecutionError ( 'The \'{0}\' para...
def iter_edges ( self , cached_content = None ) : """Iterate over the list of edges of a tree . Each egde is represented as a tuple of two elements , each containing the list of nodes separated by the edge ."""
if not cached_content : cached_content = self . get_cached_content ( ) all_leaves = cached_content [ self ] for n , side1 in six . iteritems ( cached_content ) : yield ( side1 , all_leaves - side1 )
def handle_add ( self , options ) : """Create a new user"""
username = options [ "username" ] passwd = options [ "passwd" ] if passwd is None : passwd = User . objects . make_random_password ( ) user = User . objects . create_user ( username , options [ "email" ] , passwd ) if options [ "staff" ] : user . is_staff = True if options [ "superuser" ] : user . is_superu...
def get_oauth_authcfg ( authcfg_id = AUTHCFG_ID ) : """Check if the given authcfg _ id ( or the default ) exists , and if it ' s valid OAuth2 , return the configuration or None"""
# Handle empty strings if not authcfg_id : authcfg_id = AUTHCFG_ID configs = auth_manager ( ) . availableAuthMethodConfigs ( ) if authcfg_id in configs and configs [ authcfg_id ] . isValid ( ) and configs [ authcfg_id ] . method ( ) == 'OAuth2' : return configs [ authcfg_id ] return None
def unlike ( self ) : """Unlike a clip ."""
r = requests . delete ( "https://kippt.com/api/clips/%s/likes" % ( self . id ) , headers = self . kippt . header ) return ( r . json ( ) )
def parse ( cls , uri ) : """Parse URI - string and return WURI object : param uri : string to parse : return : WURI"""
uri_components = urlsplit ( uri ) adapter_fn = lambda x : x if x is not None and ( isinstance ( x , str ) is False or len ( x ) ) > 0 else None return cls ( scheme = adapter_fn ( uri_components . scheme ) , username = adapter_fn ( uri_components . username ) , password = adapter_fn ( uri_components . password ) , hostn...
def setHorCrossPlotAutoRangeOn ( self , axisNumber ) : """Sets the horizontal cross - hair plot ' s auto - range on for the axis with number axisNumber . : param axisNumber : 0 ( X - axis ) , 1 ( Y - axis ) , 2 , ( Both X and Y axes ) ."""
setXYAxesAutoRangeOn ( self , self . xAxisRangeCti , self . horCrossPlotRangeCti , axisNumber )
def is_url ( value , ** kwargs ) : """Indicate whether ` ` value ` ` is a URL . . . note : : URL validation is . . . complicated . The methodology that we have adopted here is * generally * compliant with ` RFC 1738 < https : / / tools . ietf . org / html / rfc1738 > ` _ , ` RFC 6761 < https : / / tools ....
try : value = validators . url ( value , ** kwargs ) except SyntaxError as error : raise error except Exception : return False return True
def get_transition_time ( self ) : """Get the transition time in ms ."""
self . get_status ( ) try : self . transition_time = self . data [ 'ramp' ] except TypeError : self . transition_time = 0 return self . transition_time
def get_indic_syllabic_category_property ( value , is_bytes = False ) : """Get ` INDIC SYLLABIC CATEGORY ` property ."""
obj = unidata . ascii_indic_syllabic_category if is_bytes else unidata . unicode_indic_syllabic_category if value . startswith ( '^' ) : negated = value [ 1 : ] value = '^' + unidata . unicode_alias [ 'indicsyllabiccategory' ] . get ( negated , negated ) else : value = unidata . unicode_alias [ 'indicsyllab...
def _ReadAttributeValueDateTime ( self , attribute_values_data , record_offset , attribute_values_data_offset , attribute_value_offset ) : """Reads a date time attribute value . Args : attribute _ values _ data ( bytes ) : attribute values data . record _ offset ( int ) : offset of the record relative to the ...
if attribute_value_offset == 0 : return None data_type_map = self . _GetDataTypeMap ( 'keychain_date_time' ) file_offset = ( record_offset + attribute_values_data_offset + attribute_value_offset ) attribute_value_offset -= attribute_values_data_offset + 1 attribute_value_data = attribute_values_data [ attribute_val...
def load_models ( context : mx . context . Context , max_input_len : Optional [ int ] , beam_size : int , batch_size : int , model_folders : List [ str ] , checkpoints : Optional [ List [ int ] ] = None , softmax_temperature : Optional [ float ] = None , max_output_length_num_stds : int = C . DEFAULT_NUM_STD_MAX_OUTPUT...
logger . info ( "Loading %d model(s) from %s ..." , len ( model_folders ) , model_folders ) load_time_start = time . time ( ) models = [ ] # type : List [ InferenceModel ] source_vocabs = [ ] # type : List [ List [ vocab . Vocab ] ] target_vocabs = [ ] # type : List [ vocab . Vocab ] if checkpoints is None : checkp...
def segment ( self , document ) : """document : list [ str ] return list [ int ] , i - th element denotes whether exists a boundary right before paragraph i ( 0 indexed )"""
assert ( len ( document ) > 0 and len ( [ d for d in document if not isinstance ( d , str ) ] ) == 0 ) if len ( document ) < 3 : return [ 1 ] + [ 0 for _ in range ( len ( document ) - 1 ) ] # step 1 , preprocessing n = len ( document ) self . window = min ( self . window , n ) cnts = [ Counter ( self . tokenizer . ...
def set_source_tags ( self , id , ** kwargs ) : # noqa : E501 """Set all tags associated with a specific source # noqa : E501 # noqa : E501 This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > thread = api . set _ source _ tags...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . set_source_tags_with_http_info ( id , ** kwargs ) # noqa : E501 else : ( data ) = self . set_source_tags_with_http_info ( id , ** kwargs ) # noqa : E501 return data
def run_initial_export ( self , events ) : """Runs the initial export . This process is expected to take a very long time . : param events : iterable of all events in this indico instance"""
if self . uploader is None : # pragma : no cover raise NotImplementedError uploader = self . uploader ( self ) uploader . run_initial ( events )
def inject ( ** params ) : """A Logbook processor to inject arbitrary information into log records . Simply pass in keyword arguments and use as a context manager : > > > with inject ( identifier = str ( uuid . uuid4 ( ) ) ) . applicationbound ( ) : . . . logger . debug ( ' Something happened ' )"""
def callback ( log_record ) : log_record . extra . update ( params ) return logbook . Processor ( callback )
def handle_event ( self , event ) : """Handle event callback for active listeners . It is not called for passive listeners . After calling : py : func : ` handle _ event ` on all active listeners and having received acknowledgement from all passive listeners via : py : func : ` IEventSource . event _ processe...
if not isinstance ( event , IEvent ) : raise TypeError ( "event can only be an instance of type IEvent" ) self . _call ( "handleEvent" , in_p = [ event ] )
def read_csv_to_html_list ( csvFile ) : """reads a CSV file and converts it to a HTML List"""
txt = '' with open ( csvFile ) as csv_file : for row in csv . reader ( csv_file , delimiter = ',' ) : txt += '<div id="table_row">' for col in row : txt += " " try : txt += col except Exception : txt += 'Error' txt += " ...
def reset ( self ) : """override reset behavior"""
if getattr ( self , 'num' , None ) is None : self . num_inst = 0 self . sum_metric = 0.0 else : self . num_inst = [ 0 ] * self . num self . sum_metric = [ 0.0 ] * self . num
def unregisterWorker ( self , name ) : """Unregister the Worker registered under the given name . Make sure that the given Worker is properly stopped , or that a reference is kept in another place . Once unregistered , this class will not keep any other references to the Worker . Parameters name : string ...
if not name in self . worker_list : self . logger . error ( "Worker {0} is not registered!" . format ( name ) ) raise Exception ( "Worker {0} is not registered!" . format ( name ) ) del self . worker_list [ name ] self . logger . debug ( "Unregistered worker {0}" . format ( name ) )
def get_mapper_by_content_type ( self , content_type ) : """Returs mapper based on the content type ."""
content_type = util . strip_charset ( content_type ) return self . _get_mapper ( content_type )
def _get_persistent_mpe_dir ( self ) : """get persistent storage for mpe"""
mpe_address = self . get_mpe_address ( ) . lower ( ) registry_address = self . get_registry_address ( ) . lower ( ) return Path . home ( ) . joinpath ( ".snet" , "mpe_client" , "%s_%s" % ( mpe_address , registry_address ) )
def add_substitution ( self , short , medium , long , module ) : """Add the given substitutions both as a ` short2long ` and a ` medium2long ` mapping . Assume ` variable1 ` is defined in the hydpy module ` module1 ` and the short and medium descriptions are ` var1 ` and ` mod1 . var1 ` : > > > import types...
name = module . __name__ if 'builtin' in name : self . _short2long [ short ] = long . split ( '~' ) [ 0 ] + long . split ( '.' ) [ - 1 ] else : if ( 'hydpy' in name ) and ( short not in self . _blacklist ) : if short in self . _short2long : if self . _short2long [ short ] != long : ...
def add_or_return_host ( self , host ) : """Returns a tuple ( host , new ) , where ` ` host ` ` is a Host instance , and ` ` new ` ` is a bool indicating whether the host was newly added ."""
with self . _hosts_lock : try : return self . _hosts [ host . endpoint ] , False except KeyError : self . _hosts [ host . endpoint ] = host return host , True
def activity_show ( self , activity_id , ** kwargs ) : "https : / / developer . zendesk . com / rest _ api / docs / core / activity _ stream # show - activity"
api_path = "/api/v2/activities/{activity_id}.json" api_path = api_path . format ( activity_id = activity_id ) return self . call ( api_path , ** kwargs )