signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def set_json_converters ( encode , decode ) : """Modify the default JSON conversion functions . This affects all : class : ` ~ couchbase . bucket . Bucket ` instances . These functions will called instead of the default ones ( ` ` json . dumps ` ` and ` ` json . loads ` ` ) to encode and decode JSON ( when : ...
ret = _LCB . _modify_helpers ( json_encode = encode , json_decode = decode ) return ( ret [ 'json_encode' ] , ret [ 'json_decode' ] )
def ic_pos ( self , row1 , row2 = None ) : """Calculate the information content of one position . Returns score : float Information content ."""
if row2 is None : row2 = [ 0.25 , 0.25 , 0.25 , 0.25 ] score = 0 for a , b in zip ( row1 , row2 ) : if a > 0 : score += a * log ( a / b ) / log ( 2 ) return score
def build ( self , callable : Callable ) -> Callable [ ... , CaptureResult ] : """Build a method that captures the required information when the given callable is called . : param callable : the callable to capture information from : return : the wrapped callable"""
def capturing_callable ( * args , ** kwargs ) -> CaptureResult : return CaptureResult ( return_value = callable ( * args , ** kwargs ) ) if self . capture_exceptions : # Need to capture exceptions first else other ( non - return ) captured information will be lost exceptions_wrapper = CaptureWrapBuilder . _crea...
def _player_step_tuple ( self , envs_step_tuples ) : """Construct observation , return usual step tuple . Args : envs _ step _ tuples : tuples . Returns : Step tuple : ob , reward , done , info ob : concatenated images [ simulated observation , real observation , difference ] , with additional informati...
ob_real , reward_real , _ , _ = envs_step_tuples [ "real_env" ] ob_sim , reward_sim , _ , _ = envs_step_tuples [ "sim_env" ] ob_err = absolute_hinge_difference ( ob_sim , ob_real ) ob_real_aug = self . _augment_observation ( ob_real , reward_real , self . cumulative_real_reward ) ob_sim_aug = self . _augment_observatio...
def removeDataFrameRows ( self , rows ) : """Removes rows from the dataframe . : param rows : ( list ) of row indexes to removes . : return : ( bool ) True on success , False on failure ."""
if not self . editable : return False if rows : position = min ( rows ) count = len ( rows ) self . beginRemoveRows ( QtCore . QModelIndex ( ) , position , position + count - 1 ) removedAny = False for idx , line in self . _dataFrame . iterrows ( ) : if idx in rows : removedA...
def convert ( model , image_input_names = [ ] , is_bgr = False , red_bias = 0.0 , blue_bias = 0.0 , green_bias = 0.0 , gray_bias = 0.0 , image_scale = 1.0 , class_labels = None , predicted_feature_name = None , model_precision = _MLMODEL_FULL_PRECISION ) : """Convert a Caffe model to Core ML format . Parameters ...
from . . . models import MLModel from . . . models . utils import convert_neural_network_weights_to_fp16 as convert_neural_network_weights_to_fp16 if model_precision not in _VALID_MLMODEL_PRECISION_TYPES : raise RuntimeError ( 'Model precision {} is not valid' . format ( model_precision ) ) import tempfile model_pa...
def _replace_string_args ( self ) : '''A helper method that makes passing custom validators implemented as methods to : class : ` incoming . datatypes . Function ` instances .'''
if self . _string_args_replaced : return for field in self . _fields : field = getattr ( self , field ) if isinstance ( field , Function ) : if isinstance ( field . func , str ) : field . func = getattr ( self , field . func ) elif isinstance ( field , JSON ) : if isinstance ...
def _get_contrast ( self , con_id ) : """Retreive contrast with identifier ' con _ id ' from the list of contrast objects stored in self . contrasts"""
for contrasts in list ( self . contrasts . values ( ) ) : for contrast in contrasts : if contrast . estimation . id == con_id : return contrast raise Exception ( "Contrast activity with id: " + str ( con_id ) + " not found." )
def transform ( self , pyobject ) : """Transform a ` PyObject ` to textual form"""
if pyobject is None : return ( 'none' , ) object_type = type ( pyobject ) try : method = getattr ( self , object_type . __name__ + '_to_textual' ) return method ( pyobject ) except AttributeError : return ( 'unknown' , )
def _chooseBestSegmentPerColumn ( cls , connections , matchingCells , allMatchingSegments , potentialOverlaps , cellsPerColumn ) : """For all the columns covered by ' matchingCells ' , choose the column ' s matching segment with largest number of active potential synapses . When there ' s a tie , the first segm...
candidateSegments = connections . filterSegmentsByCell ( allMatchingSegments , matchingCells ) # Narrow it down to one segment per column . cellScores = potentialOverlaps [ candidateSegments ] columnsForCandidates = ( connections . mapSegmentsToCells ( candidateSegments ) / cellsPerColumn ) onePerColumnFilter = np2 . a...
def is_owner ( ) : """A : func : ` . check ` that checks if the person invoking this command is the owner of the bot . This is powered by : meth : ` . Bot . is _ owner ` . This check raises a special exception , : exc : ` . NotOwner ` that is derived from : exc : ` . CheckFailure ` ."""
async def predicate ( ctx ) : if not await ctx . bot . is_owner ( ctx . author ) : raise NotOwner ( 'You do not own this bot.' ) return True return check ( predicate )
def load_gmsh ( file_name , gmsh_args = None ) : """Returns a surface mesh from CAD model in Open Cascade Breap ( . brep ) , Step ( . stp or . step ) and Iges formats Or returns a surface mesh from 3D volume mesh using gmsh . For a list of possible options to pass to GMSH , check : http : / / gmsh . info / ...
# use STL as an intermediate format from . . exchange . stl import load_stl # start with default args for the meshing step # Mesh . Algorithm = 2 MeshAdapt / Delaunay , there are others but they may include quads # With this planes are meshed using Delaunay and cylinders are meshed using MeshAdapt args = [ ( "Mesh.Algo...
def _close_stdio ( ) : """Close stdio streams to avoid output in the tty that launched pantsd ."""
for fd in ( sys . stdin , sys . stdout , sys . stderr ) : file_no = fd . fileno ( ) fd . flush ( ) fd . close ( ) os . close ( file_no )
def _wraps ( self , tokens ) : """determine if a token is wrapped by another token"""
def _differ ( tokens ) : inner , outer = tokens not_same_start = inner . get ( 'start' ) != outer . get ( 'start' ) not_same_end = inner . get ( 'end' ) != outer . get ( 'end' ) return not_same_start or not_same_end def _in_range ( tokens ) : inner , outer = tokens starts_in = outer . get ( 'sta...
def sort_list ( items ) : """Sort a simple list by number of words and length ."""
# Track by number of words . track = { } def by_length ( word1 , word2 ) : return len ( word2 ) - len ( word1 ) # Loop through each item . for item in items : # Count the words . cword = utils . word_count ( item , all = True ) if cword not in track : track [ cword ] = [ ] track [ cword ] . appe...
def is_partial ( self ) : """Returns True if the VG is partial , False otherwise ."""
self . open ( ) part = lvm_vg_is_partial ( self . handle ) self . close ( ) return bool ( part )
def _hdu_on_disk ( self , hdulist_index ) : """IRAF routines such as daophot need input on disk . Returns : filename : str The name of the file containing the FITS data ."""
if self . _tempfile is None : self . _tempfile = tempfile . NamedTemporaryFile ( mode = "r+b" , suffix = ".fits" ) self . hdulist [ hdulist_index ] . writeto ( self . _tempfile . name ) return self . _tempfile . name
def getSamples ( netDataFile ) : """Returns samples joined at reset points . @ param netDataFile ( str ) Path to file ( in the FileRecordStream format ) . @ return samples ( OrderedDict ) Keys are sample number ( in order they are read in ) . Values are two - tuples of sample text and category ints ."""
try : with open ( netDataFile ) as f : reader = csv . reader ( f ) header = next ( reader , None ) next ( reader , None ) resetIdx = next ( reader ) . index ( "R" ) tokenIdx = header . index ( "_token" ) catIdx = header . index ( "_category" ) idIdx = header ....
def handle_range ( schema , field , validator , parent_schema ) : """Adds validation logic for ` ` marshmallow . validate . Range ` ` , setting the values appropriately ` ` fields . Number ` ` and it ' s subclasses . Args : schema ( dict ) : The original JSON schema we generated . This is what we want to po...
if not isinstance ( field , fields . Number ) : return schema if validator . min : schema [ 'minimum' ] = validator . min schema [ 'exclusiveMinimum' ] = True else : schema [ 'minimum' ] = 0 schema [ 'exclusiveMinimum' ] = False if validator . max : schema [ 'maximum' ] = validator . max sch...
def drop_paired_notebook ( self , path ) : """Remove the current notebook from the list of paired notebooks"""
if path not in self . paired_notebooks : return fmt , formats = self . paired_notebooks . pop ( path ) prev_paired_paths = paired_paths ( path , fmt , formats ) for alt_path , _ in prev_paired_paths : if alt_path in self . paired_notebooks : self . drop_paired_notebook ( alt_path )
def parse_options ( arguments ) : """Parse command line arguments . The parsing logic is fairly simple . It can only parse long - style parameters of the form : : - - key value Several parameters can be defined in the environment and will be used unless explicitly overridden with command - line arguments ...
arguments = arguments [ 1 : ] options = { } while arguments : key = arguments . pop ( 0 ) if key in ( "-h" , "--help" ) : raise UsageError ( "Help requested." ) if key . startswith ( "--" ) : key = key [ 2 : ] try : value = arguments . pop ( 0 ) except IndexError ...
def load_labware ( self , labware : Labware ) -> Labware : """Load labware onto a Magnetic Module , checking if it is compatible"""
if labware . magdeck_engage_height is None : MODULE_LOG . warning ( "This labware ({}) is not explicitly compatible with the" " Magnetic Module. You will have to specify a height when" " calling engage()." ) return super ( ) . load_labware ( labware )
def delete ( self , * keys ) : """Removes the specified keys . A key is ignored if it does not exist . Returns : data : ` True ` if all keys are removed . . . note : : * * Time complexity * * : ` ` O ( N ) ` ` where ` ` N ` ` is the number of keys that will be removed . When a key to remove holds a value ot...
return self . _execute ( [ b'DEL' ] + list ( keys ) , len ( keys ) )
def draw ( self , drawDC = None ) : """Render the figure using RendererWx instance renderer , or using a previously defined renderer if none is specified ."""
DEBUG_MSG ( "draw()" , 1 , self ) self . renderer = RendererWx ( self . bitmap , self . figure . dpi ) self . figure . draw ( self . renderer ) self . _isDrawn = True self . gui_repaint ( drawDC = drawDC )
def create ( self , archive_name , authority_name = None , versioned = True , raise_on_err = True , metadata = None , tags = None , helper = False ) : '''Create a DataFS archive Parameters archive _ name : str Name of the archive authority _ name : str Name of the data service to use as the archive ' s da...
authority_name , archive_name = self . _normalize_archive_name ( archive_name , authority_name = authority_name ) if authority_name is None : authority_name = self . default_authority_name self . _validate_archive_name ( archive_name ) if metadata is None : metadata = { } res = self . manager . create_archive (...
def get_default ( self , stmt , refd ) : """Return default value for ` stmt ` node . ` refd ` is a dictionary of applicable refinements that is constructed in the ` process _ patches ` method ."""
if refd [ "default" ] : return refd [ "default" ] defst = stmt . search_one ( "default" ) if defst : return defst . arg return None
def split_code_and_text_blocks ( source_file ) : """Return list with source file separated into code and text blocks . Returns file _ conf : dict File - specific settings given in source file comments as : ` ` # sphinx _ gallery _ < name > = < value > ` ` blocks : list ( label , content , line _ number ...
docstring , rest_of_content , lineno = get_docstring_and_rest ( source_file ) blocks = [ ( 'text' , docstring , 1 ) ] file_conf = extract_file_config ( rest_of_content ) pattern = re . compile ( r'(?P<header_line>^#{20,}.*)\s(?P<text_content>(?:^#.*\s)*)' , flags = re . M ) sub_pat = re . compile ( '^#' , flags = re . ...
def load_page ( self , payload ) : """Parses the collection of records out of a list payload . : param dict payload : The JSON - loaded content . : return list : The list of records ."""
if 'meta' in payload and 'key' in payload [ 'meta' ] : return payload [ payload [ 'meta' ] [ 'key' ] ] else : keys = set ( payload . keys ( ) ) key = keys - self . META_KEYS if len ( key ) == 1 : return payload [ key . pop ( ) ] raise TwilioException ( 'Page Records can not be deserialized' )
def get_fieldsets ( self , fieldsets = None ) : """This method returns a generator which yields fieldset instances . The method uses the optional fieldsets argument to generate fieldsets for . If no fieldsets argument is passed , the class property ` ` fieldsets ` ` is used . When generating the fieldsets , t...
fieldsets = fieldsets or self . fieldsets if not fieldsets : raise StopIteration # Search for primary marker in at least one of the fieldset kwargs . has_primary = any ( fieldset . get ( 'primary' ) for fieldset in fieldsets ) for fieldset_kwargs in fieldsets : fieldset_kwargs = copy . deepcopy ( fieldset_kwarg...
def check_staged ( filename = None ) : """Check if there are ' changes to be committed ' in the index ."""
retcode , _ , stdout = git [ 'diff-index' , '--quiet' , '--cached' , 'HEAD' , filename ] . run ( retcode = None ) if retcode == 1 : return True elif retcode == 0 : return False else : raise RuntimeError ( stdout )
def enable_host_event_handler ( self , host ) : """Enable event handlers for a host Format of the line that triggers function call : : ENABLE _ HOST _ EVENT _ HANDLER ; < host _ name > : param host : host to edit : type host : alignak . objects . host . Host : return : None"""
if not host . event_handler_enabled : host . modified_attributes |= DICT_MODATTR [ "MODATTR_EVENT_HANDLER_ENABLED" ] . value host . event_handler_enabled = True self . send_an_element ( host . get_update_status_brok ( ) )
def nova_client ( self ) : """Each of the OpenStack client libraries ( i . e . the ` ` python - * client ` ` projects that live under https : / / github . com / openstack / ) has its own way of connecting to the identity service ( keystone ) . The object returned here is a : class : ` novaclient . v1_1 . clie...
if not self . _client : self . _client = self . _get_nova_client ( ) return self . _client
def key ( self ) -> Tuple [ int , int ] : """The unique identifier of the edge consisting of the indexes of its source and target nodes ."""
return self . _source . index , self . _target . index
def _publish_status ( self , port ) : '''Publish status for specified port . Parameters port : str Device name / port .'''
if port not in self . open_devices : status = { } else : device = self . open_devices [ port ] . serial properties = ( 'port' , 'baudrate' , 'bytesize' , 'parity' , 'stopbits' , 'timeout' , 'xonxoff' , 'rtscts' , 'dsrdtr' ) status = { k : getattr ( device , k ) for k in properties } status_json = json ....
def choices ( self ) : """Retrieve the parts that you can reference for this ` ReferenceProperty ` . This method makes 2 API calls : 1 ) to retrieve the referenced model , and 2 ) to retrieve the instances of that model . : return : the : class : ` Part ` ' s that can be referenced as a : class : ` ~ pykechai...
# from the reference property ( instance ) we need to get the value of the reference property in the model # in the reference property of the model the value is set to the ID of the model from which we can choose parts model_parent_part = self . part . model ( ) # makes single part call property_model = model_parent_pa...
def get_asset_path ( self , filename ) : """Get the full system path of a given asset if it exists . Otherwise it throws an error . Args : filename ( str ) - File name of a file in / assets folder to fetch the path for . Returns : str - path to the target file . Raises : AssetNotFoundError - if asset ...
if os . path . exists ( os . path . join ( self . _asset_path , filename ) ) : return os . path . join ( self . _asset_path , filename ) else : raise AssetNotFoundError ( u ( "Cannot find asset: {0}" ) . format ( filename ) )
def remove_pointer ( type_ ) : """removes pointer from the type definition If type is not pointer type , it will be returned as is ."""
nake_type = remove_alias ( type_ ) if not is_pointer ( nake_type ) : return type_ elif isinstance ( nake_type , cpptypes . volatile_t ) and isinstance ( nake_type . base , cpptypes . pointer_t ) : return cpptypes . volatile_t ( nake_type . base . base ) elif isinstance ( nake_type , cpptypes . const_t ) and isi...
def register ( self ) : """Change the state machine that is observed for new selected states to the selected state machine ."""
self . _do_selection_update = True # relieve old model if self . __my_selected_sm_id is not None : # no old models available self . relieve_model ( self . _selected_sm_model ) # set own selected state machine id self . __my_selected_sm_id = self . model . selected_state_machine_id if self . __my_selected_sm_id is n...
def file_verify ( sender_blockchain_id , sender_key_id , input_path , sig , config_path = CONFIG_PATH , wallet_keys = None ) : """Verify that a file was signed with the given blockchain ID @ config _ path should be for the * client * , not blockstack - file Return { ' status ' : True } on succes Return { ' er...
config_dir = os . path . dirname ( config_path ) old_key = False old_key_index = 0 sender_old_key_index = 0 # get the sender key sender_key_info = file_key_lookup ( sender_blockchain_id , None , None , key_id = sender_key_id , config_path = config_path , wallet_keys = wallet_keys ) if 'error' in sender_key_info : l...
def write ( self , df , table_name , temp_dir = CACHE_DIR , overwrite = False , lnglat = None , encode_geom = False , geom_col = None , ** kwargs ) : """Write a DataFrame to a CARTO table . Examples : Write a pandas DataFrame to CARTO . . . code : : python cc . write ( df , ' brooklyn _ poverty ' , overwrit...
# noqa tqdm . write ( 'Params: encode_geom, geom_col and everything in kwargs are deprecated and not being used any more' ) dataset = Dataset ( self , table_name , df = df ) if_exists = Dataset . FAIL if overwrite : if_exists = Dataset . REPLACE dataset = dataset . upload ( with_lonlat = lnglat , if_exists = if_exi...
def _provider_state_fixtures_with_params ( provider_state_fixture_by_descriptor : Dict [ str , ProviderStateFixture ] , provider_states : Tuple [ ProviderState , ... ] ) -> List [ Tuple [ ProviderStateFixture , Dict ] ] : """Get a list of provider states fixtures for an interaction with their parameters . Raises ...
provider_state_fixtures_with_params : List [ Tuple [ ProviderStateFixture , Dict ] ] = [ ] for provider_state in provider_states : provider_state_fixture = provider_state_fixture_by_descriptor . get ( provider_state . descriptor ) if not provider_state_fixture : raise UnsupportedProviderStateError ( f'M...
def keys_in ( items , * args ) : """Use this utility function to ensure multiple keys are in one or more dicts . Returns ` True ` if all keys are present in at least one of the given dicts , otherwise returns ` False ` . : Parameters : - ` items ` : Iterable of required keys - Variable number of subsequen...
found = dict ( ( key , False ) for key in items ) for d in args : for item in items : if not found [ item ] and item in d : found [ item ] = True return all ( found . values ( ) )
def throw_random ( lengths , mask ) : """Try multiple times to run ' throw _ random '"""
saved = None for i in range ( maxtries ) : try : return throw_random_bits ( lengths , mask ) except MaxtriesException as e : saved = e continue raise e
def tmdb_find ( api_key , external_source , external_id , language = "en-US" , cache = True ) : """Search for The Movie Database objects using another DB ' s foreign key Note : language codes aren ' t checked on this end or by TMDb , so if you enter an invalid language code your search itself will succeed , but...
sources = [ "imdb_id" , "freebase_mid" , "freebase_id" , "tvdb_id" , "tvrage_id" ] if external_source not in sources : raise MapiProviderException ( "external_source must be in %s" % sources ) if external_source == "imdb_id" and not match ( r"tt\d+" , external_id ) : raise MapiProviderException ( "invalid imdb ...
def get_isotope_dicts ( element = '' , database = 'ENDF_VII' ) : """return a dictionary with list of isotopes found in database and name of database files Parameters : element : string . Name of the element ex : ' Ag ' database : string ( default is ENDF _ VII ) Returns : dictionary with isotopes and fi...
_file_path = os . path . abspath ( os . path . dirname ( __file__ ) ) _database_folder = os . path . join ( _file_path , 'reference_data' , database ) _element_search_path = os . path . join ( _database_folder , element + '-*.csv' ) list_files = glob . glob ( _element_search_path ) if not list_files : raise ValueEr...
def cond ( A ) : """Return condition number of A . Parameters A : { dense or sparse matrix } e . g . array , matrix , csr _ matrix , . . . Returns 2 - norm condition number through use of the SVD Use for small to moderate sized dense matrices . For large sparse matrices , use condest . Notes The c...
if A . shape [ 0 ] != A . shape [ 1 ] : raise ValueError ( 'expected square matrix' ) if sparse . isspmatrix ( A ) : A = A . todense ( ) # 2 - Norm Condition Number from scipy . linalg import svd U , Sigma , Vh = svd ( A ) return np . max ( Sigma ) / min ( Sigma )
def enable_hostgroup_host_notifications ( self , hostgroup ) : """Enable host notifications for a hostgroup Format of the line that triggers function call : : ENABLE _ HOSTGROUP _ HOST _ NOTIFICATIONS ; < hostgroup _ name > : param hostgroup : hostgroup to enable : type hostgroup : alignak . objects . hostg...
for host_id in hostgroup . get_hosts ( ) : if host_id in self . daemon . hosts : self . enable_host_notifications ( self . daemon . hosts [ host_id ] )
def _done_callback ( self , wrapped ) : """Internal " done callback " to set the result of the object . The result of the object if forced by the wrapped future . So this internal callback must be called when the wrapped future is ready . Args : wrapped ( Future ) : the wrapped Future object"""
if wrapped . exception ( ) : self . set_exception ( wrapped . exception ( ) ) else : self . set_result ( wrapped . result ( ) )
def _find_alias ( FunctionName , Name , FunctionVersion = None , region = None , key = None , keyid = None , profile = None ) : '''Given function name and alias name , find and return matching alias information .'''
conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile ) args = { 'FunctionName' : FunctionName } if FunctionVersion : args [ 'FunctionVersion' ] = FunctionVersion for aliases in __utils__ [ 'boto3.paged_call' ] ( conn . list_aliases , ** args ) : for alias in aliases . get ( 'Aliase...
def neighbors_iter ( self ) : """Iterate over atoms and return its neighbors ."""
for n , adj in self . graph . adj . items ( ) : yield n , { n : attr [ "bond" ] for n , attr in adj . items ( ) }
def chunks ( items , size ) : """Split list into chunks of the given size . Original order is preserved . Example : > chunks ( [ 1,2,3,4,5,6,7,8 ] , 3) [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 ] ]"""
return [ items [ i : i + size ] for i in range ( 0 , len ( items ) , size ) ]
def Clear ( self ) : """Clears the breakpoint and releases all breakpoint resources . This function is assumed to be called by BreakpointsManager . Therefore we don ' t call CompleteBreakpoint from here ."""
self . _RemoveImportHook ( ) if self . _cookie is not None : native . LogInfo ( 'Clearing breakpoint %s' % self . GetBreakpointId ( ) ) native . ClearConditionalBreakpoint ( self . _cookie ) self . _cookie = None self . _completed = True
def publish ( self ) : '''Publish the current release to PyPI'''
if self . config . publish : logger . info ( 'Publish' ) self . execute ( self . config . publish )
def rotate ( self , alpha , beta , gamma , degrees = True , convention = 'y' , body = False , dj_matrix = None ) : """Rotate either the coordinate system used to express the spherical harmonic coefficients or the physical body , and return a new class instance . Usage x _ rotated = x . rotate ( alpha , beta...
if type ( convention ) != str : raise ValueError ( 'convention must be a string. ' + 'Input type was {:s}' . format ( str ( type ( convention ) ) ) ) if convention . lower ( ) not in ( 'x' , 'y' ) : raise ValueError ( "convention must be either 'x' or 'y'. " + "Provided value was {:s}" . format ( repr ( convent...
def get_from_geo ( self , lat , lng , distance , skip_cache = False ) : """Calls ` postcodes . get _ from _ geo ` but checks the correctness of all arguments , and by default utilises a local cache . : param skip _ cache : optional argument specifying whether to skip the cache and make an explicit request . ...
# remove spaces and change case here due to caching lat , lng , distance = float ( lat ) , float ( lng ) , float ( distance ) if distance < 0 : raise IllegalDistanceException ( "Distance must not be negative" ) self . _check_point ( lat , lng ) return self . _lookup ( skip_cache , get_from_geo , lat , lng , distanc...
def get_pID ( read ) : """Return the percent identity of a read . based on the NM tag if present , if not calculate from MD tag and CIGAR string read . query _ alignment _ length can be zero in the case of ultra long reads aligned with minimap2 - L"""
try : return 100 * ( 1 - read . get_tag ( "NM" ) / read . query_alignment_length ) except KeyError : try : return 100 * ( 1 - ( parse_MD ( read . get_tag ( "MD" ) ) + parse_CIGAR ( read . cigartuples ) ) / read . query_alignment_length ) except KeyError : return None except ZeroDivisionError...
def getLogger ( name ) : """This is used by gcdt plugins to get a logger with the right level ."""
logger = logging . getLogger ( name ) # note : the level might be adjusted via ' - v ' option logger . setLevel ( logging_config [ 'loggers' ] [ 'gcdt' ] [ 'level' ] ) return logger
def _GetISO8601String ( self , structure ) : """Normalize date time parsed format to an ISO 8601 date time string . The date and time values in Apache access log files are formatted as : " [ 18 / Sep / 2011:19:18:28 - 0400 ] " . Args : structure ( pyparsing . ParseResults ) : structure of tokens derived fro...
time_offset = structure . time_offset month = timelib . MONTH_DICT . get ( structure . month . lower ( ) , 0 ) try : time_offset_hours = int ( time_offset [ 1 : 3 ] , 10 ) time_offset_minutes = int ( time_offset [ 3 : 5 ] , 10 ) except ( IndexError , TypeError , ValueError ) as exception : raise ValueError ...
def _unary_ ( self , func , inplace = False ) : ''': func : unary function to apply to each coordinate : inplace : optional boolean : return : Point Implementation private method . All of the unary operations funnel thru this method to reduce cut - and - paste code and enforce consistent behavior of una...
dst = self if inplace else self . __class__ ( self ) dst . x = func ( dst . x ) dst . y = func ( dst . y ) dst . z = func ( dst . z ) return dst
def RFC3156_micalg_from_algo ( hash_algo ) : """Converts a GPGME hash algorithm name to one conforming to RFC3156. GPGME returns hash algorithm names such as " SHA256 " , but RFC3156 says that programs need to use names such as " pgp - sha256 " instead . : param str hash _ algo : GPGME hash _ algo : returns...
# hash _ algo will be something like SHA256 , but we need pgp - sha256. algo = gpg . core . hash_algo_name ( hash_algo ) if algo is None : raise GPGProblem ( 'Unknown hash algorithm {}' . format ( algo ) , code = GPGCode . INVALID_HASH_ALGORITHM ) return 'pgp-' + algo . lower ( )
def _check_frames ( self , frames , fill_value ) : """Reduce frames to no more than are available in the file ."""
if self . seekable ( ) : remaining_frames = self . frames - self . tell ( ) if frames < 0 or ( frames > remaining_frames and fill_value is None ) : frames = remaining_frames elif frames < 0 : raise ValueError ( "frames must be specified for non-seekable files" ) return frames
def get_all_lower ( self ) : """Return all parent GO IDs through both reverse ' is _ a ' and all relationships ."""
all_lower = set ( ) for lower in self . get_goterms_lower ( ) : all_lower . add ( lower . item_id ) all_lower |= lower . get_all_lower ( ) return all_lower
def get_storage_account ( access_token , subscription_id , rgname , account_name ) : '''Get the properties for the named storage account . Args : access _ token ( str ) : A valid Azure authentication token . subscription _ id ( str ) : Azure subscription id . rgname ( str ) : Azure resource group name . a...
endpoint = '' . join ( [ get_rm_endpoint ( ) , '/subscriptions/' , subscription_id , '/resourcegroups/' , rgname , '/providers/Microsoft.Storage/storageAccounts/' , account_name , '?api-version=' , STORAGE_API ] ) return do_get ( endpoint , access_token )
def readTables ( self ) : """Retrieves data ( D ) and names ( N ) from relational tables ."""
class D : pass cur = self . cur cur . execute ( 'SELECT * FROM users' ) D . users = cur . fetchall ( ) cur . execute ( 'SELECT * FROM profiles' ) D . profiles = cur . fetchall ( ) cur . execute ( 'SELECT * FROM articles' ) D . articles = cur . fetchall ( ) cur . execute ( 'SELECT * FROM comments' ) D . comments = c...
def _set_expressions ( self , expressions ) : """Extract expressions and variables from the user provided expressions ."""
self . expressions = { } for key , item in expressions . items ( ) : self . expressions [ key ] = { 'function' : item }
def url_is_project ( url , default = 'not_a_func' ) : """Check if URL is part of the current project ' s URLs . Args : url ( str ) : URL to check . default ( callable ) : used to filter out some URLs attached to function . Returns :"""
try : u = resolve ( url ) if u and u . func != default : return True except Resolver404 : static_url = settings . STATIC_URL static_url_wd = static_url . lstrip ( '/' ) if url . startswith ( static_url ) : url = url [ len ( static_url ) : ] elif url . startswith ( static_url_wd )...
def makeVisualSong ( self ) : """Return a sequence of images and durations ."""
self . files = os . listdir ( self . basedir ) self . stairs = [ i for i in self . files if ( "stair" in i ) and ( "R" in i ) ] self . sectors = [ i for i in self . files if "sector" in i ] self . stairs . sort ( ) self . sectors . sort ( ) filenames = [ self . basedir + i for i in self . sectors [ : 4 ] ] self . iS0 =...
def createmeta ( accountable , project_key , issue_type = None ) : """Create new issue ."""
metadata = accountable . create_meta ( project_key , issue_type ) headers = [ 'project_key' , 'issuetype_name' , 'field_key' , 'field_name' , 'required' ] rows = [ headers ] for project in metadata : key = project [ 'key' ] issuetypes = project [ 'issuetypes' ] for issuetype in issuetypes : name = i...
def warm_up_cache ( self ) : """Warms up the cache for the slice or table . Note for slices a force refresh occurs ."""
slices = None session = db . session ( ) slice_id = request . args . get ( 'slice_id' ) table_name = request . args . get ( 'table_name' ) db_name = request . args . get ( 'db_name' ) if not slice_id and not ( table_name and db_name ) : return json_error_response ( __ ( 'Malformed request. slice_id or table_name an...
def message ( self , to , subject , text ) : """Alias for : meth : ` compose ` ."""
return self . compose ( to , subject , text )
def kill_cursors ( cursor_ids ) : """Get a * * killCursors * * message ."""
num_cursors = len ( cursor_ids ) pack = struct . Struct ( "<ii" + ( "q" * num_cursors ) ) . pack op_kill_cursors = pack ( 0 , num_cursors , * cursor_ids ) return __pack_message ( 2007 , op_kill_cursors )
def _populate ( self , client ) : """Populate module with the client when available"""
self . client = client for fn in self . _buffered_calls : self . _log . debug ( "Executing buffered call {}" . format ( fn ) ) fn ( )
def install_certs ( ssl_dir , certs , chain = None , user = 'root' , group = 'root' ) : """Install the certs passed into the ssl dir and append the chain if provided . : param ssl _ dir : str Directory to create symlinks in : param certs : { } { ' cn ' : { ' cert ' : ' CERT ' , ' key ' : ' KEY ' } } : param...
for cn , bundle in certs . items ( ) : cert_filename = 'cert_{}' . format ( cn ) key_filename = 'key_{}' . format ( cn ) cert_data = bundle [ 'cert' ] if chain : # Append chain file so that clients that trust the root CA will # trust certs signed by an intermediate in the chain cert_data = c...
def taxids ( self ) : """Distinct NCBI taxonomy identifiers ( ` ` taxid ` ` ) in : class : ` . models . Entry ` : return : NCBI taxonomy identifiers : rtype : list [ int ]"""
r = self . session . query ( distinct ( models . Entry . taxid ) ) . all ( ) return [ x [ 0 ] for x in r ]
def computeHeteroPercentage ( fileName ) : """Computes the heterozygosity percentage . : param fileName : the name of the input file . : type fileName : str Reads the ` ` ped ` ` file created by Plink using the ` ` recodeA ` ` options ( see : py : func : ` createPedChr23UsingPlink ` ) and computes the heter...
outputFile = None try : outputFile = open ( fileName + ".hetero" , "w" ) except IOError : msg = "%s: can't write file" % fileName + ".hetero" raise ProgramError ( msg ) print >> outputFile , "\t" . join ( [ "PED" , "ID" , "SEX" , "HETERO" ] ) try : toPrint = [ ] with open ( fileName , "r" ) as input...
def read_meta ( self , document_id = None ) : """Load metadata associated with the document . . note : : This method is called automatically if needed when a property is first accessed . You will not normally have to use this method manually . : param document _ id : ( optional ) set the document id if this...
if document_id : if not self . abstract : raise ImmutableDocumentException ( ) self . _id = document_id if self . abstract : raise AbstractDocumentException ( ) metadata = self . _api . get_document_meta ( self . id ) self . _name = metadata [ 'document_name' ] self . _public = metadata [ 'public' ]...
def poisson ( x , a , b , c , d = 0 ) : '''Poisson function a - > height of the curve ' s peak b - > position of the center of the peak c - > standard deviation d - > offset'''
from scipy . misc import factorial # save startup time lamb = 1 X = ( x / ( 2 * c ) ) . astype ( int ) return a * ( ( lamb ** X / factorial ( X ) ) * np . exp ( - lamb ) ) + d
def search_by_release ( self , release_id , limit = 0 , order_by = None , sort_order = None , filter = None ) : """Search for series that belongs to a release id . Returns information about matching series in a DataFrame . Parameters release _ id : int release id , e . g . , 151 limit : int , optional lim...
url = "%s/release/series?release_id=%d" % ( self . root_url , release_id ) info = self . __get_search_results ( url , limit , order_by , sort_order , filter ) if info is None : raise ValueError ( 'No series exists for release id: ' + str ( release_id ) ) return info
def log_request ( _ , request , * _args , ** _kwargs ) : # type : ( Any , ClientRequest , str , str ) - > None """Log a client request . : param _ : Unused in current version ( will be None ) : param requests . Request request : The request object ."""
if not _LOGGER . isEnabledFor ( logging . DEBUG ) : return try : _LOGGER . debug ( "Request URL: %r" , request . url ) _LOGGER . debug ( "Request method: %r" , request . method ) _LOGGER . debug ( "Request headers:" ) for header , value in request . headers . items ( ) : if header . lower ( ...
def _create ( observation_data , user_id = 'user_id' , item_id = 'item_id' , target = None , user_data = None , item_data = None , ranking = True , verbose = True ) : """A unified interface for training recommender models . Based on simple characteristics of the data , a type of model is selected and trained . Th...
if not ( isinstance ( observation_data , _SFrame ) ) : raise TypeError ( 'observation_data input must be a SFrame' ) side_data = ( user_data is not None ) or ( item_data is not None ) if user_data is not None : if not isinstance ( user_data , _SFrame ) : raise TypeError ( 'Provided user_data must be an ...
def default ( self , statement : Statement ) -> Optional [ bool ] : """Executed when the command given isn ' t a recognized command implemented by a do _ * method . : param statement : Statement object with parsed input"""
if self . default_to_shell : if 'shell' not in self . exclude_from_history : self . history . append ( statement ) return self . do_shell ( statement . command_and_args ) else : err_msg = self . default_error . format ( statement . command ) self . decolorized_write ( sys . stderr , "{}\n" . for...
def _request_submit ( self , func , ** kwargs ) : """A helper function that will wrap any requests we make . : param func : a function reference to the requests method to invoke : param kwargs : any extra arguments that requests . request takes : type func : ( url : Any , data : Any , json : Any , kwargs : Di...
resp = func ( headers = self . _get_headers ( ) , ** kwargs ) self . _log_response_from_method ( func . __name__ , resp ) self . _validate_response_success ( resp ) return resp
def get_tx_identity_info ( self , tx_ac ) : """returns features associated with a single transcript . : param tx _ ac : transcript accession with version ( e . g . , ' NM _ 199425.2 ' ) : type tx _ ac : str # database output - [ RECORD 1 ] - - + - - - - - tx _ ac | NM _ 199425.2 alt _ ac | NM _ 199425.2...
rows = self . _fetchall ( self . _queries [ 'tx_identity_info' ] , [ tx_ac ] ) if len ( rows ) == 0 : raise HGVSDataNotAvailableError ( "No transcript definition for (tx_ac={tx_ac})" . format ( tx_ac = tx_ac ) ) return rows [ 0 ]
def check_network_health ( self ) : r"""This method check the network topological health by checking for : (1 ) Isolated pores (2 ) Islands or isolated clusters of pores (3 ) Duplicate throats (4 ) Bidirectional throats ( ie . symmetrical adjacency matrix ) (5 ) Headless throats Returns A dictionary c...
health = HealthDict ( ) health [ 'disconnected_clusters' ] = [ ] health [ 'isolated_pores' ] = [ ] health [ 'trim_pores' ] = [ ] health [ 'duplicate_throats' ] = [ ] health [ 'bidirectional_throats' ] = [ ] health [ 'headless_throats' ] = [ ] health [ 'looped_throats' ] = [ ] # Check for headless throats hits = sp . wh...
def load2Dimage ( filename , alpha = 1 ) : """Read a JPEG / PNG / BMP image from file . Return an ` ` ImageActor ( vtkImageActor ) ` ` object . . . hint : : | rotateImage | | rotateImage . py | _"""
fl = filename . lower ( ) if ".png" in fl : picr = vtk . vtkPNGReader ( ) elif ".jpg" in fl or ".jpeg" in fl : picr = vtk . vtkJPEGReader ( ) elif ".bmp" in fl : picr = vtk . vtkBMPReader ( ) picr . Allow8BitBMPOff ( ) else : colors . printc ( "~times File must end with png, bmp or jp(e)g" , c = 1 )...
def ParentAndBaseName ( path ) : """Given a path return only the parent name and file name as a string ."""
dirname , basename = os . path . split ( path ) dirname = dirname . rstrip ( os . path . sep ) if os . path . altsep : dirname = dirname . rstrip ( os . path . altsep ) _ , parentname = os . path . split ( dirname ) return os . path . join ( parentname , basename )
def create_payment ( self , * , amount , currency , order = None , customer_id = None , billing_address = None , shipping_address = None , additional_details = None , statement_soft_descriptor = None ) : """Creates a payment object , which provides a single reference to all the transactions that make up a payment ....
headers = self . client . _get_private_headers ( ) payload = { "amount" : amount , "currency" : currency , "order" : order , "customer_id" : customer_id , "billing_address" : billing_address , "shipping_address" : shipping_address , "additional_details" : additional_details , "statement_soft_descriptor" : statement_sof...
def html_fromstring ( s ) : """Parse html tree from string . Return None if the string can ' t be parsed ."""
if isinstance ( s , six . text_type ) : s = s . encode ( 'utf8' ) try : if html_too_big ( s ) : return None return html5parser . fromstring ( s , parser = _html5lib_parser ( ) ) except Exception : pass
def _handle_app_result_build_failure ( self , out , err , exit_status , result_paths ) : """Catch the error when files are not produced"""
try : raise ApplicationError , 'RAxML failed to produce an output file due to the following error: \n\n%s ' % err . read ( ) except : raise ApplicationError , 'RAxML failed to run properly.'
def send_message ( ) -> None : """Send message via WS to all client connections ."""
if not _msg_queue : return msg = json . dumps ( _msg_queue ) _msg_queue . clear ( ) for conn in module . connections : conn . write_message ( msg )
def find_malformed_single_file_project ( self ) : # type : ( ) - > List [ str ] """Take first non - setup . py python file . What a mess . : return :"""
files = [ f for f in os . listdir ( "." ) if os . path . isfile ( f ) ] candidates = [ ] # project misnamed & not in setup . py for file in files : if file . endswith ( "setup.py" ) or not file . endswith ( ".py" ) : continue # duh candidate = file . replace ( ".py" , "" ) if candidate != "setup...
def time_series_h5 ( timefile , colnames ) : """Read temporal series HDF5 file . If : data : ` colnames ` is too long , it will be truncated . If it is too short , additional column names will be deduced from the content of the file . Args : timefile ( : class : ` pathlib . Path ` ) : path of the TimeSeries...
if not timefile . is_file ( ) : return None with h5py . File ( timefile , 'r' ) as h5f : dset = h5f [ 'tseries' ] _ , ncols = dset . shape ncols -= 1 # first is istep h5names = map ( bytes . decode , h5f [ 'names' ] [ len ( colnames ) + 1 : ] ) _tidy_names ( colnames , ncols , h5names ) ...
def _getEventsByWeek ( self , request , year , month ) : """Return my child events for the given month grouped by week ."""
return getAllEventsByWeek ( request , year , month , home = self )
def count_n_grams_py_polarity ( self , data_set_reader , n_grams , filters ) : """Returns a map of n - gram and the number of times it appeared in positive context and the number of times it appeared in negative context in dataset file . : param data _ set _ reader : Dataset containing tweets and their classifi...
self . data_set_reader = data_set_reader token_trie = TokenTrie ( n_grams ) counter = { } # Todo : parallelize for entry in data_set_reader . items ( ) : tweet = filters . apply ( entry . get_tweet ( ) ) tokens = token_trie . find_optimal_tokenization ( RegexFilters . WHITESPACE . split ( tweet ) ) for n_gr...
def get_download_uri ( package_name , version , source , index_url = None ) : """Use setuptools to search for a package ' s URI @ returns : URI string"""
tmpdir = None force_scan = True develop_ok = False if not index_url : index_url = 'http://cheeseshop.python.org/pypi' if version : pkg_spec = "%s==%s" % ( package_name , version ) else : pkg_spec = package_name req = pkg_resources . Requirement . parse ( pkg_spec ) pkg_index = MyPackageIndex ( index_url ) t...
def update_subtotals ( self , current , sub_key ) : """updates sub _ total counts for the class instance based on the current dictionary counts args : current : current dictionary counts sub _ key : the key / value to use for the subtotals"""
if not self . sub_counts . get ( sub_key ) : self . sub_counts [ sub_key ] = { } for item in current : try : self . sub_counts [ sub_key ] [ item ] += 1 except KeyError : self . sub_counts [ sub_key ] [ item ] = 1
def parse ( self , type_str ) : """Parses a type string into an appropriate instance of : class : ` ~ eth _ abi . grammar . ABIType ` . If a type string cannot be parsed , throws : class : ` ~ eth _ abi . exceptions . ParseError ` . : param type _ str : The type string to be parsed . : returns : An instance...
if not isinstance ( type_str , str ) : raise TypeError ( 'Can only parse string values: got {}' . format ( type ( type_str ) ) ) try : return super ( ) . parse ( type_str ) except parsimonious . ParseError as e : raise ParseError ( e . text , e . pos , e . expr )
def _get_phi_al_regional ( self , C , mag , vs30measured , rrup ) : """Returns intra - event ( Tau ) standard deviation ( equation 26 , page 1046)"""
phi_al = np . ones ( ( len ( vs30measured ) ) ) idx = rrup < 30 phi_al [ idx ] *= C [ 's5' ] idx = ( ( rrup <= 80 ) & ( rrup >= 30. ) ) phi_al [ idx ] *= C [ 's5' ] + ( C [ 's6' ] - C [ 's5' ] ) / 50. * ( rrup [ idx ] - 30. ) idx = rrup > 80 phi_al [ idx ] *= C [ 's6' ] return phi_al
def write_doc ( doc : MetapackDoc , mt_file = None ) : """Write a Metatab doc to a CSV file , and update the Modified time : param doc : : param mt _ file : : return :"""
from rowgenerators import parse_app_url if not mt_file : mt_file = doc . ref add_giturl ( doc ) u = parse_app_url ( mt_file ) if u . scheme == 'file' : doc . write ( mt_file ) return True else : return False
def _version_from_file ( lines ) : """Given an iterable of lines from a Metadata file , return the value of the Version field , if present , or None otherwise ."""
def is_version_line ( line ) : return line . lower ( ) . startswith ( 'version:' ) version_lines = filter ( is_version_line , lines ) line = next ( iter ( version_lines ) , '' ) _ , _ , value = line . partition ( ':' ) return safe_version ( value . strip ( ) ) or None