signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def reciprocal_lattice_from_outcar ( filename ) : # from https : / / github . com / MaterialsDiscovery / PyChemia """Finds and returns the reciprocal lattice vectors , if more than one set present , it just returns the last one . Args : filename ( Str ) : The name of the outcar file to be read Returns : L...
outcar = open ( filename , "r" ) . read ( ) # just keeping the last component recLat = re . findall ( r"reciprocal\s*lattice\s*vectors\s*([-.\s\d]*)" , outcar ) [ - 1 ] recLat = recLat . split ( ) recLat = np . array ( recLat , dtype = float ) # up to now I have , both direct and rec . lattices ( 3 + 3 = 6 columns ) re...
def default_resolve_fn ( source , info , ** args ) : # type : ( Any , ResolveInfo , * * Any ) - > Optional [ Any ] """If a resolve function is not given , then a default resolve behavior is used which takes the property of the source object of the same name as the field and returns it as the result , or if it ' s...
name = info . field_name if isinstance ( source , dict ) : property = source . get ( name ) else : property = getattr ( source , name , None ) if callable ( property ) : return property ( ) return property
def _process_raw_report ( self , raw_report ) : "Default raw input report data handler"
if not self . is_opened ( ) : return if not self . __evt_handlers and not self . __raw_handler : return if not raw_report [ 0 ] and ( raw_report [ 0 ] not in self . __input_report_templates ) : # windows sends an empty array when disconnecting # but , this might have a collision with report _ id = 0 if not ...
def stop ( self ) : """Stop consuming the stream and shutdown the background thread ."""
with self . _operational_lock : self . _bidi_rpc . close ( ) if self . _thread is not None : # Resume the thread to wake it up in case it is sleeping . self . resume ( ) self . _thread . join ( ) self . _thread = None
def abort ( payment ) : """Abort a payment from its id . : param payment : The payment id or payment object : type payment : string | Payment : return : The payment resource : rtype : resources . Payment"""
if isinstance ( payment , resources . Payment ) : payment = payment . id http_client = HttpClient ( ) response , __ = http_client . patch ( routes . url ( routes . PAYMENT_RESOURCE , resource_id = payment ) , { 'abort' : True } ) return resources . Payment ( ** response )
def _split_coefficents ( self , w ) : """Split into intercept / bias and feature - specific coefficients"""
if self . _fit_intercept : bias = w [ 0 ] wf = w [ 1 : ] else : bias = 0.0 wf = w return bias , wf
def reset ( self ) : """Instruct the target to forget any related exception ."""
if not self . chain_id : return saved , self . chain_id = self . chain_id , None try : self . call_no_reply ( mitogen . core . Dispatcher . forget_chain , saved ) finally : self . chain_id = saved
def add_particles_ascii ( self , s ) : """Adds particles from an ASCII string . Parameters s : string One particle per line . Each line should include particle ' s mass , radius , position and velocity ."""
for l in s . split ( "\n" ) : r = l . split ( ) if len ( r ) : try : r = [ float ( x ) for x in r ] p = Particle ( simulation = self , m = r [ 0 ] , r = r [ 1 ] , x = r [ 2 ] , y = r [ 3 ] , z = r [ 4 ] , vx = r [ 5 ] , vy = r [ 6 ] , vz = r [ 7 ] ) self . add ( p ) ...
def siblings ( self , ** kwargs ) : """Retrieve the other activities that also belong to the parent . It returns a combination of Tasks ( a . o . UserTasks ) and Subprocesses on the level of the current task , including itself . This also works if the activity is of type ` ActivityType . PROCESS ` . : param k...
parent_id = self . _json_data . get ( 'parent_id' ) if parent_id is None : raise NotFoundError ( "Cannot find subprocess for this task '{}', " "as this task exist on top level." . format ( self . name ) ) return self . _client . activities ( parent_id = parent_id , scope = self . scope_id , ** kwargs )
def send ( self , request , ** kwargs ) : # type : ( ClientRequest , Any ) - > ClientResponse """Send request object according to configuration . Allowed kwargs are : - session : will override the driver session and use yours . Should NOT be done unless really required . - anything else is sent straight to re...
# It ' s not recommended to provide its own session , and is mostly # to enable some legacy code to plug correctly session = kwargs . pop ( 'session' , self . session ) try : response = session . request ( request . method , request . url , ** kwargs ) except requests . RequestException as err : msg = "Error oc...
def _extract_upnperror ( self , err_xml ) : """Extract the error code and error description from an error returned by the device ."""
nsmap = { 's' : list ( err_xml . nsmap . values ( ) ) [ 0 ] } fault_str = err_xml . findtext ( 's:Body/s:Fault/faultstring' , namespaces = nsmap ) try : err = err_xml . xpath ( 's:Body/s:Fault/detail/*[name()="%s"]' % fault_str , namespaces = nsmap ) [ 0 ] except IndexError : msg = 'Tag with name of %r was not ...
def list_overlay_names ( self ) : """Return list of overlay names ."""
overlay_names = [ ] if not os . path . isdir ( self . _overlays_abspath ) : return overlay_names for fname in os . listdir ( self . _overlays_abspath ) : name , ext = os . path . splitext ( fname ) overlay_names . append ( name ) return overlay_names
def alignProcrustes ( sources , rigid = False ) : """Return an ` ` Assembly ` ` of aligned source actors with the ` Procrustes ` algorithm . The output ` ` Assembly ` ` is normalized in size . ` Procrustes ` algorithm takes N set of points and aligns them in a least - squares sense to their mutual mean . The ...
group = vtk . vtkMultiBlockDataGroupFilter ( ) for source in sources : if sources [ 0 ] . N ( ) != source . N ( ) : vc . printc ( "~times Procrustes error in align():" , c = 1 ) vc . printc ( " sources have different nr of points" , c = 1 ) exit ( 0 ) group . AddInputData ( source . poly...
def diy ( expression_data , regressor_type , regressor_kwargs , gene_names = None , tf_names = 'all' , client_or_address = 'local' , early_stop_window_length = EARLY_STOP_WINDOW_LENGTH , limit = None , seed = None , verbose = False ) : """: param expression _ data : one of : * a pandas DataFrame ( rows = observat...
if verbose : print ( 'preparing dask client' ) client , shutdown_callback = _prepare_client ( client_or_address ) try : if verbose : print ( 'parsing input' ) expression_matrix , gene_names , tf_names = _prepare_input ( expression_data , gene_names , tf_names ) if verbose : print ( 'crea...
def impute ( args ) : """% prog impute input . vcf hs37d5 . fa 1 Use IMPUTE2 to impute vcf on chromosome 1."""
from pyfaidx import Fasta p = OptionParser ( impute . __doc__ ) p . set_home ( "shapeit" ) p . set_home ( "impute" ) p . set_ref ( ) p . set_cpus ( ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) vcffile , fastafile , chr = args mm = MakeManager ( ) pf = vcffile ...
def unpin_chat_message ( self , chat_id : Union [ int , str ] ) -> bool : """Use this method to unpin a message in a group , channel or your own chat . You must be an administrator in the chat for this to work and must have the " can _ pin _ messages " admin right in the supergroup or " can _ edit _ messages " ...
self . send ( functions . messages . UpdatePinnedMessage ( peer = self . resolve_peer ( chat_id ) , id = 0 ) ) return True
def get_entry_map ( self , group = None ) : """Return the entry point map for ` group ` , or the full entry map"""
try : ep_map = self . _ep_map except AttributeError : ep_map = self . _ep_map = EntryPoint . parse_map ( self . _get_metadata ( 'entry_points.txt' ) , self ) if group is not None : return ep_map . get ( group , { } ) return ep_map
def _plot_weights_motif ( self , index , plot_type = "motif_raw" , background_probs = DEFAULT_BASE_BACKGROUND , ncol = 1 , figsize = None ) : """Index can only be a single int"""
w_all = self . get_weights ( ) if len ( w_all ) == 0 : raise Exception ( "Layer needs to be initialized first" ) W = w_all [ 0 ] if index is None : index = np . arange ( W . shape [ 2 ] ) if isinstance ( index , int ) : index = [ index ] fig = plt . figure ( figsize = figsize ) if plot_type == "motif_pwm" a...
def choices ( self ) : """Available choices for characters to be generated ."""
if self . _choices : return self . _choices for n in os . listdir ( self . _voicedir ) : if len ( n ) == 1 and os . path . isdir ( os . path . join ( self . _voicedir , n ) ) : self . _choices . append ( n ) return self . _choices
def getContactTypes ( self ) : """Return an iterator of L { IContactType } providers available to this organizer ' s store ."""
yield VIPPersonContactType ( ) yield EmailContactType ( self . store ) yield PostalContactType ( ) yield PhoneNumberContactType ( ) yield NotesContactType ( ) for getContactTypes in self . _gatherPluginMethods ( 'getContactTypes' ) : for contactType in getContactTypes ( ) : self . _checkContactType ( contac...
def money_flow_index ( close_data , high_data , low_data , volume , period ) : """Money Flow Index . Formula : MFI = 100 - ( 100 / ( 1 + PMF / NMF ) )"""
catch_errors . check_for_input_len_diff ( close_data , high_data , low_data , volume ) catch_errors . check_for_period_error ( close_data , period ) mf = money_flow ( close_data , high_data , low_data , volume ) tp = typical_price ( close_data , high_data , low_data ) flow = [ tp [ idx ] > tp [ idx - 1 ] for idx in ran...
def extracted ( name , source , source_hash = None , source_hash_name = None , source_hash_update = False , skip_verify = False , password = None , options = None , list_options = None , force = False , overwrite = False , clean = False , user = None , group = None , if_missing = None , trim_output = False , use_cmd_un...
ret = { 'name' : name , 'result' : False , 'changes' : { } , 'comment' : '' } # Remove pub kwargs as they ' re irrelevant here . kwargs = salt . utils . args . clean_kwargs ( ** kwargs ) if 'keep_source' in kwargs and 'keep' in kwargs : ret . setdefault ( 'warnings' , [ ] ) . append ( 'Both \'keep_source\' and \'ke...
def changes ( self , adding = None , deleting = None ) : """Pass the given changes to the root _ node ."""
if deleting is not None : for deleted in deleting : self . root_node . remove ( deleted ) if adding is not None : for added in adding : self . root_node . add ( added ) added = list ( ) removed = list ( ) for csn in self . _get_conflict_set_nodes ( ) : c_added , c_removed = csn . get_activat...
def nla_for_each_attr ( head , len_ , rem ) : """Iterate over a stream of attributes . https : / / github . com / thom311 / libnl / blob / libnl3_2_25 / include / netlink / attr . h # L262 Positional arguments : head - - first nlattr with more in its bytearray payload ( nlattr class instance ) . len _ - - l...
pos = head rem . value = len_ while nla_ok ( pos , rem ) : yield pos pos = nla_next ( pos , rem )
def docelement ( self ) : """Returns the instance of the element whose body owns the docstring in the current operation ."""
# This is needed since the decorating documentation # for types and executables is in the body of the module , but when they # get edited , the edit belongs to the type / executable because the character # falls within the absstart and end attributes . if self . _docelement is None : if isinstance ( self . element ...
def add_case ( self , case , update = False ) : """Add a case to the case collection If the case exists and update is False raise error . Args : db ( MongoClient ) : A connection to the mongodb case ( dict ) : A case dictionary update ( bool ) : If existing case should be updated Returns : mongo _ cas...
existing_case = self . case ( case ) if existing_case and not update : raise CaseError ( "Case {} already exists" . format ( case [ 'case_id' ] ) ) if existing_case : self . db . case . find_one_and_replace ( { 'case_id' : case [ 'case_id' ] } , case , ) else : self . db . case . insert_one ( case ) return ...
def freeze_bn ( self ) : '''Freeze BatchNorm layers .'''
for layer in self . modules ( ) : if isinstance ( layer , nn . BatchNorm2d ) : layer . eval ( )
def update ( cls , cluster_id_label , cluster_info ) : """Update the cluster with id / label ` cluster _ id _ label ` using information provided in ` cluster _ info ` ."""
conn = Qubole . agent ( version = "v2" ) return conn . put ( cls . element_path ( cluster_id_label ) , data = cluster_info )
def termination_check ( self ) : # type : ( Uploader ) - > bool """Check if terminated : param Uploader self : this : rtype : bool : return : if terminated"""
with self . _upload_lock : with self . _transfer_lock : return ( self . _upload_terminate or len ( self . _exceptions ) > 0 or ( self . _all_files_processed and len ( self . _upload_set ) == 0 and len ( self . _transfer_set ) == 0 ) )
def load_vocab ( vocab_file ) : """Loads a vocabulary file into a dictionary ."""
vocab = collections . OrderedDict ( ) index = 0 with io . open ( vocab_file , 'r' ) as reader : while True : token = reader . readline ( ) if not token : break token = token . strip ( ) vocab [ token ] = index index += 1 return vocab
def to_twos_comp ( val , bits ) : """compute the 2 ' s compliment of int value val"""
if not val . startswith ( '-' ) : return to_int ( val ) value = _invert ( to_bin_str_from_int_string ( bits , bin ( to_int ( val [ 1 : ] ) ) ) ) return int ( value , 2 ) + 1
def convert_upload_string_to_file ( i ) : """Input : { file _ content _ base64 - string transmitted through Internet ( filename ) - file name to write ( if empty , generate tmp file ) Output : { return - return code = 0 , if successful > 0 , if error ( error ) - error text if return > 0 filename - fil...
import base64 x = i [ 'file_content_base64' ] fc = base64 . urlsafe_b64decode ( str ( x ) ) # convert from unicode to str since base64 works on strings # should be safe in Python 2 . x and 3 . x fn = i . get ( 'filename' , '' ) if fn == '' : rx = gen_tmp_file ( { 'prefix' : 'tmp-' } ) if rx [ 'return' ] > 0 : ...
def relation_column ( instance , fields ) : '''such as : user . username such as : replies . content'''
relation = getattr ( instance . __class__ , fields [ 0 ] ) . property _field = getattr ( instance , fields [ 0 ] ) if relation . lazy == 'dynamic' : _field = _field . first ( ) return getattr ( _field , fields [ 1 ] ) if _field else ''
def get_image_path ( name , default = "not_found.png" ) : """Return image absolute path"""
for img_path in IMG_PATH : full_path = osp . join ( img_path , name ) if osp . isfile ( full_path ) : return osp . abspath ( full_path ) if default is not None : img_path = osp . join ( get_module_path ( 'spyder' ) , 'images' ) return osp . abspath ( osp . join ( img_path , default ) )
def handle ( self , * args , ** options ) : """Main command method ."""
# Already running , so quit if os . path . exists ( self . lock_file ) : self . log ( ( "This script is already running. " "(If your are sure it's not please " "delete the lock file in {}')" ) . format ( self . lock_file ) ) sys . exit ( 0 ) if not os . path . exists ( os . path . dirname ( self . lock_file ) )...
def dataSource ( self , value ) : """sets the datasource object"""
if isinstance ( value , DataSource ) : self . _dataSource = value else : raise TypeError ( "value must be a DataSource object" )
def start ( self ) : """Begin listening for events from the Client and acting upon them . Note : If configuration has not already been loaded , it will be loaded immediately before starting to listen for events . Calling this method without having specified and / or loaded a configuration will result in com...
if not self . config and self . config_path is not None : self . load_config ( ) self . running = True self . process_event ( "STARTUP" , self . client , ( ) )
def _invade_isolated_Ts ( self ) : r"""Throats that are uninvaded connected to pores that are both invaded should be invaded too ."""
net = self . project . network Ts = net [ 'throat.conns' ] . copy ( ) invaded_Ps = self [ 'pore.invasion_sequence' ] > - 1 uninvaded_Ts = self [ 'throat.invasion_sequence' ] == - 1 isolated_Ts = np . logical_and ( invaded_Ps [ Ts [ : , 0 ] ] , invaded_Ps [ Ts [ : , 1 ] ] ) isolated_Ts = np . logical_and ( isolated_Ts ,...
def convert_multiple_sources_to_consumable_types ( self , project , prop_set , sources ) : """Converts several files to consumable types ."""
if __debug__ : from . targets import ProjectTarget assert isinstance ( project , ProjectTarget ) assert isinstance ( prop_set , property_set . PropertySet ) assert is_iterable_typed ( sources , virtual_target . VirtualTarget ) if not self . source_types_ : return list ( sources ) acceptable_types = ...
def check_for_update ( self , force = True , download = False ) : """Returns a : class : ` ~ plexapi . base . Release ` object containing release info . Parameters : force ( bool ) : Force server to check for new releases download ( bool ) : Download if a update is available ."""
part = '/updater/check?download=%s' % ( 1 if download else 0 ) if force : self . query ( part , method = self . _session . put ) releases = self . fetchItems ( '/updater/status' ) if len ( releases ) : return releases [ 0 ]
def save_anndata ( self , fname , data = 'adata_raw' , ** kwargs ) : """Saves ` adata _ raw ` to a . h5ad file ( AnnData ' s native file format ) . Parameters fname - string The filename of the output file ."""
x = self . __dict__ [ data ] x . write_h5ad ( fname , ** kwargs )
def notify_scale_factor_change ( self , screen_id , u32_scale_factor_w_multiplied , u32_scale_factor_h_multiplied ) : """Notify OpenGL HGCM host service about graphics content scaling factor change . in screen _ id of type int in u32 _ scale _ factor _ w _ multiplied of type int in u32 _ scale _ factor _ h _ ...
if not isinstance ( screen_id , baseinteger ) : raise TypeError ( "screen_id can only be an instance of type baseinteger" ) if not isinstance ( u32_scale_factor_w_multiplied , baseinteger ) : raise TypeError ( "u32_scale_factor_w_multiplied can only be an instance of type baseinteger" ) if not isinstance ( u32_...
def check_retcode ( self , line ) : """Look for retcode on line line and return return code if found . : param line : Line to search from : return : integer return code or - 1 if " cmd tasklet init " is found . None if retcode or cmd tasklet init not found ."""
retcode = None match = re . search ( r"retcode\: ([-\d]{1,})" , line ) if match : retcode = num ( str ( match . group ( 1 ) ) ) match = re . search ( "cmd tasklet init" , line ) if match : self . logger . debug ( "Device Boot up" , extra = { 'type' : ' ' } ) return - 1 return retcode
def display ( self , ret , indent , out , rows_key = None , labels_key = None ) : '''Display table ( s ) .'''
rows = [ ] labels = None if isinstance ( ret , dict ) : if not rows_key or ( rows_key and rows_key in list ( ret . keys ( ) ) ) : # either not looking for a specific key # either looking and found in the current root for key in sorted ( ret ) : if rows_key and key != rows_key : ...
def start ( self , name ) : '''End the current behaviour and run a named behaviour . : param name : the name of the behaviour to run : type name : str'''
d = self . boatd . post ( { 'active' : name } , endpoint = '/behaviours' ) current = d . get ( 'active' ) if current is not None : return 'started {}' . format ( current ) else : return 'no behaviour running'
def min_date ( self , symbol ) : """Return the minimum datetime stored for a particular symbol Parameters symbol : ` str ` symbol name for the item"""
res = self . _collection . find_one ( { SYMBOL : symbol } , projection = { ID : 0 , START : 1 } , sort = [ ( START , pymongo . ASCENDING ) ] ) if res is None : raise NoDataFoundException ( "No Data found for {}" . format ( symbol ) ) return utc_dt_to_local_dt ( res [ START ] )
def select_template ( template_name_list , using = None ) : """Loads and returns a template for one of the given names . Tries names in order and returns the first template found . Raises TemplateDoesNotExist if no such template exists ."""
if isinstance ( template_name_list , six . string_types ) : raise TypeError ( 'select_template() takes an iterable of template names but got a ' 'string: %r. Use get_template() if you want to load a single ' 'template by name.' % template_name_list ) engines = _engine_list ( using ) for template_name in template_na...
def get_comic_format ( filename ) : """Return the comic format if it is a comic archive ."""
image_format = None filename_ext = os . path . splitext ( filename ) [ - 1 ] . lower ( ) if filename_ext in _COMIC_EXTS : if zipfile . is_zipfile ( filename ) : image_format = _CBZ_FORMAT elif rarfile . is_rarfile ( filename ) : image_format = _CBR_FORMAT return image_format
def get_lattice_vector_equivalence ( point_symmetry ) : """Return ( b = = c , c = = a , a = = b )"""
# primitive _ vectors : column vectors equivalence = [ False , False , False ] for r in point_symmetry : if ( np . abs ( r [ : , 0 ] ) == [ 0 , 1 , 0 ] ) . all ( ) : equivalence [ 2 ] = True if ( np . abs ( r [ : , 0 ] ) == [ 0 , 0 , 1 ] ) . all ( ) : equivalence [ 1 ] = True if ( np . abs (...
def info ( self , msg : str ) -> None : """Write an info message to the Windows Application log ( ± to the Python disk log ) ."""
# noinspection PyUnresolvedReferences s = "{}: {}" . format ( self . fullname , msg ) servicemanager . LogInfoMsg ( s ) if self . debugging : log . info ( s )
def predict_is ( self , h = 5 , fit_once = True ) : """Makes dynamic in - sample predictions with the estimated model Parameters h : int ( default : 5) How many steps would you like to forecast ? fit _ once : boolean ( default : True ) Fits only once before the in - sample prediction ; if False , fits aft...
predictions = [ ] for t in range ( 0 , h ) : x = NLLEV ( family = self . family , integ = self . integ , data = self . data_original [ : ( - h + t ) ] ) x . fit ( print_progress = False ) if t == 0 : predictions = x . predict ( h = 1 ) else : predictions = pd . concat ( [ predictions , x...
def _log ( self , num = None , format = None ) : '''Helper function to receive git log : param num : Number of entries : param format : Use formatted output with specified format string'''
num = '-n %s' % ( num ) if num else '' format = '--format="%s"' % ( format ) if format else '' return self . m ( 'getting git log' , cmdd = dict ( cmd = 'git log %s %s' % ( num , format ) , cwd = self . local ) , verbose = False )
def _UpdateSudoer ( self , user , sudoer = False ) : """Update sudoer group membership for a Linux user account . Args : user : string , the name of the Linux user account . sudoer : bool , True if the user should be a sudoer . Returns : bool , True if user update succeeded ."""
if sudoer : self . logger . info ( 'Adding user %s to the Google sudoers group.' , user ) command = self . gpasswd_add_cmd . format ( user = user , group = self . google_sudoers_group ) else : self . logger . info ( 'Removing user %s from the Google sudoers group.' , user ) command = self . gpasswd_remo...
def MaximumLikelihood ( self ) : """Returns the value with the highest probability . Returns : float probability"""
prob , val = max ( ( prob , val ) for val , prob in self . Items ( ) ) return val
def _handler ( self , conn ) : """Connection handler thread . Takes care of communication with the client and running the proper task or applying a signal ."""
incoming = self . recv ( conn ) self . log ( DEBUG , incoming ) try : # E . g . [ ' twister ' , [ 7 , ' invert ' ] , { ' guess _ type ' : True } ] task , args , kw = self . codec . decode ( incoming ) # OK , so we ' ve received the information . Now to use it . self . log ( INFO , 'Fulfilling task %r' % tas...
def lookup_ids ( self , keys ) : """Lookup the integer ID associated with each ( namespace , key ) in the keys list"""
keys_len = len ( keys ) ids = { namespace_key : None for namespace_key in keys } start = 0 bulk_insert = self . bulk_insert query = 'SELECT namespace, key, id FROM gauged_keys WHERE ' check = '(namespace = %s AND key = %s) ' cursor = self . cursor execute = cursor . execute while start < keys_len : rows = keys [ st...
def ecliptic_xyz ( self , epoch = None ) : """Compute J2000 ecliptic position vector ( x , y , z ) . If you instead want the coordinates referenced to the dynamical system defined by the Earth ' s true equator and equinox , provide an epoch time ."""
if epoch is None : vector = _ECLIPJ2000 . dot ( self . position . au ) return Distance ( vector ) position_au = self . position . au if isinstance ( epoch , Time ) : pass elif isinstance ( epoch , float ) : epoch = Time ( None , tt = epoch ) elif epoch == 'date' : epoch = self . t else : raise V...
def libvlc_event_attach ( p_event_manager , i_event_type , f_callback , user_data ) : '''Register for an event notification . @ param p _ event _ manager : the event manager to which you want to attach to . Generally it is obtained by vlc _ my _ object _ event _ manager ( ) where my _ object is the object you wan...
f = _Cfunctions . get ( 'libvlc_event_attach' , None ) or _Cfunction ( 'libvlc_event_attach' , ( ( 1 , ) , ( 1 , ) , ( 1 , ) , ( 1 , ) , ) , None , ctypes . c_int , EventManager , ctypes . c_uint , Callback , ctypes . c_void_p ) return f ( p_event_manager , i_event_type , f_callback , user_data )
def startAlertListener ( self , callback = None ) : """Creates a websocket connection to the Plex Server to optionally recieve notifications . These often include messages from Plex about media scans as well as updates to currently running Transcode Sessions . NOTE : You need websocket - client installed in o...
notifier = AlertListener ( self , callback ) notifier . start ( ) return notifier
def obfuscatable_variable ( tokens , index , ignore_length = False ) : """Given a list of * tokens * and an * index * ( representing the current position ) , returns the token string if it is a variable name that can be safely obfuscated . Returns ' _ _ skipline _ _ ' if the rest of the tokens on this line sh...
tok = tokens [ index ] token_type = tok [ 0 ] token_string = tok [ 1 ] line = tok [ 4 ] if index > 0 : prev_tok = tokens [ index - 1 ] else : # Pretend it ' s a newline ( for simplicity ) prev_tok = ( 54 , '\n' , ( 1 , 1 ) , ( 1 , 2 ) , '#\n' ) prev_tok_type = prev_tok [ 0 ] prev_tok_string = prev_tok [ 1 ] try...
def fixchars ( self , text ) : """Find and replace problematic characters ."""
keys = '' . join ( Config . CHARFIXES . keys ( ) ) values = '' . join ( Config . CHARFIXES . values ( ) ) fixed = text . translate ( str . maketrans ( keys , values ) ) if fixed != text : self . modified = True return fixed
def get_interface_detail_output_interface_ifHCInOctets ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) get_interface_detail = ET . Element ( "get_interface_detail" ) config = get_interface_detail output = ET . SubElement ( get_interface_detail , "output" ) interface = ET . SubElement ( output , "interface" ) interface_type_key = ET . SubElement ( interface , "interface-type" ) interfac...
def report_parse ( self ) : """If the pipeline has previously been run on these data , instead of reading through the results , parse the report instead"""
# Initialise lists report_strains = list ( ) genus_list = list ( ) if self . analysistype == 'mlst' : for sample in self . runmetadata . samples : try : genus_list . append ( sample . general . referencegenus ) except AttributeError : sample . general . referencegenus = 'ND' ...
def get_errors ( audit_results ) : """Args : audit _ results : results of ` AxsAudit . do _ audit ( ) ` . Returns : a list of errors ."""
errors = [ ] if audit_results : if audit_results . errors : errors . extend ( audit_results . errors ) return errors
def sort_dictionary_list ( dict_list , sort_key ) : """sorts a list of dictionaries based on the value of the sort _ key dict _ list - a list of dictionaries sort _ key - a string that identifies the key to sort the dictionaries with . Test sorting a list of dictionaries : > > > sort _ dictionary _ list ( [...
if not dict_list or len ( dict_list ) == 0 : return dict_list dict_list . sort ( key = itemgetter ( sort_key ) ) return dict_list
def name ( self , value ) : """Generate the Site ' s slug ( for file paths , URL ' s , etc . )"""
self . _name = value self . slug = re . sub ( '[^0-9a-zA-Z_-]+' , '_' , str ( value ) . lower ( ) ) self . root = os . path . abspath ( os . path . join ( _cfg . get ( 'Paths' , 'HttpRoot' ) , self . domain . name , self . slug ) )
def get ( self , id ) : """Return the : class : ` ~ plexapi . settings . Setting ` object with the specified id ."""
id = utils . lowerFirst ( id ) if id in self . _settings : return self . _settings [ id ] raise NotFound ( 'Invalid setting id: %s' % id )
def replace_contractions_with_full_words_and_replace_numbers_with_digits ( text = None , remove_articles = True ) : """This function replaces contractions with full words and replaces numbers with digits in specified text . There is the option to remove articles ."""
words = text . split ( ) text_translated = "" for word in words : if remove_articles and word in [ "a" , "an" , "the" ] : continue contractions_expansions = { "ain't" : "is not" , "aren't" : "are not" , "can't" : "can not" , "could've" : "could have" , "couldn't" : "could not" , "didn't" : "did not" , "...
def _send_command_list ( self , commands ) : """Wrapper for Netmiko ' s send _ command method ( for list of commands ."""
output = "" for command in commands : output += self . device . send_command ( command , strip_prompt = False , strip_command = False ) return output
def move_mouse_relative ( self , x , y ) : """Move the mouse relative to it ' s current position . : param x : the distance in pixels to move on the X axis . : param y : the distance in pixels to move on the Y axis ."""
_libxdo . xdo_move_mouse_relative ( self . _xdo , x , y )
def _kbhit_unix ( ) -> bool : """Under UNIX : is a keystroke available ?"""
dr , dw , de = select . select ( [ sys . stdin ] , [ ] , [ ] , 0 ) return dr != [ ]
def plotFCM ( data , channel_names , kind = 'histogram' , ax = None , autolabel = True , xlabel_kwargs = { } , ylabel_kwargs = { } , colorbar = False , grid = False , ** kwargs ) : """Plots the sample on the current axis . Follow with a call to matplotlibs show ( ) in order to see the plot . Parameters data :...
if ax == None : ax = pl . gca ( ) xlabel_kwargs . setdefault ( 'size' , 16 ) ylabel_kwargs . setdefault ( 'size' , 16 ) channel_names = to_list ( channel_names ) if len ( channel_names ) == 1 : # 1D so histogram plot kwargs . setdefault ( 'color' , 'gray' ) kwargs . setdefault ( 'histtype' , 'stepfilled' ) ...
def find_models ( self , constructor , constraints = None , * , columns = None , order_by = None , limiting = None , table_name = None ) : """Specialization of DataAccess . find _ all that returns models instead of cursor objects ."""
return self . _find_models ( constructor , table_name or constructor . table_name , constraints , columns = columns , order_by = order_by , limiting = limiting )
def inner_rect ( self ) : """The rectangular area inside the margin , border , and padding . Generally widgets should avoid drawing or placing sub - widgets outside this rectangle ."""
m = self . margin + self . _border_width + self . padding if not self . border_color . is_blank : m += 1 return Rect ( ( m , m ) , ( self . size [ 0 ] - 2 * m , self . size [ 1 ] - 2 * m ) )
def _UpdateAndMigrateUnmerged ( self , not_merged_stops , zone_map , merge_map , schedule ) : """Correct references in migrated unmerged stops and add to merged _ schedule . For stops migrated from one of the input feeds to the output feed update the parent _ station and zone _ id references to point to objects...
# for the unmerged stops , we use an already mapped zone _ id if possible # if not , we generate a new one and add it to the map for stop , migrated_stop in not_merged_stops : if stop . zone_id in zone_map : migrated_stop . zone_id = zone_map [ stop . zone_id ] else : migrated_stop . zone_id = s...
def fetch_digests ( self , package_name : str , package_version : str ) -> dict : """Fetch digests for the given package in specified version from the given package index ."""
report = { } for source in self . _sources : try : report [ source . url ] = source . get_package_hashes ( package_name , package_version ) except NotFound as exc : _LOGGER . debug ( f"Package {package_name} in version {package_version} not " f"found on index {source.name}: {str(exc)}" ) return ...
def set ( self , oid , value , value_type = None ) : """Sets a single OID value . If you do not pass value _ type hnmp will try to guess the correct type . Autodetection is supported for : * int and float ( as Integer , fractional part will be discarded ) * IPv4 address ( as IpAddress ) * str ( as OctetStri...
snmpsecurity = self . _get_snmp_security ( ) if value_type is None : if isinstance ( value , int ) : data = Integer ( value ) elif isinstance ( value , float ) : data = Integer ( value ) elif isinstance ( value , str ) : if is_ipv4_address ( value ) : data = IpAddress ( v...
def get_objective_search_session ( self ) : """Gets the OsidSession associated with the objective search service . return : ( osid . learning . ObjectiveSearchSession ) - an ObjectiveSearchSession raise : OperationFailed - unable to complete request raise : Unimplemented - supports _ objective _ search ( ...
if not self . supports_objective_search ( ) : raise Unimplemented ( ) try : from . import sessions except ImportError : raise OperationFailed ( ) try : session = sessions . ObjectiveSearchSession ( runtime = self . _runtime ) except AttributeError : raise OperationFailed ( ) return session
def parse_range_header ( header , maxlen = 0 ) : '''Yield ( start , end ) ranges parsed from a HTTP Range header . Skip unsatisfiable ranges . The end index is non - inclusive .'''
if not header or header [ : 6 ] != 'bytes=' : return ranges = [ r . split ( '-' , 1 ) for r in header [ 6 : ] . split ( ',' ) if '-' in r ] for start , end in ranges : try : if not start : # bytes = - 100 - > last 100 bytes start , end = max ( 0 , maxlen - int ( end ) ) , maxlen elif...
def compute_asset_lifetimes ( frames ) : """Parameters frames : dict [ str , pd . DataFrame ] A dict mapping each OHLCV field to a dataframe with a row for each date and a column for each sid , as passed to write ( ) . Returns start _ date _ ixs : np . array [ int64] The index of the first date with non...
# Build a 2D array ( dates x sids ) , where an entry is True if all # fields are nan for the given day and sid . is_null_matrix = np . logical_and . reduce ( [ frames [ field ] . isnull ( ) . values for field in FIELDS ] , ) if not is_null_matrix . size : empty = np . array ( [ ] , dtype = 'int64' ) return empt...
def fetch_object ( self , doc_id ) : """Fetch the document by its PK ."""
try : return self . object_class . objects . get ( pk = doc_id ) except self . object_class . DoesNotExist : raise ReferenceNotFoundError
def reboot ( self ) : """Reboots the device . Generally one should use this method to reboot the device instead of directly calling ` adb . reboot ` . Because this method gracefully handles the teardown and restoration of running services . This method is blocking and only returns when the reboot has comple...
if self . is_bootloader : self . fastboot . reboot ( ) return with self . handle_reboot ( ) : self . adb . reboot ( )
def verify ( self , ** kwargs ) : """Checks this component for invalidating conditions : returns : str - - message if error , 0 otherwise"""
if 'duration' in kwargs : if kwargs [ 'duration' ] < self . _duration : return "Window size must equal or exceed stimulus length" if self . _risefall > self . _duration : return "Rise and fall times exceed component duration" return 0
def encode_certificate ( result ) : """Encode cert bytes to PEM encoded cert file ."""
cert_body = """-----BEGIN CERTIFICATE-----\n{0}\n-----END CERTIFICATE-----\n""" . format ( "\n" . join ( textwrap . wrap ( base64 . b64encode ( result ) . decode ( 'utf8' ) , 64 ) ) ) signed_crt = open ( "{}/signed.crt" . format ( gettempdir ( ) ) , "w" ) signed_crt . write ( cert_body ) signed_crt . close ( ) return T...
def show ( self ) : """Ensure the widget is shown . Calling this method will also set the widget visibility to True ."""
self . visible = True if self . proxy_is_active : self . proxy . ensure_visible ( )
def mask ( scope , ips , mask ) : """Applies the given IP mask ( e . g . 255.255.255.0 ) to the given IP address ( or list of IP addresses ) and returns it . : type ips : string : param ips : A prefix , or a list of IP prefixes . : type mask : string : param mask : An IP mask . : rtype : string : retu...
mask = ipv4 . ip2int ( mask [ 0 ] ) return [ ipv4 . int2ip ( ipv4 . ip2int ( ip ) & mask ) for ip in ips ]
def contains ( self , token : str ) -> bool : """Return if the token is in the list or not ."""
self . _validate_token ( token ) return token in self
def delete_all_metadata ( self ) : """DELETE / : login / machines / : id / metadata : Returns : current metadata : rtype : empty : py : class : ` dict ` Deletes all the metadata stored for this machine . Also explicitly requests and returns the machine metadata so that the local copy stays synchronized ."...
j , r = self . datacenter . request ( 'DELETE' , self . path + '/metadata' ) r . raise_for_status ( ) return self . get_metadata ( )
def _write_proxy_conf ( proxyfile ) : '''write to file'''
msg = 'Invalid value for proxy file provided!, Supplied value = {0}' . format ( proxyfile ) log . trace ( 'Salt Proxy Module: write proxy conf' ) if proxyfile : log . debug ( 'Writing proxy conf file' ) with salt . utils . files . fopen ( proxyfile , 'w' ) as proxy_conf : proxy_conf . write ( salt . uti...
def get_locations ( self , filter_to_my_group = False ) : """Retrieve Locations listed in ChemInventory"""
resp = self . _post ( 'general-retrievelocations' , 'locations' ) groups = { } if resp [ 'groupinfo' ] : for group in resp [ 'groupinfo' ] : groups [ group [ 'id' ] ] = Group ( name = group . get ( 'name' ) , inventory_id = group . get ( 'id' ) ) final_resp = [ ] if resp [ 'data' ] : if filter_to_my_gro...
def solution_path ( self , min_lambda , max_lambda , lambda_bins , verbose = 0 ) : '''Follows the solution path to find the best lambda value .'''
self . u = np . zeros ( self . Dk . shape [ 0 ] , dtype = 'double' ) lambda_grid = np . exp ( np . linspace ( np . log ( max_lambda ) , np . log ( min_lambda ) , lambda_bins ) ) aic_trace = np . zeros ( lambda_grid . shape ) # The AIC score for each lambda value aicc_trace = np . zeros ( lambda_grid . shape ) # The AIC...
def _calc_percent_disk_stats ( self , stats ) : """Calculate a percentage of used disk space for data and metadata"""
mtypes = [ 'data' , 'metadata' ] percs = { } for mtype in mtypes : used = stats . get ( 'docker.{0}.used' . format ( mtype ) ) total = stats . get ( 'docker.{0}.total' . format ( mtype ) ) free = stats . get ( 'docker.{0}.free' . format ( mtype ) ) if used and total and free and ceil ( total ) < free + ...
def create ( cls , name , servers = None , time_range = 'yesterday' , all_logs = False , filter_for_delete = None , comment = None , ** kwargs ) : """Create a new delete log task . Provide True to all _ logs to delete all log types . Otherwise provide kwargs to specify each log by type of interest . : param s...
if not servers : servers = [ svr . href for svr in ManagementServer . objects . all ( ) ] servers . extend ( [ svr . href for svr in LogServer . objects . all ( ) ] ) else : servers = [ svr . href for svr in servers ] filter_for_delete = filter_for_delete . href if filter_for_delete else FilterExpression ( ...
def recheck_limits ( self ) : """Re - check that the cached limits are the current limits ."""
limit_data = self . control_daemon . get_limits ( ) try : # Get the new checksum and list of limits new_sum , new_limits = limit_data . get_limits ( self . limit_sum ) # Convert the limits list into a list of objects lims = database . limits_hydrate ( self . db , new_limits ) # Save the new data sel...
def _rook_legal_for_castle ( self , rook ) : """Decides if given rook exists , is of this color , and has not moved so it is eligible to castle . : type : rook : Rook : rtype : bool"""
return rook is not None and type ( rook ) is Rook and rook . color == self . color and not rook . has_moved
def to_dataframe ( self , extra_edges_columns = [ ] ) : """Return this network in pandas DataFrame . : return : Network as DataFrame . This is equivalent to SIF ."""
return df_util . to_dataframe ( self . session . get ( self . __url ) . json ( ) , edges_attr_cols = extra_edges_columns )
def connect_predecessors ( self , predecessors ) : """Connect all nodes in predecessors to this node ."""
for n in predecessors : self . ingoing . append ( n ) n . outgoing . append ( self )
def clear_file_systems ( self ) : """Remove references to build and source file systems , reverting to the defaults"""
self . _source_url = None self . dataset . config . library . source . url = None self . _source_fs = None self . _build_url = None self . dataset . config . library . build . url = None self . _build_fs = None self . dataset . commit ( )
def device_query_retrieve ( self , query_id , ** kwargs ) : # noqa : E501 """Retrieve a device query . # noqa : E501 Retrieve a specific device query . # noqa : E501 This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass asynchronous = True > > > thread ...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'asynchronous' ) : return self . device_query_retrieve_with_http_info ( query_id , ** kwargs ) # noqa : E501 else : ( data ) = self . device_query_retrieve_with_http_info ( query_id , ** kwargs ) # noqa : E501 return data
def policy_parameters ( self ) : """Parameters of policy"""
return it . chain ( self . policy_backbone . parameters ( ) , self . action_head . parameters ( ) )