signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def resizeToContents ( self ) : """Resizes the list widget to fit its contents vertically ."""
if self . count ( ) : item = self . item ( self . count ( ) - 1 ) rect = self . visualItemRect ( item ) height = rect . bottom ( ) + 8 height = max ( 28 , height ) self . setFixedHeight ( height ) else : self . setFixedHeight ( self . minimumHeight ( ) )
def get_brand_by_id ( cls , brand_id , ** kwargs ) : """Find Brand Return single instance of Brand by its ID . This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async = True > > > thread = api . get _ brand _ by _ id ( brand _ id , async = True ) ...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async' ) : return cls . _get_brand_by_id_with_http_info ( brand_id , ** kwargs ) else : ( data ) = cls . _get_brand_by_id_with_http_info ( brand_id , ** kwargs ) return data
def takeout ( self , finalize = True , * , contacts = None , users = None , chats = None , megagroups = None , channels = None , files = None , max_file_size = None ) : """Creates a proxy object over the current : ref : ` TelegramClient ` through which making requests will use : tl : ` InvokeWithTakeoutRequest ` ...
request_kwargs = dict ( contacts = contacts , message_users = users , message_chats = chats , message_megagroups = megagroups , message_channels = channels , files = files , file_max_size = max_file_size ) arg_specified = ( arg is not None for arg in request_kwargs . values ( ) ) if self . session . takeout_id is None ...
def norm_proj_path ( path , build_module ) : """Return a normalized path for the ` path ` observed in ` build _ module ` . The normalized path is " normalized " ( in the ` os . path . normpath ` sense ) , relative from the project root directory , and OS - native . Supports making references from project root...
if path == '//' : return '' if path . startswith ( '//' ) : norm = normpath ( path [ 2 : ] ) if norm [ 0 ] in ( '.' , '/' , '\\' ) : raise ValueError ( "Invalid path: `{}'" . format ( path ) ) return norm if path . startswith ( '/' ) : raise ValueError ( "Invalid path: `{}' - use '//' to sta...
def _connect ( self ) : """Connect to the socket ."""
try : while True : _LOGGER . info ( 'Trying to connect to %s' , self . server_address ) try : yield from asyncio . wait_for ( self . loop . create_connection ( lambda : self . protocol , * self . server_address ) , self . reconnect_timeout , loop = self . loop ) self . tcp_ch...
def version ( self ) : """Return ( generating first if needed ) version hash ."""
if not self . _version : self . _version = hashlib . md5 ( self . rendered . encode ( ) ) . hexdigest ( ) [ : 8 ] return self . _version
def save ( self , form , name , composite_form , commit ) : """This method is called by : meth : ` django _ superform . forms . SuperModelForm . save ` in order to save the modelform that this field takes care of and calls on the nested form ' s ` ` save ( ) ` ` method . But only if : meth : ` ~ django _ su...
if self . shall_save ( form , name , composite_form ) : return composite_form . save ( commit = commit ) return None
def cli ( ctx ) : """PyHardLinkBackup"""
click . secho ( "\nPyHardLinkBackup v%s\n" % PyHardLinkBackup . __version__ , bg = "blue" , fg = "white" , bold = True )
def nanprod ( values , axis = None , skipna = True , min_count = 0 , mask = None ) : """Parameters values : ndarray [ dtype ] axis : int , optional skipna : bool , default True min _ count : int , default 0 mask : ndarray [ bool ] , optional nan - mask if known Returns result : dtype Examples > ...
if mask is None : mask = isna ( values ) if skipna and not is_any_int_dtype ( values ) : values = values . copy ( ) values [ mask ] = 1 result = values . prod ( axis ) return _maybe_null_out ( result , axis , mask , min_count = min_count )
def error ( code , message , ** kwargs ) : """Call this to raise an exception and have it stored in the journal"""
assert code in Logger . _error_code_to_exception exc_type , domain = Logger . _error_code_to_exception [ code ] exc = exc_type ( message , ** kwargs ) Logger . _log ( code , exc . message , ERROR , domain ) raise exc
def file_source ( self , filename ) : """Return a list of namedtuple ` Line ` for each line of code found in the source file with the given ` filename ` ."""
lines = [ ] try : with self . filesystem . open ( filename ) as f : line_statuses = dict ( self . line_statuses ( filename ) ) for lineno , source in enumerate ( f , start = 1 ) : line_status = line_statuses . get ( lineno ) line = Line ( lineno , source , line_status , None ...
def create_html ( self ) : """Create a HTML page for this BAM file ."""
roc_dicts = [ ] with open ( self . _roc_fn , "r" ) as roc : for line in roc : line = line . strip ( ) if line != "" and line [ 0 ] != "#" : ( q , M , w , m , P , U , u , T , t , x , a ) = map ( int , line . split ( "\t" ) ) roc_dict = { "q" : q , "M" : M , "w" : w , "m" : m ,...
def parse_timemap_from_blocks ( profile_block_list ) : """Build a map from times to line _ profile blocks"""
prefix_list = [ ] timemap = ut . ddict ( list ) for ix in range ( len ( profile_block_list ) ) : block = profile_block_list [ ix ] total_time = get_block_totaltime ( block ) # Blocks without time go at the front of sorted output if total_time is None : prefix_list . append ( block ) # Blocks...
def poll ( self , timeout_ms = None , future = None ) : """Try to read and write to sockets . This method will also attempt to complete node connections , refresh stale metadata , and run previously - scheduled tasks . Arguments : timeout _ ms ( int , optional ) : maximum amount of time to wait ( in ms ) ...
if future is not None : timeout_ms = 100 elif timeout_ms is None : timeout_ms = self . config [ 'request_timeout_ms' ] elif not isinstance ( timeout_ms , ( int , float ) ) : raise TypeError ( 'Invalid type for timeout: %s' % type ( timeout_ms ) ) # Loop for futures , break after first loop if None responses...
def main ( ) : """Testing function for DFA brzozowski algebraic method Operation"""
argv = sys . argv if len ( argv ) < 2 : targetfile = 'target.y' else : targetfile = argv [ 1 ] print 'Parsing ruleset: ' + targetfile , flex_a = Flexparser ( ) mma = flex_a . yyparse ( targetfile ) print 'OK' print 'Perform minimization on initial automaton:' , mma . minimize ( ) print 'OK' print 'Perform Brzoz...
def recode ( self , table : pd . DataFrame , validate = False ) -> pd . DataFrame : """Pass the appropriate columns through each recoder function sequentially and return the final result . Args : table ( pd . DataFrame ) : A dataframe on which to apply recoding logic . validate ( bool ) : If ` ` True ` ` , re...
raise NotImplementedError ( "This method must be defined for each subclass." )
def auto_init_default ( column ) : """Set the default value for a column when it ' s first accessed rather than first committed to the database ."""
if isinstance ( column , ColumnProperty ) : default = column . columns [ 0 ] . default else : default = column . default @ event . listens_for ( column , 'init_scalar' , retval = True , propagate = True ) def init_scalar ( target , value , dict_ ) : # A subclass may override the column and not provide a default...
def convert_uen ( pinyin ) : """uen 转换 , 还原原始的韵母 iou , uei , uen前面加声母的时候 , 写成iu , ui , un 。 例如niu ( 牛 ) , gui ( 归 ) , lun ( 论 ) 。"""
return UN_RE . sub ( lambda m : m . group ( 1 ) + UN_MAP [ m . group ( 2 ) ] , pinyin )
def vi_score ( self , x , index ) : """Wrapper function for selecting appropriate score Parameters x : float A random variable index : int 0 or 1 depending on which latent variable Returns The gradient of the scale latent variable at x"""
if index == 0 : return self . vi_loc_score ( x ) elif index == 1 : return self . vi_scale_score ( x )
def _initLayerCtors ( self ) : '''Registration for built - in Layer ctors'''
ctors = { 'lmdb' : s_lmdblayer . LmdbLayer , 'remote' : s_remotelayer . RemoteLayer , } self . layrctors . update ( ** ctors )
def increaseScore ( self , participant ) : """The participant successfully transferred a chunk to me ."""
if participant not in self . scores : self . scores [ participant ] = 0 self . scores [ participant ] += 1
def _getImageSize ( filename ) : """Try to get the width and height of a bmp of png image file"""
result = None file = open ( filename , 'rb' ) if file . read ( 8 ) == b'\x89PNG\r\n\x1a\n' : # PNG while 1 : length , = _struct . unpack ( '>i' , file . read ( 4 ) ) chunkID = file . read ( 4 ) if chunkID == '' : # EOF break if chunkID == b'IHDR' : # return width , height...
def get ( self ) : r'''An HTTP stream of the Salt master event bus This stream is formatted per the Server Sent Events ( SSE ) spec . Each event is formatted as JSON . . . http : get : : / events : status 200 : | 200 | : status 401 : | 401 | : status 406 : | 406 | * * Example request : * * . . code ...
# if you aren ' t authenticated , redirect to login if not self . _verify_auth ( ) : self . redirect ( '/login' ) return # set the streaming headers self . set_header ( 'Content-Type' , 'text/event-stream' ) self . set_header ( 'Cache-Control' , 'no-cache' ) self . set_header ( 'Connection' , 'keep-alive' ) sel...
def string_avg ( strings , binary = True ) : """Takes a list of strings of equal length and returns a string containing the most common value from each index in the string . Optional argument : binary - a boolean indicating whether or not to treat strings as binary numbers ( fill in leading zeros if lengths d...
if binary : # Assume this is a binary number and fill leading zeros strings = deepcopy ( strings ) longest = len ( max ( strings , key = len ) ) for i in range ( len ( strings ) ) : while len ( strings [ i ] ) < longest : split_string = strings [ i ] . split ( "b" ) strings [...
def compile_datetime ( rule ) : """Compiler helper method : attempt to compile constant into object representing datetime object to enable relations and thus simple comparisons using Python operators ."""
if isinstance ( rule . value , datetime . datetime ) : return rule try : # Try numeric type return DatetimeRule ( datetime . datetime . fromtimestamp ( float ( rule . value ) ) ) except ( TypeError , ValueError ) : pass # Try RFC3339 timestamp string res = TIMESTAMP_RE . match ( str ( rule . value ) ) if re...
def categories ( self ) : """List [ : class : ` CategoryChannel ` ] : A list of categories that belongs to this guild . This is sorted by the position and are in UI order from top to bottom ."""
r = [ ch for ch in self . _channels . values ( ) if isinstance ( ch , CategoryChannel ) ] r . sort ( key = lambda c : ( c . position , c . id ) ) return r
def find_content ( self , text ) : """Find content ."""
if self . trigraphs : text = RE_TRIGRAPHS . sub ( self . process_trigraphs , text ) for m in self . pattern . finditer ( self . norm_nl ( text ) ) : self . evaluate ( m )
def get_unit_property ( self , unit_id , property_name ) : '''This function rerturns the data stored under the property name given from the given unit . Parameters unit _ id : int The unit id for which the property will be returned property _ name : str The name of the property Returns value The d...
if isinstance ( unit_id , ( int , np . integer ) ) : if unit_id in self . get_unit_ids ( ) : if unit_id not in self . _unit_properties : self . _unit_properties [ unit_id ] = { } if isinstance ( property_name , str ) : if property_name in list ( self . _unit_properties [ unit...
def get_xpath_frequencydistribution ( paths ) : """Build and return a frequency distribution over xpath occurrences ."""
# " html / body / div / div / text " - > [ " html " , " body " , " div " , " div " , " text " ] splitpaths = [ p . rsplit ( '/' , 1 ) for p in paths ] # get list of " parentpaths " by right - stripping off the last xpath - node , # effectively getting the parent path # thanks to eugene - eeo for optimization parentpath...
def randomColor ( self ) : """Generates a random color . : return < QColor >"""
r = random . randint ( 120 , 180 ) g = random . randint ( 120 , 180 ) b = random . randint ( 120 , 180 ) return QColor ( r , g , b )
def compare ( self , first , second ) : """Case in - sensitive comparison of two strings . Required arguments : * first - The first string to compare . * second - The second string to compare ."""
if first . lower ( ) == second . lower ( ) : return True else : return False
def fs_obj_remove ( self , path ) : """Removes a file system object ( file , symlink , etc ) in the guest . Will not work on directories , use : py : func : ` IGuestSession . directory _ remove ` to remove directories . This method will remove symbolic links in the final path component , not follow them . ...
if not isinstance ( path , basestring ) : raise TypeError ( "path can only be an instance of type basestring" ) self . _call ( "fsObjRemove" , in_p = [ path ] )
def append ( self , other ) : """Appends stars from another StarPopulations , in place . : param other : Another : class : ` StarPopulation ` ; must have same columns as ` ` self ` ` ."""
if not isinstance ( other , StarPopulation ) : raise TypeError ( 'Only StarPopulation objects can be appended to a StarPopulation.' ) if not np . all ( self . stars . columns == other . stars . columns ) : raise ValueError ( 'Two populations must have same columns to combine them.' ) if len ( self . constraints...
def _build_showstr ( self , seed ) : """Returns show ( ) display string for data attribute"""
output = [ "%s (%s) data" % ( seed , self . params [ 'lang' ] ) ] output . append ( '{' ) maxwidth = WPToolsQuery . MAXWIDTH for item in sorted ( self . data ) : if self . data [ item ] is None : continue prefix = item value = self . data [ item ] if isinstance ( value , dict ) : prefix ...
def visit_attribute ( self , node ) : """return an astroid . Getattr node as string"""
return "%s.%s" % ( self . _precedence_parens ( node , node . expr ) , node . attrname )
def parse_vars_and_interpolations ( self , string ) : """Parse a string for variables and interpolations , but don ' t treat anything else as Sass syntax . Returns an AST node ."""
# Shortcut : if there are no # s or $ s in the string in the first place , # it must not have anything of interest . if '#' not in string and '$' not in string : return Literal ( String . unquoted ( string ) ) return self . parse_expression ( string , 'goal_interpolated_literal_with_vars' )
def prepend_scheme_if_needed ( url , new_scheme ) : """Given a URL that may or may not have a scheme , prepend the given scheme . Does not replace a present scheme with the one provided as an argument . : rtype : str"""
scheme , netloc , path , params , query , fragment = urlparse ( url , new_scheme ) # urlparse is a finicky beast , and sometimes decides that there isn ' t a # netloc present . Assume that it ' s being over - cautious , and switch netloc # and path if urlparse decided there was no netloc . if not netloc : netloc , ...
def phone_number ( self , phone_number ) : """Sets the phone _ number of this OrderFulfillmentRecipient . The phone number of the fulfillment recipient . If provided , overrides the value from customer profile indicated by customer _ id . : param phone _ number : The phone _ number of this OrderFulfillmentRecip...
if phone_number is None : raise ValueError ( "Invalid value for `phone_number`, must not be `None`" ) if len ( phone_number ) > 16 : raise ValueError ( "Invalid value for `phone_number`, length must be less than `16`" ) self . _phone_number = phone_number
def set_parent ( self , parent ) : """Args : - * * parent * * ( ( : class : ` ~ pyFG . forticonfig . FortiConfig ` ) : FortiConfig object you want to set as parent ."""
self . parent = parent if self . config_type == 'edit' : self . rel_path_fwd = 'edit %s\n' % self . get_name ( ) self . rel_path_bwd = 'next\n' elif self . config_type == 'config' : self . rel_path_fwd = 'config %s\n' % self . get_name ( ) self . rel_path_bwd = 'end\n' self . full_path_fwd = '%s%s' % ( ...
def apply ( self , docs , split = 0 , clear = True , parallelism = None , progress_bar = True ) : """Run the CandidateExtractor . : Example : To extract candidates from a set of training documents using 4 cores : : candidate _ extractor . apply ( train _ docs , split = 0 , parallelism = 4) : param docs : Se...
super ( CandidateExtractor , self ) . apply ( docs , split = split , clear = clear , parallelism = parallelism , progress_bar = progress_bar , )
def get_documents_in_database ( self , with_id = True ) : """Gets all documents in database : param with _ id : True iff each document should also come with its id : return : List of documents in collection in database"""
documents = [ ] for coll in self . get_collection_names ( ) : documents += self . get_documents_in_collection ( coll , with_id = with_id ) return documents
def get_contained_pyversions ( marker ) : """Collect all ` python _ version ` operands from a marker ."""
collection = [ ] if not marker : return set ( ) marker = _ensure_marker ( marker ) # Collect the ( Variable , Op , Value ) tuples and string joiners from the marker _markers_collect_pyversions ( marker . _markers , collection ) marker_str = " and " . join ( sorted ( collection ) ) if not marker_str : return set...
def get_output_fields ( self ) : """Get field names from output template ."""
# Re - engineer list from output format # XXX TODO : Would be better to use a FieldRecorder class to catch the full field names emit_fields = list ( i . lower ( ) for i in re . sub ( r"[^_A-Z]+" , ' ' , self . format_item ( None ) ) . split ( ) ) # Validate result result = [ ] for name in emit_fields [ : ] : if nam...
def _warn_unsafe_options ( cls , args ) : '''Print warnings about any enabled hazardous options . This function will print messages complaining about : * ` ` - - save - headers ` ` * ` ` - - no - iri ` ` * ` ` - - output - document ` ` * ` ` - - ignore - fatal - errors ` `'''
enabled_options = [ ] for option_name in cls . UNSAFE_OPTIONS : if getattr ( args , option_name ) : enabled_options . append ( option_name ) if enabled_options : _logger . warning ( __ ( _ ( 'The following unsafe options are enabled: {list}.' ) , list = enabled_options ) ) _logger . warning ( _ ( 'T...
def delete ( self ) : """Delete the task . > > > from pytodoist import todoist > > > user = todoist . login ( ' john . doe @ gmail . com ' , ' password ' ) > > > project = user . get _ project ( ' Homework ' ) > > > task = project . add _ task ( ' Read Chapter 4 ' ) > > > task . delete ( )"""
args = { 'ids' : [ self . id ] } _perform_command ( self . project . owner , 'item_delete' , args ) del self . project . owner . tasks [ self . id ]
def clear_data ( self ) : """Clear both ontology and annotation data . Parameters Returns None"""
self . clear_annotation_data ( ) self . terms = { } self . _alt_id = { } self . _syn2id = { } self . _name2id = { } self . _flattened = False
def remove_object ( collision_object ) : """Remove the collision object from the Manager"""
global collidable_objects if isinstance ( collision_object , CollidableObj ) : # print " Collision object of type " , type ( collision _ object ) , " removed from the collision manager . " try : collidable_objects . remove ( collision_object ) except : print "Ragnarok Says: Collision_Obj...
def process_response ( self , request , response ) : """Shares config with the language cookie as they serve a similar purpose"""
if hasattr ( request , 'COUNTRY_CODE' ) : response . set_cookie ( key = constants . COUNTRY_COOKIE_NAME , value = request . COUNTRY_CODE , max_age = settings . LANGUAGE_COOKIE_AGE , path = settings . LANGUAGE_COOKIE_PATH , domain = settings . LANGUAGE_COOKIE_DOMAIN ) return response
def update_lists ( self ) : """Update packages list and ChangeLog . txt file after upgrade distribution"""
print ( "{0}Update the package lists ?{1}" . format ( self . meta . color [ "GREEN" ] , self . meta . color [ "ENDC" ] ) ) print ( "=" * 79 ) if self . msg . answer ( ) in [ "y" , "Y" ] : Update ( ) . repository ( [ "slack" ] )
def kill_monitor ( self , check_alive = True ) : """Kill the monitor . Args : check _ alive ( bool ) : Raise an exception if the process was already dead ."""
self . _kill_process_type ( ray_constants . PROCESS_TYPE_MONITOR , check_alive = check_alive )
def set_inteface_up ( devid , ifindex , auth , url ) : """function takest devid and ifindex of specific device and interface and issues a RESTFUL call to " undo shut " the spec ified interface on the target device . : param devid : int or str value of the target device : param ifindex : int or str value of th...
set_int_up_url = "/imcrs/plat/res/device/" + str ( devid ) + "/interface/" + str ( ifindex ) + "/up" f_url = url + set_int_up_url try : r = requests . put ( f_url , auth = auth , headers = HEADERS ) # creates the URL using the payload variable as the contents if r . status_code == 204 : return r . s...
def results ( self , trial_ids ) : """Accepts a sequence of trial ids and returns a pandas dataframe with the schema trial _ id , iteration ? , * metric _ schema _ union where iteration is an optional column that specifies the iteration when a user logged a metric , if the user supplied one . The iteration ...
metadata_folder = os . path . join ( self . log_dir , constants . METADATA_FOLDER ) dfs = [ ] # TODO : various file - creation corner cases like the result file not # always existing if stuff is not logged and etc should be ironed out # ( would probably be easier if we had a centralized Sync class which # relied on som...
def runctx ( self , cmd , globals , locals ) : """Similar to profile . Profile . runctx ."""
with self ( ) : exec ( cmd , globals , locals ) return self
def assign_dna_reads_to_dna_database ( query_fasta_fp , database_fasta_fp , out_fp , params = { } ) : """Wraps assign _ reads _ to _ database , setting various parameters . The default settings are below , but may be overwritten and / or added to using the params dict : algorithm : bwasw"""
my_params = { 'algorithm' : 'bwasw' } my_params . update ( params ) result = assign_reads_to_database ( query_fasta_fp , database_fasta_fp , out_fp , my_params ) return result
def t_STATESHEADER ( self , token ) : ur'\ # \ # \ s + < states - list > ( ? P < title > [ ^ < \ n ] * ) \ n'
title = token . lexer . lexmatch . group ( "title" ) . decode ( "utf8" ) token . value = title token . lexer . lineno += 1 return token
def get_collections ( self , pattern = "*" , libtype = "*" ) : """Returns a list of collection name / summary tuples"""
sql = """SELECT collection.collection_id, collection.name, collection.doc, collection.type, collection.path FROM collection_table as collection WHERE name like ? AND type like ? ORDER BY collection.name """ cursor ...
def download ( self , path = None , show_progress = True , resume = True , auto_retry = True , proapi = False ) : """Download this file"""
self . api . download ( self , path , show_progress , resume , auto_retry , proapi )
def remove_from_parent ( self ) : """Removes this node from the parent ' s ` ` children ` ` collection if it exists ."""
parent = self . parent if parent is not None : try : children = parent . children except AttributeError : pass else : remove_upto_once ( children , self )
def get ( self ) : """* translate the coordinates * * * Return : * * - ` ` ra ` ` - - the right - ascension of the translated coordinate - ` ` dec ` ` - - the declination of the translated coordinate"""
self . log . info ( 'starting the ``get`` method' ) # PRECISION TEST decprecision = len ( repr ( self . dec ) . split ( "." ) [ - 1 ] ) raprecision = len ( repr ( self . ra ) . split ( "." ) [ - 1 ] ) dec2 = self . dec + self . north ra2 = self . ra + ( ( self . east ) / ( math . cos ( ( self . dec + dec2 ) * self . DE...
def print_row ( value , num_blocks , val_min , color ) : """A method to print a row for a horizontal graphs . i . e : 1 : ▇ ▇ 2 2 : ▇ ▇ ▇ 3 3 : ▇ ▇ ▇ ▇ 4"""
if color : sys . stdout . write ( f'\033[{color}m' ) # Start to write colorized . if num_blocks < 1 and ( value > val_min or value > 0 ) : # Print something if it ' s not the smallest # and the normal value is less than one . sys . stdout . write ( SM_TICK ) else : for _ in range ( num_blocks ) : sy...
def email_match ( string ) : """邮箱地址匹配 . 匹配成功返回 ( email _ name , email _ server ) , 否则返回None"""
m = re . match ( email_pattern , string ) if m : # print ( ' Match success : % s ' % m . string ) return m . groups ( ) [ 0 ] , m . groups ( ) [ 2 ] else : # print ( ' Match failed : % s ' % string ) return None
def prefixes_to_fns ( self , prefixes : List [ str ] ) -> Tuple [ List [ str ] , List [ str ] ] : """Fetches the file paths to the features files and labels files corresponding to the provided list of features"""
# TODO Return pathlib . Paths feat_fns = [ str ( self . feat_dir / ( "%s.%s.npy" % ( prefix , self . feat_type ) ) ) for prefix in prefixes ] label_fns = [ str ( self . label_dir / ( "%s.%s" % ( prefix , self . label_type ) ) ) for prefix in prefixes ] return feat_fns , label_fns
def dynamize_range_key_condition ( self , range_key_condition ) : """Convert a layer2 range _ key _ condition parameter into the structure required by Layer1."""
d = None if range_key_condition : d = { } for range_value in range_key_condition : range_condition = range_key_condition [ range_value ] if range_condition == 'BETWEEN' : if isinstance ( range_value , tuple ) : avl = [ self . dynamize_value ( v ) for v in range_value ...
def get_output_row_heights ( table , spans ) : """Get the heights of the rows of the output table . Parameters table : list of lists of str spans : list of lists of int Returns heights : list of int The heights of each row in the output table"""
heights = [ ] for row in table : heights . append ( - 1 ) for row in range ( len ( table ) ) : for column in range ( len ( table [ row ] ) ) : text = table [ row ] [ column ] span = get_span ( spans , row , column ) row_count = get_span_row_count ( span ) height = len ( text . sp...
def get_localhost ( ) : '''Should return 127.0.0.1 in ipv4 and : : 1 in ipv6 localhost is not used because on windows vista / windows 7 , there can be issues where the resolving doesn ' t work properly and takes a lot of time ( had this issue on the pyunit server ) . Using the IP directly solves the problem ....
# TODO : Needs better investigation ! global _cache if _cache is None : try : for addr_info in socket . getaddrinfo ( "localhost" , 80 , 0 , 0 , socket . SOL_TCP ) : config = addr_info [ 4 ] if config [ 0 ] == '127.0.0.1' : _cache = '127.0.0.1' return ...
def getGraphFieldList ( self , graph_name ) : """Returns list of names of fields for graph with name graph _ name . @ param graph _ name : Graph Name @ return : List of field names for graph ."""
graph = self . _getGraph ( graph_name , True ) return graph . getFieldList ( )
def _set_categories ( self ) : """Inplace conversion from categories ."""
for column , _ in self . _categories . items ( ) : if column in self . columns : self [ column ] = self [ column ] . astype ( 'category' )
def get_host ( self ) : """returns the host computer running this program"""
import socket host_name = socket . gethostname ( ) for h in hosts : if h [ 'name' ] == host_name : return h [ 'type' ] , h [ 'name' ] return dict ( type = 'Unknown' , name = host_name )
def check_state ( self , pair , state ) : """Updates the state of a check ."""
self . __log_info ( 'Check %s %s -> %s' , pair , pair . state , state ) pair . state = state
def get_medium_order ( self , lower = 200000 , higher = 1000000 ) : """return medium Keyword Arguments : lower { [ type ] } - - [ description ] ( default : { 200000 } ) higher { [ type ] } - - [ description ] ( default : { 100000 } ) Returns : [ type ] - - [ description ]"""
return self . data . query ( 'amount>={}' . format ( lower ) ) . query ( 'amount<={}' . format ( higher ) )
def find_base_style ( masters ) : """Find a base style shared between all masters . Return empty string if none is found ."""
if not masters : return "" base_style = ( masters [ 0 ] . name or "" ) . split ( ) for master in masters : style = master . name . split ( ) base_style = [ s for s in style if s in base_style ] base_style = " " . join ( base_style ) return base_style
def get_property_names ( obj ) : """Recursively gets names of all properties implemented in specified object and its subobjects . The object can be a user defined object , map or array . Returned property name correspondently are object properties , map keys or array indexes . : param obj : an object to intro...
property_names = [ ] if obj != None : cycle_detect = [ ] RecursiveObjectReader . _perform_get_property_names ( obj , None , property_names , cycle_detect ) return property_names
def largest_prime_factor ( n : int ) : """Return the largest prime factor of n . Assume n > 1 and is not a prime . > > > largest _ prime _ factor ( 13195) 29 > > > largest _ prime _ factor ( 2048)"""
assert n > 1 for i in range ( 2 , int ( n ** 0.5 ) + 1 ) : if n % i : continue return largest_prime_factor ( n // i ) return n
def jpath_parse_c ( jpath ) : """Caching variant of : py : func : ` jpath _ parse ` function . Same arguments and return value . For performance reasons thee is no copying and all returned values are references to internal cache . Treat the returned values as read only , or suffer the consequences ."""
if not jpath in _JPATH_CACHE : _JPATH_CACHE [ jpath ] = jpath_parse ( jpath ) return _JPATH_CACHE [ jpath ]
def backdoor_handler ( clientsock , namespace = None ) : """start an interactive python interpreter on an existing connection . . note : : this function will block for as long as the connection remains alive . : param sock : the socket on which to serve the interpreter : type sock : : class : ` Socket < gre...
namespace = { } if namespace is None else namespace . copy ( ) console = code . InteractiveConsole ( namespace ) multiline_statement = [ ] stdout , stderr = StringIO ( ) , StringIO ( ) clientsock . sendall ( PREAMBLE + "\n" + PS1 ) for input_line in _produce_lines ( clientsock ) : input_line = input_line . rstrip (...
def queryFilter ( self , function = None ) : """Defines a decorator that can be used to filter queries . It will assume the function being associated with the decorator will take a query as an input and return a modified query to use . : usage class MyModel ( orb . Model ) : objects = orb . ReverseLooku...
if function is not None : self . __query_filter = function return function def wrapper ( func ) : self . __query_filter = func return func return wrapper
def asserts ( input_value , rule , message = '' ) : """this function allows you to write asserts in generators since there are moments where you actually want the program to halt when certain values are seen ."""
assert callable ( rule ) or type ( rule ) == bool , 'asserts needs rule to be a callable function or a test boolean' assert isinstance ( message , str ) , 'asserts needs message to be a string' # if the message is empty and rule is callable , fill message with rule ' s source code if len ( message ) == 0 and callable (...
def open_conn ( host , db , user , password , retries = 0 , sleep = 0.5 ) : '''Return an open mysql db connection using the given credentials . Use ` retries ` and ` sleep ` to be robust to the occassional transient connection failure . retries : if an exception when getting the connection , try again at most...
assert retries >= 0 try : return MySQLdb . connect ( host = host , user = user , passwd = password , db = db ) except Exception : if retries > 0 : time . sleep ( sleep ) return open_conn ( host , db , user , password , retries - 1 , sleep ) else : raise
def title ( self ) : """The title placeholder shape on the slide or | None | if the slide has no title placeholder ."""
for elm in self . _spTree . iter_ph_elms ( ) : if elm . ph_idx == 0 : return self . _shape_factory ( elm ) return None
def AdvancedJsonify ( data , status_code ) : """Advanced Jsonify Response Maker : param data : Data : param status _ code : Status _ code : return : Response"""
response = jsonify ( data ) response . status_code = status_code return response
def copy_info ( self , other , ignore = None ) : """Copies " info " from this file to the other . " Info " is defined all groups that are not the samples group . Parameters other : output file The output file . Must be an hdf file . ignore : ( list of ) str Don ' t copy the given groups ."""
logging . info ( "Copying info" ) # copy non - samples / stats data if ignore is None : ignore = [ ] if isinstance ( ignore , ( str , unicode ) ) : ignore = [ ignore ] ignore = set ( ignore + [ self . samples_group ] ) copy_groups = set ( self . keys ( ) ) - ignore for key in copy_groups : super ( BaseInfer...
def makeEquilibriumTable ( out_filename , four_in_files , CRRA ) : '''Make the equilibrium statistics table for the paper , saving it as a tex file in the tables folder . Also makes a version for the slides that doesn ' t use the table environment , nor include the note at bottom . Parameters out _ filename...
# Read in statistics from the four files SOEfrictionless = np . genfromtxt ( results_dir + four_in_files [ 0 ] + 'Results.csv' , delimiter = ',' ) SOEsticky = np . genfromtxt ( results_dir + four_in_files [ 1 ] + 'Results.csv' , delimiter = ',' ) DSGEfrictionless = np . genfromtxt ( results_dir + four_in_files [ 2 ] + ...
def allVariantAnnotationSets ( self ) : """Return an iterator over all variant annotation sets in the data repo"""
for dataset in self . getDatasets ( ) : for variantSet in dataset . getVariantSets ( ) : for vaSet in variantSet . getVariantAnnotationSets ( ) : yield vaSet
def _get_path ( name , settings , mkdir = True ) : """Generate a project path ."""
default_projects_path = settings . config . get ( "projects_path" ) path = None if default_projects_path : path = raw_input ( "\nWhere would you like to create this project? [{0}/{1}] " . format ( default_projects_path , name ) ) if not path : path = os . path . join ( default_projects_path , name ) els...
def embed ( args ) : """% prog embed evidencefile scaffolds . fasta contigs . fasta Use SSPACE evidencefile to scaffold contigs into existing scaffold structure , as in ` scaffolds . fasta ` . Contigs . fasta were used by SSPACE directly to scaffold . Rules : 1 . Only update existing structure by embeddin...
p = OptionParser ( embed . __doc__ ) p . set_mingap ( default = 10 ) p . add_option ( "--min_length" , default = 200 , type = "int" , help = "Minimum length to consider [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) evidencefile , scaffolds ...
async def load_remote ( self , email : str , password : str , skip_existing : bool = True ) -> None : """Create a local client ."""
auth_resp = await self . _request ( 'post' , 'https://my.rainmachine.com/login/auth' , json = { 'user' : { 'email' : email , 'pwd' : password , 'remember' : 1 } } ) access_token = auth_resp [ 'access_token' ] sprinklers_resp = await self . _request ( 'post' , 'https://my.rainmachine.com/devices/get-sprinklers' , access...
async def bluetooth_scan ( ) : """Get nearby bluetooth devices ."""
async with aiohttp . ClientSession ( ) as session : ghlocalapi = Bluetooth ( LOOP , session , IPADDRESS ) await ghlocalapi . scan_for_devices ( ) # Start device scan await ghlocalapi . get_scan_result ( ) # Returns the result print ( "Device info:" , ghlocalapi . devices )
def asDictionary ( self ) : """returns the object as a python dictionary"""
value = self . _dict if value is None : template = { "hasM" : self . _hasM , "hasZ" : self . _hasZ , "paths" : [ ] , "spatialReference" : self . spatialReference } for part in self . _paths : lpart = [ ] for pt in part : lpart . append ( pt . asList ) template [ 'paths' ] . a...
def send_templated_email ( recipients , template_path , context = None , from_email = settings . DEFAULT_FROM_EMAIL , fail_silently = False , extra_headers = None ) : """recipients can be either a list of emails or a list of users , if it is users the system will change to the language that the user has set as ...
recipient_pks = [ r . pk for r in recipients if isinstance ( r , get_user_model ( ) ) ] recipient_emails = [ e for e in recipients if not isinstance ( e , get_user_model ( ) ) ] send = _send_task . delay if use_celery else _send msg = send ( recipient_pks , recipient_emails , template_path , context , from_email , fail...
def cleanup_lines ( lines , ** kwargs ) : '''Cleans up annotation after syntactic pre - processing and processing : - - Removes embedded clause boundaries " < { > " and " < } > " ; - - Removes CLBC markings from analysis ; - - Removes additional information between < and > from analysis ; - - Removes additi...
if not isinstance ( lines , list ) : raise Exception ( '(!) Unexpected type of input argument! Expected a list of strings.' ) remove_caps = False remove_clo = False double_quotes = None fix_sent_tags = False for argName , argVal in kwargs . items ( ) : if argName in [ 'remove_caps' , 'remove_cap' ] : re...
def create_xml_path ( path , ** kwargs ) : '''Start a transient domain based on the XML - file path passed to the function : param path : path to a file containing the libvirt XML definition of the domain : param connection : libvirt connection URI , overriding defaults . . versionadded : : 2019.2.0 : param...
try : with salt . utils . files . fopen ( path , 'r' ) as fp_ : return create_xml_str ( salt . utils . stringutils . to_unicode ( fp_ . read ( ) ) , ** kwargs ) except ( OSError , IOError ) : return False
def get_channels_by_sln_year_quarter ( self , channel_type , sln , year , quarter ) : """Search for all channels by sln , year and quarter"""
return self . search_channels ( type = channel_type , tag_sln = sln , tag_year = year , tag_quarter = quarter )
def save_snps ( self , filename = None ) : """Save SNPs to file . Parameters filename : str filename for file to save Returns str path to file in output directory if SNPs were saved , else empty str"""
comment = ( "# Source(s): {}\n" "# Assembly: {}\n" "# SNPs: {}\n" "# Chromosomes: {}\n" . format ( self . source , self . assembly , self . snp_count , self . chromosomes_summary ) ) if filename is None : filename = self . get_var_name ( ) + "_lineage_" + self . assembly + ".csv" return lineage . save_df_as_csv ( s...
def cylinder_and_strand ( self ) : '''Display the protein secondary structure as a white , solid tube and the alpha - helices as yellow cylinders .'''
top = self . topology # We build a mini - state machine to find the # start end of helices and such in_helix = False helices_starts = [ ] helices_ends = [ ] coils = [ ] coil = [ ] for i , typ in enumerate ( top [ 'secondary_structure' ] ) : if typ == 'H' : if in_helix == False : # We become helices ...
def inbreeding_coefficient ( g , fill = np . nan ) : """Calculate the inbreeding coefficient for each variant . Parameters g : array _ like , int , shape ( n _ variants , n _ samples , ploidy ) Genotype array . fill : float , optional Use this value for variants where the expected heterozygosity is zero...
# check inputs if not hasattr ( g , 'count_het' ) or not hasattr ( g , 'count_called' ) : g = GenotypeArray ( g , copy = False ) # calculate observed and expected heterozygosity ho = heterozygosity_observed ( g ) af = g . count_alleles ( ) . to_frequencies ( ) he = heterozygosity_expected ( af , ploidy = g . shape ...
def get_current_user ( ) : """Return a TOKEN _ USER for the owner of this process ."""
process = OpenProcessToken ( ctypes . windll . kernel32 . GetCurrentProcess ( ) , TokenAccess . TOKEN_QUERY ) return GetTokenInformation ( process , TOKEN_USER )
def get_field_value ( self , name , raw = False ) : """Tries getting the value of the given field . Tries it in the following order : show ( standard nice display ) , value ( raw value ) , showname ( extended nice display ) . : param name : The name of the field : param raw : Only return raw value : return ...
field = self . get_field ( name ) if field is None : return if raw : return field . raw_value return field
def games_by_time ( self , start_game , end_game ) : """Given a range of games , return the games sorted by time . Returns [ ( time , game _ number ) , . . . ] The time will be a ` datetime . datetime ` and the game number is the integer used as the basis of the row ID . Note that when a cluster of self - p...
move_count = b'move_count' rows = self . bt_table . read_rows ( ROWCOUNT_PREFIX . format ( start_game ) , ROWCOUNT_PREFIX . format ( end_game ) , filter_ = bigtable_row_filters . ColumnRangeFilter ( METADATA , move_count , move_count ) ) def parse ( r ) : rk = str ( r . row_key , 'utf-8' ) game = _game_from_cou...
def validate ( validation , dictionary ) : """Validate that a dictionary passes a set of key - based validators . If all of the keys in the dictionary are within the parameters specified by the validation mapping , then the validation passes . : param validation : a mapping of keys to validators : type ...
errors = defaultdict ( list ) for key in validation : if isinstance ( validation [ key ] , ( list , tuple ) ) : if Required in validation [ key ] : if not Required ( key , dictionary ) : errors [ key ] = [ "must be present" ] continue _validate_list_helper...
def set_value ( dictionary , keys , value ) : """Similar to Python ' s built in ` dictionary [ key ] = value ` , but takes a list of nested keys instead of a single key . set _ value ( { ' a ' : 1 } , [ ] , { ' b ' : 2 } ) - > { ' a ' : 1 , ' b ' : 2} set _ value ( { ' a ' : 1 } , [ ' x ' ] , 2 ) - > { ' a ' ...
if not keys : dictionary . update ( value ) return for key in keys [ : - 1 ] : if key not in dictionary : dictionary [ key ] = { } dictionary = dictionary [ key ] dictionary [ keys [ - 1 ] ] = value