signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def describe_splits_ex ( self , cfName , start_token , end_token , keys_per_split ) : """Parameters : - cfName - start _ token - end _ token - keys _ per _ split"""
self . _seqid += 1 d = self . _reqs [ self . _seqid ] = defer . Deferred ( ) self . send_describe_splits_ex ( cfName , start_token , end_token , keys_per_split ) return d
async def pixy_init ( self , max_blocks = 5 , cb = None , cb_type = None ) : """Initialize Pixy and enable Pixy block reporting . This is a FirmataPlusRB feature . : param cb : callback function to report Pixy blocks : param cb _ type : Constants . CB _ TYPE _ DIRECT = direct call or Constants . CB _ TYPE _...
if cb : self . digital_pins [ PrivateConstants . PIN_PIXY_MOSI ] . cb = cb # Pixy uses SPI . Pin 11 is MOSI . if cb_type : self . digital_pins [ PrivateConstants . PIN_PIXY_MOSI ] . cb_type = cb_type data = [ PrivateConstants . PIXY_INIT , max_blocks & 0x7f ] await self . _send_sysex ( PrivateConstants . PI...
def get_async_pillar ( opts , grains , minion_id , saltenv = None , ext = None , funcs = None , pillar_override = None , pillarenv = None , extra_minion_data = None ) : '''Return the correct pillar driver based on the file _ client option'''
file_client = opts [ 'file_client' ] if opts . get ( 'master_type' ) == 'disable' and file_client == 'remote' : file_client = 'local' ptype = { 'remote' : AsyncRemotePillar , 'local' : AsyncPillar , } . get ( file_client , AsyncPillar ) return ptype ( opts , grains , minion_id , saltenv , ext , functions = funcs , ...
def update ( self , data = None , ** kwargs ) : """Update the record right away . : param data : dictionary of changes : param kwargs : possibly a list of keyword args to change"""
if data is None : data = { } data . update ( kwargs ) return self . model . write ( [ self . id ] , data )
def create_double ( self , value : float ) -> Double : """Creates a new : class : ` ConstantDouble ` , adding it to the pool and returning it . : param value : The value of the new Double ."""
self . append ( ( 6 , value ) ) self . append ( None ) return self . get ( self . raw_count - 2 )
def transform ( self , X , y = None ) : ''': param X : list of dict which contains metabolic measurements .'''
return Parallel ( n_jobs = self . n_jobs ) ( delayed ( self . _transform ) ( x ) for x in X )
def load_wavefront ( file_obj , resolver = None , ** kwargs ) : """Loads an ascii Wavefront OBJ file _ obj into kwargs for the Trimesh constructor . Vertices with the same position but different normals or uvs are split into multiple vertices . Colors are discarded . Parameters file _ obj : file object ...
# make sure text is UTF - 8 with only \ n newlines text = file_obj . read ( ) if hasattr ( text , 'decode' ) : text = text . decode ( 'utf-8' ) text = text . replace ( '\r\n' , '\n' ) . replace ( '\r' , '\n' ) + ' \n' meshes = [ ] def append_mesh ( ) : # append kwargs for a Trimesh constructor # to our list of mesh...
def set_column_count ( self , count ) : """Sets the table column count . Args : count ( int ) : column of rows"""
current_row_count = self . row_count ( ) current_column_count = self . column_count ( ) if count > current_column_count : cl = TableEditableItem if self . _editable else TableItem for r_key in self . children . keys ( ) : row = self . children [ r_key ] for i in range ( current_column_count , co...
def track_class ( self , cls , name = None , resolution_level = 0 , keep = False , trace = False ) : """Track all objects of the class ` cls ` . Objects of that type that already exist are * not * tracked . If ` track _ class ` is called for a class already tracked , the tracking parameters are modified . Insta...
if not isclass ( cls ) : raise TypeError ( "only class objects can be tracked" ) if name is None : name = cls . __module__ + '.' + cls . __name__ if self . _is_tracked ( cls ) : self . _track_modify ( cls , name , resolution_level , keep , trace ) else : self . _inject_constructor ( cls , self . _tracke...
def return_rri ( self , begsam , endsam ) : """Return raw , irregularly - timed RRI ."""
interval = endsam - begsam dat = empty ( interval ) k = 0 with open ( self . filename , 'rt' ) as f : [ next ( f ) for x in range ( 12 ) ] for j , datum in enumerate ( f ) : if begsam <= j < endsam : dat [ k ] = float64 ( datum [ : datum . index ( '\t' ) ] ) k += 1 if...
def open ( self , pchPath , mode , unElementSize , unElements ) : """opens an existing or creates a new IOBuffer of unSize bytes"""
fn = self . function_table . open pulBuffer = IOBufferHandle_t ( ) result = fn ( pchPath , mode , unElementSize , unElements , byref ( pulBuffer ) ) return result , pulBuffer
def versions ( self ) : """Property for accessing : class : ` VersionManager ` instance , which is used to get server info . : rtype : yagocd . resources . version . VersionManager"""
if self . _version_manager is None : self . _version_manager = VersionManager ( session = self . _session ) return self . _version_manager
def BSearchRound ( a , x , lo = 0 , hi = None ) : """Returns index of a that is closest to x . Arguments : a - - ordered numeric sequence x - - element to search within a lo - - lowest index to consider in search * hi - - highest index to consider in search * * bisect . bisect _ left capability that we ...
if len ( a ) == 0 : return - 1 hi = hi if hi is not None else len ( a ) pos = bisect_left ( a , x , lo , hi ) if pos >= hi : return hi - 1 elif a [ pos ] == x or pos == lo : return pos else : return pos - 1 if x - a [ pos - 1 ] <= a [ pos ] - x else pos
def read ( self , file_path = None ) : """Read the contents of a file . : param filename : ( str ) path to a file in the local file system : return : ( str ) contents of the file , or ( False ) if not found / not file"""
if not file_path : file_path = self . file_path # abort if the file path does not exist if not os . path . exists ( file_path ) : self . oops ( "Sorry, but {} does not exist" . format ( file_path ) ) return False # abort if the file path is not a file if not os . path . isfile ( file_path ) : self . oop...
def setCurrentPage ( self , pageno ) : """Sets the current page for this widget to the inputed page . : param pageno | < int >"""
if ( pageno == self . _currentPage ) : return if ( pageno <= 0 ) : pageno = 1 self . _currentPage = pageno self . _prevButton . setEnabled ( pageno > 1 ) self . _nextButton . setEnabled ( pageno < self . pageCount ( ) ) self . _pagesSpinner . blockSignals ( True ) self . _pagesSpinner . setValue ( pageno ) self...
def cli ( env , identifier ) : """Retrieve credentials used for generating an AWS signature . Max of 2."""
mgr = SoftLayer . ObjectStorageManager ( env . client ) credential_list = mgr . list_credential ( identifier ) table = formatting . Table ( [ 'id' , 'password' , 'username' , 'type_name' ] ) for credential in credential_list : table . add_row ( [ credential [ 'id' ] , credential [ 'password' ] , credential [ 'usern...
def getL4PredictedActiveCells ( self ) : """Returns the predicted active cells in each column in L4."""
predictedActive = [ ] for i in xrange ( self . numColumns ) : region = self . network . regions [ "L4Column_" + str ( i ) ] predictedActive . append ( region . getOutputData ( "predictedActiveCells" ) . nonzero ( ) [ 0 ] ) return predictedActive
def _se_all ( self ) : """Standard errors ( SE ) for all parameters , including the intercept ."""
x = np . atleast_2d ( self . x ) err = np . atleast_1d ( self . ms_err ) se = np . sqrt ( np . diagonal ( np . linalg . inv ( x . T @ x ) ) * err [ : , None ] ) return np . squeeze ( se )
def snmp_server_engineID_drop_engineID_local ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) snmp_server = ET . SubElement ( config , "snmp-server" , xmlns = "urn:brocade.com:mgmt:brocade-snmp" ) engineID_drop = ET . SubElement ( snmp_server , "engineID-drop" ) engineID = ET . SubElement ( engineID_drop , "engineID" ) local = ET . SubElement ( engineID , "local" ) local . tex...
def guess_decode_from_terminal ( text , term ) : """Decode * text * coming from terminal * term * . First try the terminal encoding , if given . Then try UTF - 8 . Then try the preferred locale encoding . Fall back to latin - 1 , which always works ."""
if getattr ( term , 'encoding' , None ) : try : text = text . decode ( term . encoding ) except UnicodeDecodeError : pass else : return text , term . encoding return guess_decode ( text )
def _decode_bytes ( self , bytestring ) : """Internal method used to convert the utf - 8 encoded bytestring into unicode . If the conversion fails , the socket will be closed ."""
if not bytestring : return u'' try : return bytestring . decode ( 'utf-8' ) except UnicodeDecodeError : self . close ( 1007 ) raise
def plain ( self ) : """Get a string representation of this XML document . @ return : A I { plain } string . @ rtype : basestring"""
s = [ ] s . append ( self . DECL ) root = self . root ( ) if root is not None : s . append ( root . plain ( ) ) return '' . join ( s )
def unmount_volume_groups ( self ) : """Unmounts all volume groups and related loopback devices as identified by : func : ` find _ volume _ groups `"""
for vgname , pvname in self . find_volume_groups ( ) : _util . check_output_ ( [ 'lvchange' , '-a' , 'n' , vgname ] ) _util . check_output_ ( [ 'losetup' , '-d' , pvname ] )
def exportTiles ( self , levels , exportBy = "LevelID" , tilePackage = False , exportExtent = "DEFAULT" , optimizeTilesForSize = True , compressionQuality = 0 , areaOfInterest = None , async = False ) : """The exportTiles operation is performed as an asynchronous task and allows client applications to download ma...
params = { "f" : "json" , "tilePackage" : tilePackage , "exportExtent" : exportExtent , "optimizeTilesForSize" : optimizeTilesForSize , "compressionQuality" : compressionQuality , "exportBy" : exportBy , "levels" : levels } url = self . _url + "/exportTiles" if isinstance ( areaOfInterest , Polygon ) : geom = areaO...
def _recv ( self ) : """Implementation of the receive thread . Waits for data to arrive on the socket , then passes the data through the defined receive framer and sends it on to the application ."""
# Outer loop : receive some data while True : # Wait until we can go self . _recv_lock . release ( ) gevent . sleep ( ) # Yield to another thread self . _recv_lock . acquire ( ) recv_buf = self . _sock . recv ( self . recv_bufsize ) # If it ' s empty , the peer closed the other end if not re...
def list_sensors ( parent_class , sensor_items , filter , strategy , status , use_python_identifiers , tuple , refresh ) : """Helper for implementing : meth : ` katcp . resource . KATCPResource . list _ sensors ` Parameters sensor _ items : tuple of sensor - item tuples As would be returned the items ( ) meth...
filter_re = re . compile ( filter ) found_sensors = [ ] none_strat = resource . normalize_strategy_parameters ( 'none' ) sensor_dict = dict ( sensor_items ) for sensor_identifier in sorted ( sensor_dict . keys ( ) ) : sensor_obj = sensor_dict [ sensor_identifier ] search_name = ( sensor_identifier if use_python...
def _set_process_restart ( self , v , load = False ) : """Setter method for process _ restart , mapped from YANG variable / ha / process _ restart ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ process _ restart is considered as a private method . Backe...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = process_restart . process_restart , is_container = 'container' , presence = False , yang_name = "process-restart" , rest_name = "process-restart" , parent = self , path_helper = self . _path_helper , extmethods = self . _extm...
def get_cb_plot ( cb , plot = None ) : """Finds the subplot with the corresponding stream ."""
plot = plot or cb . plot if isinstance ( plot , GeoOverlayPlot ) : plots = [ get_cb_plot ( cb , p ) for p in plot . subplots . values ( ) ] plots = [ p for p in plots if any ( s in cb . streams and getattr ( s , '_triggering' , False ) for s in p . streams ) ] if plots : plot = plots [ 0 ] return pl...
def _check_str_value ( x ) : """If string has a space , wrap it in double quotes and remove / escape illegal characters"""
if isinstance ( x , str ) : # remove commas , and single quotation marks since loadarff cannot deal with it x = x . replace ( "," , "." ) . replace ( chr ( 0x2018 ) , "'" ) . replace ( chr ( 0x2019 ) , "'" ) # put string in double quotes if " " in x : if x [ 0 ] in ( '"' , "'" ) : x = x ...
def preprocess_D_segs ( self , generative_model , genomic_data ) : """Process P ( delDl , delDr | D ) into Pi arrays . Sets the attributes PD _ nt _ pos _ vec , PD _ 2nd _ nt _ pos _ per _ aa _ vec , min _ delDl _ given _ DdelDr , max _ delDl _ given _ DdelDr , and zeroD _ given _ D . Parameters generative ...
cutD_genomic_CDR3_segs = genomic_data . cutD_genomic_CDR3_segs nt2num = { 'A' : 0 , 'C' : 1 , 'G' : 2 , 'T' : 3 } num_dell_pos , num_delr_pos , num_D_genes = generative_model . PdelDldelDr_given_D . shape # These arrays only include the nt identity information , not the PdelDldelDr _ given _ D info PD_nt_pos_vec = [ [ ...
def response_builder ( self , response ) : '''Try to return a pretty formatted response object'''
try : r = response . json ( ) result = r [ 'query' ] [ 'results' ] response = { 'num_result' : r [ 'query' ] [ 'count' ] , 'result' : result } except ( Exception , ) as e : print ( e ) return response . content return response
def status ( self , job_ids ) : '''Get the status of a list of jobs identified by their ids . Args : - job _ ids ( List of ids ) : List of identifiers for the jobs Returns : - List of status codes .'''
logging . debug ( "Checking status of : {0}" . format ( job_ids ) ) for job_id in self . resources : poll_code = self . resources [ job_id ] [ 'proc' ] . poll ( ) if self . resources [ job_id ] [ 'status' ] in [ 'COMPLETED' , 'FAILED' ] : continue if poll_code is None : self . resources [ jo...
def parse_line ( self , line : str ) -> None : """Updates the dictionary with a single header line . > > > h = HTTPHeaders ( ) > > > h . parse _ line ( " Content - Type : text / html " ) > > > h . get ( ' content - type ' ) ' text / html '"""
if line [ 0 ] . isspace ( ) : # continuation of a multi - line header if self . _last_key is None : raise HTTPInputError ( "first header line cannot start with whitespace" ) new_part = " " + line . lstrip ( ) self . _as_list [ self . _last_key ] [ - 1 ] += new_part self . _dict [ self . _last_ke...
def delete_collection_certificate_signing_request ( self , ** kwargs ) : # noqa : E501 """delete _ collection _ certificate _ signing _ request # noqa : E501 delete collection of CertificateSigningRequest # noqa : E501 This method makes a synchronous HTTP request by default . To make an asynchronous HTTP requ...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . delete_collection_certificate_signing_request_with_http_info ( ** kwargs ) # noqa : E501 else : ( data ) = self . delete_collection_certificate_signing_request_with_http_info ( ** kwargs ) # noqa : E501 return...
def _Close ( self ) : """Closes the file - like object . If the file - like object was passed in the init function the file object - based file - like object does not control the file - like object and should not actually close it ."""
if not self . _file_object_set_in_init : try : # TODO : fix close being called for the same object multiple times . self . _file_object . close ( ) except IOError : pass self . _file_object = None
def Guardar ( self , tipo_doc , nro_doc , denominacion , cat_iva , direccion , email , imp_ganancias = 'NI' , imp_iva = 'NI' , monotributo = 'NI' , integrante_soc = 'N' , empleador = 'N' ) : "Agregar o actualizar los datos del cliente"
if self . Buscar ( nro_doc , tipo_doc ) : sql = ( "UPDATE padron SET denominacion=?, cat_iva=?, email=?, " "imp_ganancias=?, imp_iva=?, monotributo=?, " "integrante_soc=?, empleador=? " "WHERE tipo_doc=? AND nro_doc=?" ) params = [ denominacion , cat_iva , email , imp_ganancias , imp_iva , monotributo , integra...
def _pressed ( self , evt ) : """Clicked somewhere in the calendar ."""
x , y , widget = evt . x , evt . y , evt . widget item = widget . identify_row ( y ) column = widget . identify_column ( x ) if not column or not item in self . _items : # clicked in the weekdays row or just outside the columns return item_values = widget . item ( item ) [ 'values' ] if not len ( item_values ) : # ...
def rpc_get_subdomain_ops_at_txid ( self , txid , ** con_info ) : """Return the list of subdomain operations accepted within a given txid . Return { ' status ' : True , ' subdomain _ ops ' : [ { . . . } ] } on success Return { ' error ' : . . . } on error"""
if not check_string ( txid , min_length = 64 , max_length = 64 , pattern = '^[0-9a-fA-F]{64}$' ) : return { 'error' : 'Not a valid txid' , 'http_status' : 400 } subdomain_ops = get_subdomain_ops_at_txid ( txid ) return self . success_response ( { 'subdomain_ops' : subdomain_ops } )
def _get_calibration_for_mchits ( hits , lookup ) : """Append the position , direction and t0 columns and add t0 to time"""
n_hits = len ( hits ) cal = np . empty ( ( n_hits , 9 ) ) for i in range ( n_hits ) : cal [ i ] = lookup [ hits [ 'pmt_id' ] [ i ] ] dir_x = cal [ : , 3 ] dir_y = cal [ : , 4 ] dir_z = cal [ : , 5 ] du = cal [ : , 7 ] floor = cal [ : , 8 ] pos_x = cal [ : , 0 ] pos_y = cal [ : , 1 ] pos_z = cal [ : , 2 ] t0 = cal [...
async def create_playlist ( self , name , * songs ) : '''create a new playlist | coro | Parameters name : str name of new playlist songs : array _ like list of song ids to add to playlist'''
data = { 'Name' : name } ids = [ i . id for i in ( await self . process ( songs ) ) ] if ids : data [ 'Ids' ] = ',' . join ( ids ) # TODO - return playlist not status return await self . connector . post ( '/Playlists' , data = data , pass_uid = True , remote = False )
def update_persistent_boot ( self , devices = [ ] , persistent = False ) : """Changes the persistent boot device order in BIOS boot mode for host Note : It uses first boot device from the devices and ignores rest . : param devices : ordered list of boot devices : param persistent : Boolean flag to indicate if...
device = PERSISTENT_BOOT_DEVICE_MAP . get ( devices [ 0 ] . upper ( ) ) if device == sushy . BOOT_SOURCE_TARGET_UEFI_TARGET : try : uefi_devices = self . uefi_target_override_devices iscsi_device = None for uefi_device in uefi_devices : if uefi_device is not None and 'iSCSI' in u...
def is_nonterminal ( self , symbol : str ) -> bool : """Determines whether an input symbol is a valid non - terminal in the grammar ."""
nonterminal_productions = self . get_nonterminal_productions ( ) return symbol in nonterminal_productions
def get_networks ( parent_ref , network_names = None , get_all_networks = False ) : '''Returns networks of standard switches . The parent object can be a datacenter . parent _ ref The parent object reference . A datacenter object . network _ names The name of the standard switch networks . Default is None...
if not isinstance ( parent_ref , vim . Datacenter ) : raise salt . exceptions . ArgumentValueError ( 'Parent has to be a datacenter.' ) parent_name = get_managed_object_name ( parent_ref ) log . trace ( 'Retrieving network from %s \'%s\', network_names=\'%s\', ' 'get_all_networks=%s' , type ( parent_ref ) . __name_...
def upgrade_bootstrap ( directory = '.' , onlyif = None , unless = None , runas = None , env = ( ) , offline = False , buildout_ver = None ) : '''Upgrade current bootstrap . py with the last released one . Indeed , when we first run a buildout , a common source of problem is to have a locally stale bootstrap , ...
if buildout_ver : booturl = _URL_VERSIONS [ buildout_ver ] else : buildout_ver = _get_buildout_ver ( directory ) booturl = _get_bootstrap_url ( directory ) LOG . debug ( 'Using {0}' . format ( booturl ) ) # pylint : disable = str - format - in - logging # try to download an up - to - date bootstrap # set de...
def _get_longest_hit_at_qry_end ( self , nucmer_hits ) : '''Input : list of nucmer hits to the same query . Returns the longest hit to the end of the query , or None if there is no such hit'''
hits_at_end = [ hit for hit in nucmer_hits if self . _is_at_qry_end ( hit ) ] return self . _get_longest_hit_by_ref_length ( hits_at_end )
def log ( self , revrange = None , limit = None , firstparent = False , merges = None , path = None , follow = False ) : """Get commit logs : param revrange : Either a single revision or a range of revisions as a 2 - element list or tuple . : param int limit : Limit the number of log entries . : param bool ...
raise NotImplementedError
def prepare_patchset ( project , patchset , binaries , ips , urls ) : """Create black / white lists and default / project waivers and iterates over patchset file"""
# Get Various Lists / Project Waivers lists = get_lists . GetLists ( ) # Get file name black list and project waivers file_audit_list , file_audit_project_list = lists . file_audit_list ( project ) # Get file content black list and project waivers flag_list , ignore_list = lists . file_content_list ( project ) # Get UR...
def mmap_move ( fileobj , dest , src , count ) : """Mmaps the file object if possible and moves ' count ' data from ' src ' to ' dest ' . All data has to be inside the file size ( enlarging the file through this function isn ' t possible ) Will adjust the file offset . Args : fileobj ( fileobj ) dest ( ...
assert mmap is not None , "no mmap support" if dest < 0 or src < 0 or count < 0 : raise ValueError ( "Invalid parameters" ) try : fileno = fileobj . fileno ( ) except ( AttributeError , IOError ) : raise mmap . error ( "File object does not expose/support a file descriptor" ) fileobj . seek ( 0 , 2 ) filesi...
def describe_keypairs ( self , * keypair_names ) : """Returns information about key pairs available ."""
keypairs = { } for index , keypair_name in enumerate ( keypair_names ) : keypairs [ "KeyName.%d" % ( index + 1 ) ] = keypair_name query = self . query_factory ( action = "DescribeKeyPairs" , creds = self . creds , endpoint = self . endpoint , other_params = keypairs ) d = query . submit ( ) return d . addCallback (...
def set_display_name ( self , display_name ) : """Sets a display name . A display name is required and if not set , will be set by the provider . arg : display _ name ( string ) : the new display name raise : InvalidArgument - ` ` display _ name ` ` is invalid raise : NoAccess - ` ` Metadata . isReadonly ...
self . _my_map [ 'displayName' ] = self . _get_display_text ( display_name , self . get_display_name_metadata ( ) )
def get_recipe ( self , recipe_name ) : """Get a recipe by name . Args : recipe _ name ( str ) : The name of the recipe to fetch . Can be either the yaml file name or the name of the recipe ."""
if recipe_name . endswith ( '.yaml' ) : recipe = self . _recipes . get ( RecipeObject . FromFile ( recipe_name , self . _recipe_actions , self . _recipe_resources ) . name ) else : recipe = self . _recipes . get ( recipe_name ) if recipe is None : raise RecipeNotFoundError ( "Could not find recipe" , recipe...
def sg_seek_streamer ( self , index , force , value ) : """Ackowledge a streamer ."""
force = bool ( force ) err = self . sensor_graph . acknowledge_streamer ( index , value , force ) return [ err ]
def suspend ( self ) : """Suspends execution on all threads of the process . @ raise WindowsError : On error an exception is raised ."""
self . scan_threads ( ) # force refresh the snapshot suspended = list ( ) try : for aThread in self . iter_threads ( ) : aThread . suspend ( ) suspended . append ( aThread ) except Exception : for aThread in suspended : try : aThread . resume ( ) except Exception : ...
def SavePrivateKey ( self , private_key ) : """Store the new private key on disk ."""
self . private_key = private_key config . CONFIG . Set ( "Client.private_key" , self . private_key . SerializeToString ( ) ) config . CONFIG . Write ( )
def get_file ( self ) : """Load data into a file and return file path . : return : path to file as string"""
content = self . _load ( ) if not content : return None filename = "temporary_file.bin" with open ( filename , "wb" ) as file_name : file_name . write ( content ) return filename
def get_channel_comment ( self , name = None , group = None , index = None ) : """Gets channel comment . Channel can be specified in two ways : * using the first positional argument * name * * if there are multiple occurances for this channel then the * group * and * index * arguments can be used to select ...
gp_nr , ch_nr = self . _validate_channel_selection ( name , group , index ) grp = self . groups [ gp_nr ] if grp . data_location == v23c . LOCATION_ORIGINAL_FILE : stream = self . _file else : stream = self . _tempfile channel = grp . channels [ ch_nr ] return channel . comment
def allows_simple_recursion ( self ) : """Check recursion level and extern status ."""
rec_level = self . aggregate . config [ "recursionlevel" ] if rec_level >= 0 and self . recursion_level >= rec_level : log . debug ( LOG_CHECK , "... no, maximum recursion level reached." ) return False if self . extern [ 0 ] : log . debug ( LOG_CHECK , "... no, extern." ) return False return True
def _process_gradient_args ( f , kwargs ) : """Handle common processing of arguments for gradient and gradient - like functions ."""
axes = kwargs . get ( 'axes' , range ( f . ndim ) ) def _check_length ( positions ) : if 'axes' in kwargs and len ( positions ) < len ( axes ) : raise ValueError ( 'Length of "coordinates" or "deltas" cannot be less than that ' 'of "axes".' ) elif 'axes' not in kwargs and len ( positions ) != len ( axes...
def from_array3D ( filename , data , iline = 189 , xline = 193 , format = SegySampleFormat . IBM_FLOAT_4_BYTE , dt = 4000 , delrt = 0 ) : """Create a new SEGY file from a 3D array Create an structured SEGY file with defaulted headers from a 3 - dimensional array . The file is inline - sorted . ilines , xlines a...
data = np . asarray ( data ) dimensions = len ( data . shape ) if dimensions != 3 : problem = "Expected 3 dimensions, {} was given" . format ( dimensions ) raise ValueError ( problem ) from_array ( filename , data , iline = iline , xline = xline , format = format , dt = dt , delrt = delrt )
def create_user ( backend , details , response , uid , username , user = None , * args , ** kwargs ) : """Creates user . Depends on get _ username pipeline ."""
if user : return { 'user' : user } if not username : return None email = details . get ( 'email' ) original_email = None # email is required if not email : message = _ ( """your social account needs to have a verified email address in order to proceed.""" ) raise AuthFailed ( backend , message ) # Avoid...
def display_completions_like_readline ( event ) : """Key binding handler for readline - style tab completion . This is meant to be as similar as possible to the way how readline displays completions . Generate the completions immediately ( blocking ) and display them above the prompt in columns . Usage : ...
# Request completions . b = event . current_buffer if b . completer is None : return complete_event = CompleteEvent ( completion_requested = True ) completions = list ( b . completer . get_completions ( b . document , complete_event ) ) # Calculate the common suffix . common_suffix = get_common_complete_suffix ( b ...
def get_story ( self , id ) : """Fetches a single story by id . get / v1 / public / stories / { storyId } : param id : ID of Story : type params : int : returns : StoryDataWrapper > > > m = Marvel ( public _ key , private _ key ) > > > response = m . get _ story ( 29) > > > print response . data . res...
url = "%s/%s" % ( Story . resource_url ( ) , id ) response = json . loads ( self . _call ( url ) . text ) return StoryDataWrapper ( self , response )
def format_output ( func ) : return func """Format output ."""
@ wraps ( func ) def wrapper ( * args , ** kwargs ) : try : response = func ( * args , ** kwargs ) except Exception as error : print ( colored ( error , 'red' ) , file = sys . stderr ) sys . exit ( 1 ) else : print ( response ) sys . exit ( 0 ) return wrapper
def get_index_labels ( self , targets ) : """Get the labels ( known target / not ) mapped to indices . : param targets : List of known targets : return : Dictionary of index - label mappings"""
target_ind = self . graph . vs . select ( name_in = targets ) . indices rest_ind = self . graph . vs . select ( name_notin = targets ) . indices label_mappings = { i : 1 for i in target_ind } label_mappings . update ( { i : 0 for i in rest_ind } ) return label_mappings
def backend_from_fname ( name ) : """Determine backend module object from a file name ."""
ext = splitext ( name ) [ 1 ] try : mime = EXTS_TO_MIMETYPES [ ext ] except KeyError : try : f = open ( name , 'rb' ) except IOError as e : # The file may not exist , we are being asked to determine it ' s type # from it ' s name . Other errors are unexpected . if e . errno != errno . EN...
def create ( self , data , ** kwargs ) : """Create a new object . Args : data ( dict ) : parameters to send to the server to create the resource * * kwargs : Extra options to send to the server ( e . g . sudo ) Returns : RESTObject : a new instance of the managed object class built with the data sent ...
self . _check_missing_create_attrs ( data ) files = { } # We get the attributes that need some special transformation types = getattr ( self , '_types' , { } ) if types : # Duplicate data to avoid messing with what the user sent us data = data . copy ( ) for attr_name , type_cls in types . items ( ) : i...
def getPrivilegeForRole ( self , rolename ) : """Returns the privilege associated with a role . Input : rolename - name of the role Output : JSON Messages"""
params = { "f" : "json" , "rolename" : rolename } pURL = self . _url + "/roles/getPrivilege" return self . _post ( url = pURL , param_dict = params , securityHandler = self . _securityHandler , proxy_url = self . _proxy_url , proxy_port = self . _proxy_port )
def client_for ( service , service_module , thrift_service_name = None ) : """Build a synchronous client class for the given Thrift service . The generated class accepts a TChannelSyncClient and an optional hostport as initialization arguments . Given ` ` CommentService ` ` defined in ` ` comment . thrift ` `...
assert service_module , 'service_module is required' service = service or '' # may be blank for non - hyperbahn use cases if not thrift_service_name : thrift_service_name = service_module . __name__ . rsplit ( '.' , 1 ) [ - 1 ] method_names = get_service_methods ( service_module . Iface ) def init ( self , tchannel...
def hmsStrToDeg ( ra ) : """Convert a string representation of RA into a float in degrees ."""
hour , min , sec = ra . split ( ':' ) ra_deg = hmsToDeg ( int ( hour ) , int ( min ) , float ( sec ) ) return ra_deg
def get_vault_query_session ( self , proxy ) : """Gets the OsidSession associated with the vault query service . arg : proxy ( osid . proxy . Proxy ) : a proxy return : ( osid . authorization . VaultQuerySession ) - a ` ` VaultQuerySession ` ` raise : NullArgument - ` ` proxy ` ` is ` ` null ` ` raise : O...
if not self . supports_vault_query ( ) : raise errors . Unimplemented ( ) # pylint : disable = no - member return sessions . VaultQuerySession ( proxy = proxy , runtime = self . _runtime )
def create_key ( file_ ) : """Create a key and save it into ` ` file _ ` ` . Note that ` ` file ` ` must be opened in binary mode ."""
pkey = crypto . PKey ( ) pkey . generate_key ( crypto . TYPE_RSA , 2048 ) file_ . write ( crypto . dump_privatekey ( crypto . FILETYPE_PEM , pkey ) ) file_ . flush ( )
def summarycanvas ( args ) : """% prog summarycanvas output . vcf . gz Generate tag counts ( GAIN / LOSS / REF / LOH ) of segments in Canvas output ."""
p = OptionParser ( summarycanvas . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) < 1 : sys . exit ( not p . print_help ( ) ) for vcffile in args : counter = get_gain_loss_summary ( vcffile ) pf = op . basename ( vcffile ) . split ( "." ) [ 0 ] print ( pf + " " + " " . join ( "{}:{}" . ...
def set_row_height ( self , n = 0 , height = 18 ) : """Sets the n ' th row height in pixels ."""
self . _widget . setRowHeight ( n , height ) return self
def format_fullwidth ( self , value ) : """Return a full width column . Note that the padding is inherited from the first cell which inherits from column _ padding ."""
assert isinstance ( value , VTMLBuffer ) pad = self . colspec [ 0 ] [ 'padding' ] fmt = self . make_formatter ( self . width - pad , pad , self . table . title_align ) return VTMLBuffer ( '\n' ) . join ( fmt ( value ) )
def wait_transmit ( self , * ports ) : """Wait for traffic end on ports . : param ports : list of ports to wait for , if empty wait for all ports ."""
port_list = self . set_ports_list ( * ports ) self . api . call_rc ( 'ixCheckTransmitDone {}' . format ( port_list ) )
def rmtree ( self , path ) : """Removes directory structure , similar to shutil . rmtree ."""
for root , storage , streams in self . walk ( path , topdown = False ) : for item in streams : self . free_fat_chain ( item . sector_id , item . byte_size < self . min_stream_max_size ) self . free_dir_entry ( item ) for item in storage : self . free_dir_entry ( item ) root . child_i...
def PatchAt ( cls , n , module , method_wrapper = None , module_alias = None , method_name_modifier = utils . identity , blacklist_predicate = _False , whitelist_predicate = _True , return_type_predicate = _None , getmembers_predicate = inspect . isfunction , admit_private = False , explanation = "" ) : """This cla...
_rtp = return_type_predicate return_type_predicate = ( lambda x : _rtp ) if inspect . isclass ( _rtp ) and issubclass ( _rtp , Builder ) else _rtp module_name = module_alias if module_alias else module . __name__ + '.' patch_members = _get_patch_members ( module , blacklist_predicate = blacklist_predicate , whitelist_p...
def set_state ( self , state ) : """Call the set _ state method in SimStatePlugin class , and then perform the delayed initialization . : param state : The SimState instance"""
SimStatePlugin . set_state ( self , state ) # Delayed initialization stack_region_map , generic_region_map = self . _temp_stack_region_map , self . _temp_generic_region_map if stack_region_map or generic_region_map : # Inherited from its parent self . _stack_region_map = stack_region_map . copy ( ) self . _gene...
def submission_filenames ( round_num = None , tournament = None ) : """Get filenames of your submissions"""
click . echo ( prettify ( napi . get_submission_filenames ( tournament , round_num ) ) )
def default_reverse_key_func ( full_key ) : """Reverse of Django ' s default _ key _ func , i . e . undoing : def default _ key _ func ( key , key _ prefix , version ) : return ' % s : % s : % s ' % ( key _ prefix , version , key )"""
match = reverse_key_re . match ( full_key ) return match . group ( 3 ) , match . group ( 1 ) , int ( match . group ( 2 ) )
def delete ( self ) : """Delete this record without deleting any dependent or child records . This can orphan records , so use with care ."""
if self . id : with Repo . db : Repo ( self . __table ) . where ( id = self . id ) . delete ( )
def parse_config ( main_section , * filenames ) : """parse config files"""
filename = filenames [ - 1 ] filename = os . path . abspath ( filename ) here = os . path . dirname ( filename ) defaults = dict ( here = here , hash = '#' ) defaults [ '#' ] = '#' config = configparser . ConfigParser ( defaults , allow_no_value = False , interpolation = configparser . ExtendedInterpolation ( ) , ) con...
def offer_url ( self ) : """Offer URL : return : Offer URL ( string ) ."""
return "{0}{1}/?tag={2}" . format ( AMAZON_ASSOCIATES_BASE_URL . format ( domain = DOMAINS [ self . region ] ) , self . asin , self . aws_associate_tag )
def __register ( self , operator ) : """Registers the given logical operator to the environment and connects it to its upstream operator ( if any ) . A call to this function adds a new edge to the logical topology . Attributes : operator ( Operator ) : The metadata of the logical operator ."""
self . env . operators [ operator . id ] = operator self . dst_operator_id = operator . id logger . debug ( "Adding new dataflow edge ({},{}) --> ({},{})" . format ( self . src_operator_id , self . env . operators [ self . src_operator_id ] . name , self . dst_operator_id , self . env . operators [ self . dst_operator_...
def line_iterator ( readable_file , size = None ) : # type : ( IO [ bytes ] , Optional [ int ] ) - > Iterator [ bytes ] """Iterate over the lines of a file . Implementation reads each char individually , which is not very efficient . Yields : str : a single line in the file ."""
read = readable_file . read line = [ ] byte = b"1" if size is None or size < 0 : while byte : byte = read ( 1 ) line . append ( byte ) if byte in b"\n" : yield b"" . join ( line ) del line [ : ] else : while byte and size : byte = read ( 1 ) size -...
def dim ( self ) : """NAME : dim PURPOSE : return the dimension of the Orbit INPUT : ( none ) OUTPUT : dimension HISTORY : 2011-02-03 - Written - Bovy ( NYU )"""
if len ( self . _orb . vxvv ) == 2 : return 1 elif len ( self . _orb . vxvv ) == 3 or len ( self . _orb . vxvv ) == 4 : return 2 elif len ( self . _orb . vxvv ) == 5 or len ( self . _orb . vxvv ) == 6 : return 3
def crypto_secretstream_xchacha20poly1305_keygen ( ) : """Generate a key for use with : func : ` . crypto _ secretstream _ xchacha20poly1305 _ init _ push ` ."""
keybuf = ffi . new ( "unsigned char[]" , crypto_secretstream_xchacha20poly1305_KEYBYTES , ) lib . crypto_secretstream_xchacha20poly1305_keygen ( keybuf ) return ffi . buffer ( keybuf ) [ : ]
def visitIgnoreDirective ( self , ctx : jsgParser . IgnoreDirectiveContext ) : """directive : ' . IGNORE ' name * SEMI"""
for name in as_tokens ( ctx . name ( ) ) : self . _context . directives . append ( '_CONTEXT.IGNORE.append("{}")' . format ( name ) )
def get_all ( self , search_filter = None ) : """Fetch all data from backend ."""
items = self . backend . get_all ( ) if not items : if self . version == 1 : return { self . namespace : [ ] } return [ ] if search_filter : items = jmespath . search ( search_filter , items ) return items
def prepare_raise ( func ) : """Just a short decorator which shrinks full ` ` raise ( E , V , T ) ` ` form into proper ` ` raise E ( V ) , T ` ` ."""
@ functools . wraps ( func ) def decorator ( type_ , value = None , traceback = None ) : if value is not None and isinstance ( type_ , Exception ) : raise TypeError ( "instance exception may not have a separate value" ) if value is None : if isinstance ( type_ , Exception ) : error =...
def RemoveObject ( self , path ) : '''Remove a D - Bus object from the mock As with AddObject , this will * not * emit the InterfacesRemoved signal if it ’ s an ObjectManager instance .'''
try : objects [ path ] . remove_from_connection ( ) del objects [ path ] except KeyError : raise dbus . exceptions . DBusException ( 'object %s does not exist' % path , name = 'org.freedesktop.DBus.Mock.NameError' )
async def renew ( self , session , * , dc = None ) : """Renews a TTL - based session Parameters : session ( ObjectID ) : Session ID dc ( str ) : Specify datacenter that will be used . Defaults to the agent ' s local datacenter . Returns : ObjectMeta : where value is session Raises : NotFound : sessi...
session_id = extract_attr ( session , keys = [ "ID" ] ) response = await self . _api . put ( "/v1/session/renew" , session_id , params = { "dc" : dc } ) try : result = response . body [ 0 ] except IndexError : meta = extract_meta ( response . headers ) raise NotFound ( "No session for %r" % session_id , met...
def update_vault ( self , vault_form ) : """Updates an existing vault . arg : vault _ form ( osid . authorization . VaultForm ) : the form containing the elements to be updated raise : IllegalState - ` ` vault _ form ` ` already used in an update transaction raise : InvalidArgument - the form contains an ...
# Implemented from template for # osid . resource . BinAdminSession . update _ bin _ template if self . _catalog_session is not None : return self . _catalog_session . update_catalog ( catalog_form = vault_form ) collection = JSONClientValidated ( 'authorization' , collection = 'Vault' , runtime = self . _runtime )...
def delete_post ( apikey , post_id , username , password , publish ) : """blogger . deletePost ( api _ key , post _ id , username , password , ' publish ' ) = > boolean"""
user = authenticate ( username , password , 'zinnia.delete_entry' ) entry = Entry . objects . get ( id = post_id , authors = user ) entry . delete ( ) return True
def get_arguments ( options ) : """This function handles and validates the wrapper arguments ."""
# These the next couple of lines defines the header of the Help output parser = ArgumentParser ( formatter_class = RawDescriptionHelpFormatter , usage = ( """%(prog)s -------------------------------------------------------------------------------- """ ) , description = ( """ Service Wrapper =============== This is the ...
def pre_filter ( self ) : """Return rTorrent condition to speed up data transfer ."""
if self . _name not in self . PRE_FILTER_FIELDS or self . _template : return '' if not self . _value : return '"equal={},cat="' . format ( self . PRE_FILTER_FIELDS [ self . _name ] ) if self . _is_regex : needle = self . _value [ 1 : - 1 ] needle = self . CLEAN_PRE_VAL_RE . sub ( ' ' , needle ) need...
def retrieve_config ( self , value , default ) : """Retrieves a value ( with a certain fallback ) from the config files ( looks first into config _ filename _ global then into config _ filename _ user . The latest takes preeminence ) if the command line flag for the value is used , that overrides everything e...
args = self . args name = self . name try : if args [ value ] : return args [ value ] except KeyError : pass section = name if self . config . has_section ( name ) else self . config . default_section answer = self . config . get ( section , value , fallback = default ) return answer
def astensor ( array : TensorLike ) -> BKTensor : """Convert to product tensor"""
tensor = tf . convert_to_tensor ( array , dtype = CTYPE ) if DEVICE == 'gpu' : tensor = tensor . gpu ( ) # pragma : no cover # size = np . prod ( np . array ( tensor . get _ shape ( ) . as _ list ( ) ) ) N = int ( math . log2 ( size ( tensor ) ) ) tensor = tf . reshape ( tensor , ( [ 2 ] * N ) ) return tensor
def success ( self , ** kwargs ) : """Returns all arguments received in init and this method call"""
response = { 'success' : True } # check dates can be manipulated response . update ( kwargs ) response . update ( self . kwargs ) response [ 'test_argument3' ] = datetime . timedelta ( days = 1 ) + response [ 'test_argument3' ] return response
def fix_cufflinks_attributes ( ref_gtf , merged_gtf , data , out_file = None ) : """replace the cufflinks gene _ id and transcript _ id with the gene _ id and transcript _ id from ref _ gtf , where available"""
base , ext = os . path . splitext ( merged_gtf ) fixed = out_file if out_file else base + ".clean.fixed" + ext if file_exists ( fixed ) : return fixed ref_db = gtf . get_gtf_db ( ref_gtf ) merged_db = gtf . get_gtf_db ( merged_gtf , in_memory = True ) ref_tid_to_gid = { } for gene in ref_db . features_of_type ( 'ge...