signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def main ( ) : """Command line interface ."""
parser = argparse . ArgumentParser ( description = 'monoseq: pretty-printing DNA and protein sequences' , epilog = 'If INPUT is in FASTA format, each record is pretty-printed ' 'after printing its name and ANNOTATION (if supplied) is used by ' 'matching chromosome/record name. If INPUT contains a raw sequence, ' 'only ...
def from_dict ( cls , d ) : """Extend Field . from _ dict , set display / display _ international attributes ."""
phone = super ( cls , cls ) . from_dict ( d ) phone . display = d . get ( 'display' , u'' ) phone . display_international = d . get ( 'display_international' , u'' ) return phone
def _serial_send ( self , port , payload ) : '''Send data to connected device . Parameters port : str Device name / port . payload : bytes Payload to send to device .'''
if port not in self . open_devices : # Not connected to device . logger . error ( 'Error sending data: `%s` not connected' , port ) self . _publish_status ( port ) else : try : device = self . open_devices [ port ] device . write ( payload ) logger . debug ( 'Sent data to `%s`' , por...
def get_ips ( self , instance_id ) : """Retrieves the private and public ip addresses for a given instance . Note : Azure normally provides access to vms from a shared load balancer IP and mapping of ssh ports on the vms . So by default , the Azure provider returns strings of the form ' ip : port ' . Howe...
self . _restore_from_storage ( instance_id ) if self . _start_failed : raise Exception ( 'get_ips for node %s: failing due to' ' previous errors.' % instance_id ) ret = list ( ) v_m = self . _qualified_name_to_vm ( instance_id ) if not v_m : raise Exception ( "Can't find instance_id %s" % instance_id ) if self ...
def get_size ( ) : """- get width and height of console - works on linux , os x , windows , cygwin ( windows ) originally retrieved from : http : / / stackoverflow . com / questions / 566746 / how - to - get - console - window - width - in - python"""
current_os = platform . system ( ) tuple_xy = None if current_os == 'Windows' : tuple_xy = _get_terminal_size_windows ( ) if tuple_xy is None : tuple_xy = _get_terminal_size_tput ( ) # needed for window ' s python in cygwin ' s xterm ! if current_os in [ 'Linux' , 'Darwin' ] or current_os . star...
def all_intersections ( nodes_first , nodes_second ) : r"""Find the points of intersection among a pair of curves . . . note : : This assumes both curves are : math : ` \ mathbf { R } ^ 2 ` , but does not * * explicitly * * check this . However , functions used here will fail if that assumption fails . Ar...
# Only attempt this if the bounding boxes intersect . bbox_int = _geometric_intersection . bbox_intersect ( nodes_first , nodes_second ) if bbox_int == _DISJOINT : return np . empty ( ( 2 , 0 ) , order = "F" ) , False return intersect_curves ( nodes_first , nodes_second ) , False
def remove_declaration ( self , decl ) : """Removes declaration from members list . : param decl : declaration to be removed : type decl : : class : ` declaration _ t `"""
del self . declarations [ self . declarations . index ( decl ) ] decl . cache . reset ( )
def dispatch ( self , request , * args , ** kwargs ) : """` . dispatch ( ) ` is pretty much the same as Django ' s regular dispatch , but with extra hooks for startup , finalize , and exception handling ."""
self . args = args self . kwargs = kwargs request = self . initialize_request ( request , * args , ** kwargs ) self . request = request self . headers = self . default_response_headers # deprecate ? try : self . initial ( request , * args , ** kwargs ) # Get the appropriate handler method if request . metho...
def set_alert ( thing_name , who , condition , key , session = None ) : """Set an alert on a thing with the given condition"""
return _request ( 'get' , '/alert/{0}/when/{1}/{2}' . format ( ',' . join ( who ) , thing_name , quote ( condition ) , ) , params = { 'key' : key } , session = session )
def load ( self , filename ) : """Loads the yaml file with the given filename . : param filename : the name of the yaml file"""
self . _set_filename ( filename ) if os . path . isfile ( self [ 'location' ] ) : # d = OrderedDict ( read _ yaml _ config ( self [ ' location ' ] , check = True ) ) d = read_yaml_config ( self [ 'location' ] , check = True ) with open ( self [ 'location' ] ) as myfile : document = myfile . read ( ) ...
def _retrieve_and_validate_certificate_chain ( self , cert_url ) : # type : ( str ) - > Certificate """Retrieve and validate certificate chain . This method validates if the URL is valid and loads and validates the certificate chain , before returning it . : param cert _ url : URL for retrieving certificate c...
self . _validate_certificate_url ( cert_url ) cert_chain = self . _load_cert_chain ( cert_url ) self . _validate_cert_chain ( cert_chain ) return cert_chain
def write ( filename , data , ** kwargs ) : """Write a recarray to a specific format . Accepted file formats : [ . fits , . fz , . npy , . csv , . txt , . dat ] Parameters : filename : output file name data : the recarray data kwargs : keyword arguments for the writer Returns : ret : writer return ( u...
base , ext = os . path . splitext ( filename ) if ext in ( '.fits' , '.fz' ) : # Abstract fits here . . . return fitsio . write ( filename , data , ** kwargs ) elif ext in ( '.npy' ) : return np . save ( filename , data , ** kwargs ) elif ext in ( '.csv' ) : return np . savetxt ( filename , data , header = ...
def _ReadTablesArray ( self , file_object , tables_array_offset ) : """Reads the tables array . Args : file _ object ( file ) : file - like object . tables _ array _ offset ( int ) : offset of the tables array relative to the start of the file . Returns : dict [ int , KeychainDatabaseTable ] : tables pe...
# TODO : implement https : / / github . com / libyal / dtfabric / issues / 12 and update # keychain _ tables _ array definition . data_type_map = self . _GetDataTypeMap ( 'keychain_tables_array' ) tables_array , _ = self . _ReadStructureFromFileObject ( file_object , tables_array_offset , data_type_map ) tables = colle...
def side_effect_as_string ( * args ) : '''side _ effect _ as _ string ( ) - > " ANY _ FUNCTION ( ANY _ ARGS , ANY _ KWARGS ) " side _ effect _ as _ string ( " foo " ) - > " foo ( ANY _ ARGS , ANY _ KWARGS ) " side _ effect _ as _ string ( " foo " , ( 42 , ) ) - > " foo ( 42 , ANY _ KWARGS ) " side _ effect _ ...
fun_id = "ANY_FUNCTION" se_args = None se_kwargs = None if len ( args ) > 0 : fun_id = args [ 0 ] or "ANY_FUNCTION" if len ( args ) > 1 : se_args = args [ 1 ] if len ( args ) > 2 : se_kwargs = args [ 2 ] if se_args is None : args_desc = [ "ANY_ARGS" ] elif isinstance ( se_args , tuple ) : args_desc ...
def get_db_driver ( uri , username = None , password = None , encrypted = True , max_pool_size = 50 , trust = 0 ) : """: param uri : Bolt uri : type uri : str : param username : Neo4j username : type username : str : param password : Neo4j password : type password : str : param encrypted : Use TLS : t...
return GraphDatabase . driver ( uri , auth = basic_auth ( username , password ) , encrypted = encrypted , max_pool_size = max_pool_size , trust = trust )
def _copy_convert ( X , const = None , remove_mean = False , copy = True ) : r"""Makes a copy or converts the data type if needed Copies the data and converts the data type if unsuitable for covariance calculation . The standard data type for covariance computations is float64 , because the double precision (...
# determine type dtype = np . float64 # default : convert to float64 in order to avoid cancellation errors if X . dtype . kind == 'b' and X . shape [ 0 ] < 2 ** 23 and not remove_mean : dtype = np . float32 # convert to float32 if we can represent all numbers # copy / convert if needed if X . dtype not in ( np ...
def human_and_01 ( X , y , model_generator , method_name ) : """AND ( false / true ) This tests how well a feature attribution method agrees with human intuition for an AND operation combined with linear effects . This metric deals specifically with the question of credit allocation for the following function...
return _human_and ( X , model_generator , method_name , False , True )
def do_trace ( self , arg ) : """t - trace at the current assembly instruction trace - trace at the current assembly instruction"""
if arg : # XXX this check is to be removed raise CmdError ( "too many arguments" ) if self . lastEvent is None : raise CmdError ( "no current thread set" ) self . lastEvent . get_thread ( ) . set_tf ( ) return True
def save_plain_image_as_file ( self , filepath , format = 'png' , quality = 90 ) : """Used for generating thumbnails . Does not include overlaid graphics ."""
pixbuf = self . get_plain_image_as_pixbuf ( ) options , values = [ ] , [ ] if format == 'jpeg' : options . append ( 'quality' ) values . append ( str ( quality ) ) pixbuf . savev ( filepath , format , options , values )
async def vcx_messages_download ( status : str = None , uids : str = None , pw_dids : str = None ) -> str : """Retrieve messages from the specified connection : param status : : param uids : : param pw _ dids : : return :"""
logger = logging . getLogger ( __name__ ) if not hasattr ( vcx_messages_download , "cb" ) : logger . debug ( "vcx_messages_download: Creating callback" ) vcx_messages_download . cb = create_cb ( CFUNCTYPE ( None , c_uint32 , c_uint32 , c_char_p ) ) if status : c_status = c_char_p ( status . encode ( 'utf-8'...
def _list_variables ( self , station_codes ) : """Internal helper to list the variables for the given station codes ."""
# sample output from obs retrieval : # DD9452D0 # HP ( SRBM5) # 2013-07-22 19:30 45.97 # HT ( SRBM5) # 2013-07-22 19:30 44.29 # PC ( SRBM5) # 2013-07-22 19:30 36.19 rvar = re . compile ( r"\n\s([A-Z]{2}[A-Z0-9]{0,1})\(\w+\)" ) variables = set ( ) resp = requests . post ( self . obs_retrieval_url , data = { "state" : "n...
def build_markdown_table ( headers , rows , row_keys = None ) : """Build a lined up markdown table . Args : headers ( dict ) : A key - > value pairing fo the headers . rows ( list ) : List of dictionaries that contain all the keys listed in the headers . row _ keys ( list ) : A sorted list of keys to disp...
row_maxes = _find_row_maxes ( headers , rows ) row_keys = row_keys or [ key for key , value in headers . items ( ) ] table = [ _build_row ( headers , row_maxes , row_keys ) , _build_separator ( row_maxes , row_keys ) ] for row in rows : table . append ( _build_row ( row , row_maxes , row_keys ) ) return '\n' . join...
def senqueue ( trg_queue , item_s , * args , ** kwargs ) : '''Enqueue a string , or string - like object to queue with arbitrary arguments , senqueue is to enqueue what sprintf is to printf , senqueue is to vsenqueue what sprintf is to vsprintf .'''
return vsenqueue ( trg_queue , item_s , args , ** kwargs )
def create ( self , remove_all_rc_files = False ) : """Create default configuration files at either the default location or the given directory ."""
# Check and create configuration directory if os . path . exists ( self . config_dir ) : self . LOG . debug ( "Configuration directory %r already exists!" % ( self . config_dir , ) ) else : os . mkdir ( self . config_dir ) if remove_all_rc_files : for subdir in ( '.' , 'rtorrent.d' ) : config_files ...
def proximal_gradient ( x , f , g , gamma , niter , callback = None , ** kwargs ) : r"""( Accelerated ) proximal gradient algorithm for convex optimization . Also known as " Iterative Soft - Thresholding Algorithm " ( ISTA ) . See ` [ Beck2009 ] ` _ for more information . This solver solves the convex optimiz...
# Get and validate input if x not in f . domain : raise TypeError ( '`x` {!r} is not in the domain of `f` {!r}' '' . format ( x , f . domain ) ) if x not in g . domain : raise TypeError ( '`x` {!r} is not in the domain of `g` {!r}' '' . format ( x , g . domain ) ) gamma , gamma_in = float ( gamma ) , gamma if g...
def create_input_fn ( prefix , batch_size , augmentation = None ) : """Loads a dataset . : param prefix : The path prefix as defined in the write data method . : param batch _ size : The batch size you want for the tensors . : param augmentation : An augmentation function . : return : An input function for ...
# Check if the version is too old for dataset api to work better than manually loading data . if tf . __version__ . startswith ( "1.6" ) or tf . __version__ . startswith ( "1.5" ) or tf . __version__ . startswith ( "1.4" ) or tf . __version__ . startswith ( "1.3" ) or tf . __version__ . startswith ( "1.2" ) or tf . __v...
def wait_until_element_contains_text ( self , element , text , timeout = None ) : """Search element and wait until it contains the expected text : param element : PageElement or element locator as a tuple ( locator _ type , locator _ value ) to be found : param text : text expected to be contained into the elem...
return self . _wait_until ( self . _expected_condition_find_element_containing_text , ( element , text ) , timeout )
def normalize ( text , mode = 'NFKC' , ignore = '' ) : """Convert Half - width ( Hankaku ) Katakana to Full - width ( Zenkaku ) Katakana , Full - width ( Zenkaku ) ASCII and DIGIT to Half - width ( Hankaku ) ASCII and DIGIT . Additionally , Full - width wave dash ( 〜 ) etc . are normalized Parameters text...
text = text . replace ( '〜' , 'ー' ) . replace ( '~' , 'ー' ) text = text . replace ( "’" , "'" ) . replace ( '”' , '"' ) . replace ( '“' , '``' ) text = text . replace ( '―' , '-' ) . replace ( '‐' , '-' ) . replace ( '˗' , '-' ) . replace ( '֊' , '-' ) text = text . replace ( '‐' , '-' ) . replace ( '‑' , '-' ) . repla...
def to_array ( self , channels = 2 ) : """Return the array of multipliers for the dynamic"""
if channels == 1 : return self . volume_frames . reshape ( - 1 , 1 ) if channels == 2 : return np . tile ( self . volume_frames , ( 2 , 1 ) ) . T raise Exception ( "RawVolume doesn't know what to do with %s channels" % channels )
def get_QApplication ( args = [ ] ) : """Returns the QApplication instance , creating it is does not yet exist ."""
global _qapp if _qapp is None : QCoreApplication . setAttribute ( Qt . AA_X11InitThreads ) _qapp = QApplication ( args ) return _qapp
def connection ( self ) : """A property to retrieve the sampler connection information ."""
return { 'host' : self . host , 'namespace' : self . namespace , 'username' : self . username , 'password' : self . password }
def read_file ( filename ) : """Reads the lines of a file into a list , and returns the list : param filename : String - path and name of the file : return : List - lines within the file"""
lines = [ ] with open ( filename ) as f : for line in f : if len ( line . strip ( ) ) != 0 : lines . append ( line . strip ( ) ) return lines
def setup_config ( self , cfg = None ) : '''Open suitable config file . : return :'''
_opts , _args = optparse . OptionParser . parse_args ( self ) configs = self . find_existing_configs ( _opts . support_unit ) if configs and cfg not in configs : cfg = configs [ 0 ] return config . master_config ( self . get_config_file_path ( cfg ) )
def ctor ( self , name , func , * args , ** kwargs ) : '''Add a constructor to be called when a specific property is not present . Example : scope . ctor ( ' foo ' , FooThing ) foo = scope . get ( ' foo ' )'''
self . ctors [ name ] = ( func , args , kwargs )
def extend ( self , other ) : """See list . extend ."""
index = len ( self ) length = 0 for length , element in enumerate ( other , 1 ) : super ( ObservableList , self ) . append ( element ) if length : self . _notify_add_at ( index , length )
def process_unknown_arguments ( unknowns ) : """Process arguments unknown to the parser"""
result = argparse . Namespace ( ) result . extra_control = { } # It would be interesting to use argparse internal # machinery for this for unknown in unknowns : # Check prefixes prefix = '--parameter-' if unknown . startswith ( prefix ) : # process ' = ' values = unknown . split ( '=' ) if len (...
def choropleth ( df , projection = None , hue = None , scheme = None , k = 5 , cmap = 'Set1' , categorical = False , vmin = None , vmax = None , legend = False , legend_kwargs = None , legend_labels = None , extent = None , figsize = ( 8 , 6 ) , ax = None , ** kwargs ) : """Area aggregation plot . Parameters df...
# Initialize the figure . fig = _init_figure ( ax , figsize ) if projection : projection = projection . load ( df , { 'central_longitude' : lambda df : np . mean ( np . array ( [ p . x for p in df . geometry . centroid ] ) ) , 'central_latitude' : lambda df : np . mean ( np . array ( [ p . y for p in df . geometry ...
def colors_like ( color , arr , colormap = DEFAULT_COLORMAP ) : '''Given an array of size NxM ( usually Nx3 ) , we accept color in the following ways : - A string color name . The accepted names are roughly what ' s in X11 ' s rgb . txt - An explicit rgb triple , in ( 3 , ) , ( 3 , 1 ) , or ( 1 , 3 ) shape - ...
import numpy as np from blmath . numerics import is_empty_arraylike if is_empty_arraylike ( color ) : return None if isinstance ( color , basestring ) : from lace . color_names import name_to_rgb color = name_to_rgb [ color ] elif isinstance ( color , list ) : color = np . array ( color ) color = np . s...
def max_occuring_divisor ( start : int , end : int ) -> int : """Python function designed to identify the divisor with the highest occurrence within a given range . Args : start : Starting point of the range . end : End point of the range . Returns : Maximum occurring divisor within the given interval . ...
if start == end : return end return 2
def create_animation ( img_files ) : """See http : / / pillow . readthedocs . io / en / 4.2 . x / handbook / image - file - formats . html ? highlight = append _ images # saving"""
open_images = [ ] for fn in img_files : print ( fn ) im = Image . open ( fn ) open_images . append ( im ) im = open_images [ 0 ] im . save ( r"C:\temp\animation.gif" , save_all = True , append_images = open_images [ 1 : ] , duration = 120 , loop = 100 , optimize = True )
def _get_query_zone_id ( self ) : """Returns the ZoneId for performing queries of a Predix Time Series instance from environment inspection ."""
if 'VCAP_SERVICES' in os . environ : services = json . loads ( os . getenv ( 'VCAP_SERVICES' ) ) predix_timeseries = services [ 'predix-timeseries' ] [ 0 ] [ 'credentials' ] return predix_timeseries [ 'query' ] [ 'zone-http-header-value' ] else : return predix . config . get_env_value ( self , 'query_zo...
def urls ( self ) : """: return : Iterator yielding all configured URL targets on a remote as strings"""
try : remote_details = self . repo . git . remote ( "get-url" , "--all" , self . name ) for line in remote_details . split ( '\n' ) : yield line except GitCommandError as ex : # # We are on git < 2.7 ( i . e TravisCI as of Oct - 2016 ) , # so ` get - utl ` command does not exist yet ! # see : https : / ...
def render ( self , path , width = 1024 , height = 1024 ) : """Renders the current page to a PNG file ( viewport size in pixels ) ."""
self . conn . issue_command ( "Render" , path , width , height )
def get_order_specification_visitor ( name , registry = None ) : """Returns the class registered as the order specification visitor utility under the given name ( one of the : const : ` everest . querying . base . EXPRESSION _ KINDS ` constants ) . : returns : class implementing : class : ` everest . interf...
if registry is None : registry = get_current_registry ( ) return registry . getUtility ( IOrderSpecificationVisitor , name = name )
def filter ( self , f , operator = "and" ) : """Add a filter to the query Takes a Filter object , or a filterable DSL object ."""
if self . _filtered : self . _filter_dsl . filter ( f ) else : self . _build_filtered_query ( f , operator ) return self
def keywords ( self ) : """Returns a list of all keywords that this rule object has defined . A keyword is considered defined if the value it returns ! = None ."""
defined_keywords = [ ( 'allowempty_map' , 'allowempty_map' ) , ( 'assertion' , 'assertion' ) , ( 'default' , 'default' ) , ( 'class' , 'class' ) , ( 'desc' , 'desc' ) , ( 'enum' , 'enum' ) , ( 'example' , 'example' ) , ( 'extensions' , 'extensions' ) , ( 'format' , 'format' ) , ( 'func' , 'func' ) , ( 'ident' , 'ident'...
def check_status_logfile ( self , checker_func ) : """Check on the status of this particular job using the logfile"""
self . status = checker_func ( self . logfile ) return self . status
def edit ( self , name = None , description = github . GithubObject . NotSet , homepage = github . GithubObject . NotSet , private = github . GithubObject . NotSet , has_issues = github . GithubObject . NotSet , has_projects = github . GithubObject . NotSet , has_wiki = github . GithubObject . NotSet , has_downloads = ...
if name is None : name = self . name assert isinstance ( name , ( str , unicode ) ) , name assert description is github . GithubObject . NotSet or isinstance ( description , ( str , unicode ) ) , description assert homepage is github . GithubObject . NotSet or isinstance ( homepage , ( str , unicode ) ) , homepage ...
def find_package_data ( packages ) : """For a list of packages , find the package _ data This function scans the subdirectories of a package and considers all non - submodule subdirectories as resources , including them in the package _ data Returns a dictionary suitable for setup ( package _ data = < resul...
package_data = { } for package in packages : package_data [ package ] = [ ] for subdir in find_subdirectories ( package ) : if '.' . join ( ( package , subdir ) ) in packages : # skip submodules logging . debug ( "skipping submodule %s/%s" % ( package , subdir ) ) continue ...
def get_jids ( ) : '''Return a list of all job ids'''
with _get_serv ( ret = None , commit = True ) as cur : sql = '''SELECT jid, load FROM jids''' cur . execute ( sql ) data = cur . fetchall ( ) ret = { } for jid , load in data : ret [ jid ] = salt . utils . jid . format_jid_instance ( jid , salt . utils . json . loads ( load )...
def _feature_to_fields ( f , jsonify = True ) : """Convert feature to tuple , for faster sqlite3 import"""
x = [ ] for k in constants . _keys : v = getattr ( f , k ) if jsonify and ( k in ( 'attributes' , 'extra' ) ) : x . append ( _jsonify ( v ) ) else : x . append ( v ) return tuple ( x )
def on_new ( self , button ) : '''Copy selected notebook template to notebook directory . # # Notes # # - An exception is raised if the parent of the selected file is the notebook directory . - If notebook with same name already exists in notebook directory , offer is made to overwrite ( the new copy of t...
buttons = ( gtk . STOCK_CANCEL , gtk . RESPONSE_CANCEL , gtk . STOCK_OPEN , gtk . RESPONSE_OK ) dialog = gtk . FileChooserDialog ( "Select notebook template" , self . parent , gtk . FILE_CHOOSER_ACTION_OPEN , buttons ) add_filters ( dialog , [ { 'name' : 'Jupyter notebook (*.ipynb)' , 'pattern' : '*.ipynb' } ] ) if sel...
def getDatastreamHistory ( self , pid , dsid , format = None ) : '''Get history information for a datastream . : param pid : object pid : param dsid : datastream id : param format : format : rtype : : class : ` requests . models . Response `'''
http_args = { } if format is not None : http_args [ 'format' ] = format # Fedora docs say the url should be : # / objects / { pid } / datastreams / { dsid } / versions # In Fedora 3.4.3 , that 404s but / history does not uri = 'objects/%(pid)s/datastreams/%(dsid)s/history' % { 'pid' : pid , 'dsid' : dsid } return s...
def ExcludePathsFromIndex ( client , database_id ) : """The default behavior is for Cosmos to index every attribute in every document automatically . There are times when a document contains large amounts of information , in deeply nested structures that you know you will never search on . In extreme cases like...
try : DeleteContainerIfExists ( client , database_id , COLLECTION_ID ) database_link = GetDatabaseLink ( database_id ) # collections = Query _ Entities ( client , ' collection ' , parent _ link = database _ link ) # print ( collections ) doc_with_nested_structures = { "id" : "doc1" , "foo" : "bar" ,...
def _proxy ( self ) : """Generate an instance context for the instance , the context is capable of performing various actions . All instance actions are proxied to the context : returns : ChannelContext for this ChannelInstance : rtype : twilio . rest . chat . v1 . service . channel . ChannelContext"""
if self . _context is None : self . _context = ChannelContext ( self . _version , service_sid = self . _solution [ 'service_sid' ] , sid = self . _solution [ 'sid' ] , ) return self . _context
def getContext ( self ) : """Create an SSL context with a dodgy certificate ."""
ctx = SSL . Context ( SSL . SSLv23_METHOD ) ctx . use_certificate_file ( 'server.pem' ) ctx . use_privatekey_file ( 'server.pem' ) return ctx
def to_struct ( self , value ) : """Cast ` time ` object to string ."""
if self . str_format : return value . strftime ( self . str_format ) return value . isoformat ( )
def parse ( self ) : """parse the data"""
# convert the xlsx file to csv first delimiter = "|" csv_file = self . xlsx_to_csv ( self . getInputFile ( ) , delimiter = delimiter ) reader = csv . DictReader ( csv_file , delimiter = delimiter ) for n , row in enumerate ( reader ) : resid = row . get ( "SampleID" , None ) serial = row . get ( "SerialNumber" ...
def exclude_by_ends ( in_file , exclude_file , data , in_params = None ) : """Exclude calls based on overlap of the ends with exclusion regions . Removes structural variants with either end being in a repeat : a large source of false positives . Parameters tuned based on removal of LCR overlapping false posit...
params = { "end_buffer" : 50 , "rpt_pct" : 0.9 , "total_rpt_pct" : 0.2 , "sv_pct" : 0.5 } if in_params : params . update ( in_params ) assert in_file . endswith ( ".bed" ) out_file = "%s-norepeats%s" % utils . splitext_plus ( in_file ) to_filter = collections . defaultdict ( list ) removed = 0 if not utils . file_u...
def add_request_ids_from_environment ( logger , name , event_dict ) : """Custom processor adding request IDs to the log event , if available ."""
if ENV_APIG_REQUEST_ID in os . environ : event_dict [ 'api_request_id' ] = os . environ [ ENV_APIG_REQUEST_ID ] if ENV_LAMBDA_REQUEST_ID in os . environ : event_dict [ 'lambda_request_id' ] = os . environ [ ENV_LAMBDA_REQUEST_ID ] return event_dict
def competence ( s ) : """The competence function for MatrixMetropolis"""
# MatrixMetropolis handles the Wishart family , which are valued as # _ symmetric _ matrices . if any ( [ isinstance ( s , cls ) for cls in [ distributions . Wishart , distributions . WishartCov ] ] ) : return 2 else : return 0
def get_data ( start , end , username = None , password = None , data_path = os . path . abspath ( "." ) + '/tmp_data' ) : """* * Download data ( badly ) from Blitzorg * * Using a specified time stamp for start and end , data is downloaded at a default frequency ( 10 minute intervals ) . If a directory called d...
dl_link = "http://data.blitzortung.org/Data_1/Protected/Strokes/" if not os . path . exists ( data_path ) : os . makedirs ( data_path ) if not username : username = input ( "Username to access Blitzorg with:" ) password = getpass . getpass ( prompt = 'Enter password for {0}:' . format ( username ) ) auth_ha...
def flux_minimization ( model , fixed , solver , weights = { } ) : """Minimize flux of all reactions while keeping certain fluxes fixed . The fixed reactions are given in a dictionary as reaction id to value mapping . The weighted L1 - norm of the fluxes is minimized . Args : model : MetabolicModel to solve...
fba = FluxBalanceProblem ( model , solver ) for reaction_id , value in iteritems ( fixed ) : flux = fba . get_flux_var ( reaction_id ) fba . prob . add_linear_constraints ( flux >= value ) fba . minimize_l1 ( ) return ( ( reaction_id , fba . get_flux ( reaction_id ) ) for reaction_id in model . reactions )
def get ( self , key , index = None ) : """Retrieves a value associated with a key from the database Args : key ( str ) : The key to retrieve"""
records = self . get_multi ( [ key ] , index = index ) try : return records [ 0 ] [ 1 ] # return the value from the key / value tuple except IndexError : return None
def soft_hard ( self , value ) : """sets the Soft or Hard range setting ( with validation of input )"""
if not isinstance ( value , RangeCheckType ) : raise AttributeError ( "%s soft_hard invalid in RangeCheck." % ( value , ) ) self . _soft_hard = value
def get_max_bitlen ( self ) : """Returns total maximum bit length of the array , including length field if applicable ."""
payload_max_bitlen = self . max_size * self . value_type . get_max_bitlen ( ) return { self . MODE_DYNAMIC : payload_max_bitlen + self . max_size . bit_length ( ) , self . MODE_STATIC : payload_max_bitlen } [ self . mode ]
def remapMutations ( self , mutations , pdbID = '?' ) : '''Takes in a list of ( Chain , ResidueID , WildTypeAA , MutantAA ) mutation tuples and returns the remapped mutations based on the ddGResmap ( which must be previously instantiated ) . This function checks that the mutated positions exist and that the wil...
raise Exception ( 'This code is deprecated. Please use map_pdb_residues_to_rosetta_residues instead.' ) remappedMutations = [ ] ddGResmap = self . get_ddGResmap ( ) for m in mutations : ns = ( PDB . ChainResidueID2String ( m [ 'Chain' ] , str ( ddGResmap [ 'ATOM-%s' % PDB . ChainResidueID2String ( m [ 'Chain' ] , m...
def get_nav_menu ( self ) : """Method to generate the menu"""
_menu = self . get_site_menu ( ) if _menu : site_menu = list ( _menu ) else : site_menu = [ ] had_urls = [ ] def get_url ( menu , had_urls ) : if 'url' in menu : had_urls . append ( menu [ 'url' ] ) if 'menus' in menu : for m in menu [ 'menus' ] : get_url ( m , had_urls ) get...
def coderef_to_ecoclass ( self , code , reference = None ) : """Map a GAF code to an ECO class Arguments code : str GAF evidence code , e . g . ISS , IDA reference : str CURIE for a reference for the evidence instance . E . g . GO _ REF : 000001. Optional - If provided can give a mapping to a more speci...
mcls = None for ( this_code , this_ref , cls ) in self . mappings ( ) : if str ( this_code ) == str ( code ) : if this_ref == reference : return cls if this_ref is None : mcls = cls return mcls
def upload ( self ) : '''* Check if project already exists * if it doesn ' t , then create it * stage a new revision * upload * commit revision'''
if not self . exists ( ) : self . create ( ) data = self . stage ( ) . json ( ) self . file_upload ( data [ 'post_url' ] , data ) res = self . commit ( data [ 'dist_id' ] ) data = res . json ( ) return data
def get_authorization_query_session ( self ) : """Gets the ` ` OsidSession ` ` associated with the authorization query service . return : ( osid . authorization . AuthorizationQuerySession ) - an ` ` AuthorizationQuerySession ` ` raise : OperationFailed - unable to complete request raise : Unimplemented - `...
if not self . supports_authorization_query ( ) : raise errors . Unimplemented ( ) # pylint : disable = no - member return sessions . AuthorizationQuerySession ( runtime = self . _runtime )
def new_cipher ( self , key , mode_iv , digest = None ) : """@ param key : the secret key , a byte string @ param mode _ iv : the initialization vector or nonce , a byte string . Formatted by ` format _ mode _ iv ` . @ param digest : also known as tag or icv . A byte string containing the digest of the encr...
if self . is_aead and digest is not None : # With AEAD , the mode needs the digest during decryption . return Cipher ( self . cipher ( key ) , self . mode ( mode_iv , digest , len ( digest ) ) , default_backend ( ) , ) else : return Cipher ( self . cipher ( key ) , self . mode ( mode_iv ) , default_backend ( ) ...
def adjust_for_scratch ( self ) : """Remove certain plugins in order to handle the " scratch build " scenario . Scratch builds must not affect subsequent builds , and should not be imported into Koji ."""
if self . scratch : self . template [ 'spec' ] . pop ( 'triggers' , None ) remove_plugins = [ ( "prebuild_plugins" , "koji_parent" ) , ( "postbuild_plugins" , "compress" ) , # required only to make an archive for Koji ( "postbuild_plugins" , "pulp_pull" ) , # required only to make an archive for Koji ( ...
def list ( self , path , filename = None , start = None , stop = None , recursive = False , directories = False ) : """List objects specified by path . Returns sorted list of ' gs : / / ' or ' s3n : / / ' URIs ."""
storageScheme , keys = self . getkeys ( path , filename = filename , directories = directories , recursive = recursive ) keys = [ storageScheme + ":///" + key . bucket . name + "/" + key . name for key in keys ] keys . sort ( ) keys = select ( keys , start , stop ) return keys
def _constant_probability_density ( self , X ) : """Probability density for the degenerate case of constant distribution . Note that the output of this method will be an array whose unique values are 0 and 1. More information can be found here : https : / / en . wikipedia . org / wiki / Degenerate _ distributio...
result = np . zeros ( X . shape ) result [ np . nonzero ( X == self . constant_value ) ] = 1 return result
def run_task ( self , task , source_patterns = None ) : """Walk source and initiate spell check ."""
# Perform spell check self . log ( 'Running Task: %s...' % task . get ( 'name' , '' ) , 1 ) # Setup filters and variables for the spell check self . default_encoding = task . get ( 'default_encoding' , '' ) options = self . setup_spellchecker ( task ) personal_dict = self . setup_dictionary ( task ) glob_flags = self ....
def manipulate ( self , stored_instance , component_instance ) : """Stores the given StoredInstance bean . : param stored _ instance : The iPOPO component StoredInstance : param component _ instance : The component instance"""
# Store the stored instance . . . self . _ipopo_instance = stored_instance # . . . and the bundle context self . _context = stored_instance . bundle_context # Set the default value for the field : an empty dictionary setattr ( component_instance , self . _field , { } )
def get_assessments_offered ( self ) : """Gets all ` ` AssessmentOffered ` ` elements . In plenary mode , the returned list contains all known assessments offered or an error results . Otherwise , the returned list may contain only those assessments offered that are accessible through this session . retur...
# Implemented from template for # osid . resource . ResourceLookupSession . get _ resources # NOTE : This implementation currently ignores plenary view collection = JSONClientValidated ( 'assessment' , collection = 'AssessmentOffered' , runtime = self . _runtime ) result = collection . find ( self . _view_filter ( ) ) ...
def connect ( self ) : """Connect to the Redis server or Cluster . : rtype : tornado . concurrent . Future"""
LOGGER . debug ( 'Creating a%s connection to %s:%s (db %s)' , ' cluster node' if self . _clustering else '' , self . _hosts [ 0 ] [ 'host' ] , self . _hosts [ 0 ] [ 'port' ] , self . _hosts [ 0 ] . get ( 'db' , DEFAULT_DB ) ) self . _connect_future = concurrent . Future ( ) conn = _Connection ( self . _hosts [ 0 ] [ 'h...
def connect ( self , server , port , nickname , password = None , username = None , ircname = None , connect_factory = connection . Factory ( ) ) : """Connect / reconnect to a server . Arguments : * server - Server name * port - Port number * nickname - The nickname * password - Password ( if any ) * us...
log . debug ( "connect(server=%r, port=%r, nickname=%r, ...)" , server , port , nickname ) if self . connected : self . disconnect ( "Changing servers" ) self . buffer = self . buffer_class ( ) self . handlers = { } self . real_server_name = "" self . real_nickname = nickname self . server = server self . port = po...
def prt_hdr ( self , prt = sys . stdout , name = "name " ) : """Print stats header in markdown style ."""
hdr = "{NAME} | # {ITEMS:11} | range | 25th percentile | " " median | 75th percentile | mean | stddev\n" . format ( NAME = name , ITEMS = self . desc ) div = "{DASHES}|---------------|----------------------|" "-----------------|----------|-----------------|----------|-------\n" . format ( DASHES = '...
def integer_based_slice ( self , ts ) : """Transform a : class : ` TimeSlice ` into integer indices that numpy can work with Args : ts ( slice , TimeSlice ) : the time slice to translate into integer indices"""
if isinstance ( ts , slice ) : try : start = Seconds ( 0 ) if ts . start is None else ts . start if start < Seconds ( 0 ) : start = self . end + start stop = self . end if ts . stop is None else ts . stop if stop < Seconds ( 0 ) : stop = self . end + stop ...
def write_tables ( tables , path , column_styles = None , cell_styles = None , tables_fields = None , tables_names = None ) : """Exporta un reporte con varias tablas en CSV o XLSX . Si la extensión es " . csv " se crean varias tablas agregando el nombre de la tabla al final del " path " . Si la extensión es "...
assert isinstance ( path , string_types ) , "`path` debe ser un string" assert isinstance ( tables , dict ) , "`table` es dict de listas de dicts" # Deduzco el formato de archivo de ` path ` y redirijo según corresponda . suffix = path . split ( "." ) [ - 1 ] if suffix == "csv" : for table_name , table in tables :...
def transaction_write ( self , items , client_request_token ) : """Wraps : func : ` boto3 . DynamoDB . Client . db . transact _ write _ items ` . : param items : Unpacked into " TransactionItems " for : func : ` boto3 . DynamoDB . Client . transact _ write _ items ` : param client _ request _ token : Idempotenc...
try : self . dynamodb_client . transact_write_items ( TransactItems = items , ClientRequestToken = client_request_token ) except botocore . exceptions . ClientError as error : if error . response [ "Error" ] [ "Code" ] == "TransactionCanceledException" : raise TransactionCanceled from error raise Bl...
def create_coupon ( self , currency , amount , receiver ) : """This method allows you to create Coupons . Please , note : In order to use this method , you need the Coupon key privilege . You can make a request to enable it by submitting a ticket to Support . . You need to create the API key that you are goin...
return self . _trade_api_call ( 'CreateCoupon' , currency = currency , amount = amount , receiver = receiver )
def limit ( self , n ) : """Enforces the Stream to finish after ` ` n ` ` items ."""
data = self . _data self . _data = ( next ( data ) for _ in xrange ( int ( round ( n ) ) ) ) return self
def query_keyword ( ) : """Returns list of keywords linked to entries by query parameters tags : - Query functions parameters : - name : name in : query type : string required : false description : Disease identifier default : ' Ubl conjugation ' - name : identifier in : query type : string ...
args = get_args ( request_args = request . args , allowed_str_args = [ 'name' , 'identifier' , 'entry_name' ] , allowed_int_args = [ 'limit' ] ) print ( args ) return jsonify ( query . keyword ( ** args ) )
def _xml_to_dict ( xml_to_convert ) : """Convert RAW XML string to Python dict : param xml _ to _ convert : XML to convert ( string / text ) : return : Python dict with all XML data"""
logger . debug ( "Converting to Python dict this XML: " + str ( xml_to_convert ) ) return xmltodict . parse ( xml_to_convert , attr_prefix = '' )
def storage_p_soc ( network , mean = '1H' , filename = None ) : """Plots the dispatch and state of charge ( SOC ) of extendable storages . Parameters network : PyPSA network container Holds topology of grid including results from powerflow analysis mean : str Defines over how many snapshots the p and soc ...
sbatt = network . storage_units . index [ ( network . storage_units . p_nom_opt > 1 ) & ( network . storage_units . capital_cost > 10 ) & ( network . storage_units . max_hours == 6 ) ] shydr = network . storage_units . index [ ( network . storage_units . p_nom_opt > 1 ) & ( network . storage_units . capital_cost > 10 )...
def get_content_items ( access_token , limit , page ) : '''Name : get _ content _ items Parameters : access _ token , limit ( optional ) , page ( optional ) Return : dictionary'''
headers = { 'Authorization' : 'Bearer ' + str ( access_token ) } content_items_url = construct_content_items_url ( enrichment_url , limit , page ) request = requests . get ( content_items_url , headers = headers ) if request . status_code == 200 : content_item = request . json ( ) return content_item return { '...
def _scatter ( self ) : """plot a scatter plot of count vs . elapsed . For internal use only"""
plt . scatter ( self . count_arr , self . elapsed_arr ) plt . title ( '{}: Count vs. Elapsed' . format ( self . name ) ) plt . xlabel ( 'Items' ) plt . ylabel ( 'Seconds' )
def clean ( self ) : """Remove services without host object linked to Note that this should not happen ! : return : None"""
to_del = [ ] for serv in self : if not serv . host : to_del . append ( serv . uuid ) for service_uuid in to_del : del self . items [ service_uuid ]
def pop_event ( self ) : '''Pop the next queued event from the queue . : raise ValueError : If there is no event queued .'''
with self . lock : if not self . events : raise ValueError ( 'no events queued' ) return self . events . popleft ( )
def dread ( infile , cols ) : """reads in specimen , tr , dec , inc int into data [ ] . position of tr , dec , inc , int determined by cols [ ]"""
data = [ ] f = open ( infile , "r" ) for line in f . readlines ( ) : tmp = line . split ( ) rec = ( tmp [ 0 ] , float ( tmp [ cols [ 0 ] ] ) , float ( tmp [ cols [ 1 ] ] ) , float ( tmp [ cols [ 2 ] ] ) , float ( tmp [ cols [ 3 ] ] ) ) data . append ( rec ) f . close ( ) return data
def is_running ( conn , args ) : """Run a command to check the status of a mon , return a boolean . We heavily depend on the format of the output , if that ever changes we need to modify this . Check daemon status for 3 times output of the status should be similar to : : mon . mira094 : running { " versio...
stdout , stderr , _ = remoto . process . check ( conn , args ) result_string = b' ' . join ( stdout ) for run_check in [ b': running' , b' start/running' ] : if run_check in result_string : return True return False
async def request_status ( self , status_link ) : """Do a simple GET to this status link . This method re - inject ' x - ms - client - request - id ' . : rtype : requests . Response"""
# ARM requires to re - inject ' x - ms - client - request - id ' while polling header_parameters = { 'x-ms-client-request-id' : self . _operation . initial_response . request . headers [ 'x-ms-client-request-id' ] } request = self . _client . get ( status_link , headers = header_parameters ) return await self . _client...
def load ( filename ) : """Load a pickled database . Return a Database instance ."""
file = open ( filename , 'rb' ) container = std_pickle . load ( file ) file . close ( ) db = Database ( file . name ) chains = 0 funs = set ( ) for k , v in six . iteritems ( container ) : if k == '_state_' : db . _state_ = v else : db . _traces [ k ] = Trace ( name = k , value = v , db = db ) ...
def _add_to_docstring ( string ) : '''Private wrapper function . Appends ` ` string ` ` to the docstring of the wrapped function .'''
def wrapper ( method ) : if method . __doc__ is not None : method . __doc__ += string else : method . __doc__ = string return method return wrapper
def quit ( self ) : """Restore previous stdout / stderr and destroy the window ."""
sys . stdout = self . _oldstdout sys . stderr = self . _oldstderr self . destroy ( )
def updateBeforeDecorator ( function ) : """Function updateAfterDecorator Decorator to ensure local dict is sync with remote foreman"""
def _updateBeforeDecorator ( self , * args , ** kwargs ) : if self . forceFullSync : self . reload ( ) return function ( self , * args , ** kwargs ) return _updateBeforeDecorator