signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def file_or_path ( file ) : """Open a file and return the handler if a path is given . If a file handler is given , return it directly . : param file : A file handler or path to a file . : returns : A tuple with the open file handler and whether it was a path . : rtype : ( file , bool )"""
is_path = False if isinstance ( file , string_types ) : if not os . path . exists ( file ) : raise IOError ( 'File at path ' + file + ' does not exist.' ) file = open ( file , 'rb' ) is_path = True return file , is_path
def add ( self , f , name = None , types = None , required = None ) : """Adds a new method to the jsonrpc service . Arguments : f - - the remote function name - - name of the method in the jsonrpc service types - - list or dictionary of the types of accepted arguments required - - list of required keyword...
if name is None : fname = f . __name__ # Register the function using its own name . else : fname = name self . method_data [ fname ] = { 'method' : f } if types is not None : self . method_data [ fname ] [ 'types' ] = types if required is not None : self . method_data [ fname ] [ 'required' ...
def add_transcription ( self , gene : Gene , rna : Union [ Rna , MicroRna ] ) -> str : """Add a transcription relation from a gene to an RNA or miRNA node . : param gene : A gene node : param rna : An RNA or microRNA node"""
return self . add_unqualified_edge ( gene , rna , TRANSCRIBED_TO )
def get_bounding_box ( self ) : """Returns the bounding box for this reference . Returns out : Numpy array [ 2,2 ] or ` ` None ` ` Bounding box of this cell [ [ x _ min , y _ min ] , [ x _ max , y _ max ] ] , or ` ` None ` ` if the cell is empty ."""
if not isinstance ( self . ref_cell , Cell ) : return None if ( self . rotation is None and self . magnification is None and self . x_reflection is None ) : key = self else : key = ( self . ref_cell , self . rotation , self . magnification , self . x_reflection ) deps = self . ref_cell . get_dependencies ( ...
def get_file_mode_for_reading ( context ) : """Get file mode for reading from tar [ ' format ' ] . This should return r : * , r : gz , r : bz2 or r : xz . If user specified something wacky in tar . Format , that ' s their business . In theory r : * will auto - deduce the correct format ."""
format = context [ 'tar' ] . get ( 'format' , None ) if format or format == '' : mode = f"r:{context.get_formatted_string(format)}" else : mode = 'r:*' return mode
def getUnionLocations ( encoder , x , y , r , step = 1 ) : """Return a union of location encodings that correspond to the union of all locations within the specified circle ."""
output = np . zeros ( encoder . getWidth ( ) , dtype = defaultDtype ) locations = set ( ) for dx in range ( - r , r + 1 , step ) : for dy in range ( - r , r + 1 , step ) : if dx * dx + dy * dy <= r * r : e = encodeLocation ( encoder , x + dx , y + dy , output ) locations = locations ...
def calc_std ( c0 , c1 = [ ] ) : """Calculates the variance of the data ."""
if c1 == [ ] : return numpy . std ( c0 , 0 ) prop = float ( len ( c0 ) ) / float ( len ( c1 ) ) if prop < 1 : p0 = int ( math . ceil ( 1 / prop ) ) p1 = 1 else : p0 = 1 p1 = int ( math . ceil ( prop ) ) return numpy . std ( numpy . vstack ( p0 * [ c0 ] + p1 * [ c1 ] ) , 0 )
def parse_fields_whois ( self , response ) : """The function for parsing ASN fields from a whois response . Args : response ( : obj : ` str ` ) : The response from the ASN whois server . Returns : dict : The ASN lookup results ' asn ' ( str ) - The Autonomous System Number ' asn _ date ' ( str ) - The A...
try : temp = response . split ( '|' ) # Parse out the ASN information . ret = { 'asn_registry' : temp [ 4 ] . strip ( ' \n' ) } if ret [ 'asn_registry' ] not in self . rir_whois . keys ( ) : raise ASNRegistryError ( 'ASN registry {0} is not known.' . format ( ret [ 'asn_registry' ] ) ) ret [...
def mv_videos ( path ) : """move videos in sub - directory of path to path ."""
count = 0 for f in os . listdir ( path ) : f = os . path . join ( path , f ) if os . path . isdir ( f ) : for sf in os . listdir ( f ) : sf = os . path . join ( f , sf ) if os . path . isfile ( sf ) : new_name = os . path . join ( path , os . path . basename ( sf ...
def chart_type ( self , value ) : """Set the MetricsGraphics chart type . Allowed charts are : line , histogram , point , and bar Args : value ( str ) : chart type . Raises : ValueError : Not a valid chart type ."""
if value not in self . _allowed_charts : raise ValueError ( "Not a valid chart type" ) self . options [ "chart_type" ] = value
def get ( self , name , default = None ) : """Get the value at ` ` name ` ` for this : class : ` Config ` container The returned value is obtained from : * the value at ` ` name ` ` in the : attr : ` settings ` dictionary if available . * the value at ` ` name ` ` in the : attr : ` params ` dictionary if av...
try : return self . _get ( name , default ) except KeyError : return default
def parse ( readDataInstance , numberOfEntries ) : """Returns a L { ImageBoundForwarderRef } array where every element is a L { ImageBoundForwarderRefEntry } object . @ type readDataInstance : L { ReadData } @ param readDataInstance : A L { ReadData } object with the corresponding data to generate a new L { Ima...
imageBoundForwarderRefsList = ImageBoundForwarderRef ( ) dLength = len ( readDataInstance ) entryLength = ImageBoundForwarderRefEntry ( ) . sizeof ( ) toRead = numberOfEntries * entryLength if dLength >= toRead : for i in range ( numberOfEntries ) : entryData = readDataInstance . read ( entryLength ) ...
def _to_python ( input_string ) : '''a helper method to convert camelcase to python'''
python_string = '' for i in range ( len ( input_string ) ) : if not python_string : python_string += input_string [ i ] . lower ( ) elif input_string [ i ] . isupper ( ) : python_string += '_%s' % input_string [ i ] . lower ( ) else : python_string += input_string [ i ] return python...
def venn3 ( subsets , set_labels = ( 'A' , 'B' , 'C' ) , set_colors = ( 'r' , 'g' , 'b' ) , alpha = 0.4 , normalize_to = 1.0 , ax = None , subset_label_formatter = None ) : '''Plots a 3 - set area - weighted Venn diagram . The subsets parameter can be one of the following : - A list ( or a tuple ) , containing ...
# Prepare parameters if isinstance ( subsets , dict ) : subsets = [ subsets . get ( t , 0 ) for t in [ '100' , '010' , '110' , '001' , '101' , '011' , '111' ] ] elif len ( subsets ) == 3 : subsets = compute_venn3_subsets ( * subsets ) if subset_label_formatter is None : subset_label_formatter = str areas = ...
def parse_ctuple ( s , length = 2 ) : '''parse a string of acceptable colors into matplotlib , that is , either strings , or three tuples of rgb . Don ' t quote strings .'''
if parse_utuple ( s , colrx_s , length = length ) is None : raise ValueError ( "{} is not a valid color tuple." . format ( s ) ) ; # quote strings s = quote_subs ( s , colorfix = True ) ; return evalt ( s ) ;
def copyNode ( node , children = False , parent = False ) : """Copy an XML Node : param node : Etree Node : param children : Copy children nodes is set to True : param parent : Append copied node to parent if given : return : New Element"""
if parent is not False : element = SubElement ( parent , node . tag , attrib = node . attrib , nsmap = { None : "http://www.tei-c.org/ns/1.0" } ) else : element = Element ( node . tag , attrib = node . attrib , nsmap = { None : "http://www.tei-c.org/ns/1.0" } ) if children : if node . text : element...
def get_calculated_aes ( aesthetics ) : """Return a list of the aesthetics that are calculated"""
calculated_aesthetics = [ ] for name , value in aesthetics . items ( ) : if is_calculated_aes ( value ) : calculated_aesthetics . append ( name ) return calculated_aesthetics
def bivrandom ( x0 , y0 , sx , sy , cxy , size = None ) : """Compute random values distributed according to the specified bivariate distribution . Inputs : * x0 : the center of the x distribution ( i . e . its intended mean ) * y0 : the center of the y distribution * sx : standard deviation ( not variance...
from numpy . random import multivariate_normal as mvn p0 = np . asarray ( [ x0 , y0 ] ) cov = np . asarray ( [ [ sx ** 2 , cxy ] , [ cxy , sy ** 2 ] ] ) return mvn ( p0 , cov , size )
def add_asset ( self , asset_id , asset_content_id = None , label = None , asset_content_type = None ) : """stub"""
if asset_id is None : raise NullArgument ( 'asset_id cannot be None' ) if not isinstance ( asset_id , Id ) : raise InvalidArgument ( 'asset_id must be an Id instance' ) if asset_content_id is not None and not isinstance ( asset_content_id , Id ) : raise InvalidArgument ( 'asset_content_id must be an Id inst...
def unregisterHandler ( self , fh ) : """Unregister a file descriptor . Clean data , if such operation has been scheduled . Parameters fh : int File descriptor ."""
try : self . fds . remove ( fh ) except KeyError : pass self . lock . acquire ( ) try : self . data . rollover ( ) # rollover data on close . finally : self . lock . release ( ) if self . closing and not self . fds : self . data . close ( )
def publishToRoom ( self , roomId , name , data , userList = None ) : """Publish to given room data submitted"""
if userList is None : userList = self . getRoom ( roomId ) # Publish data to all room users logging . debug ( "%s: broadcasting (name: %s, data: %s, number of users: %s)" % ( self . _gcls ( ) , name , data , len ( userList ) ) ) self . broadcast ( userList , { "name" : name , "data" : SockJSRoomHandler . _parser . ...
def get ( self , res_path , timeout = 10. ) : """Get operation . : param str res _ path : Resource path . : param float timeout : Timeout in seconds . : rtype : tuple : return : Tuple with status code and response body ."""
resp = requests . get ( self . __res_uri ( res_path ) , headers = self . __headers ( ) , verify = False , auth = self . __auth ( ) , timeout = timeout ) return ( resp . status_code , json . loads ( resp . text ) if resp . status_code == 200 else { } )
def info ( ctx ) : """Display status of OpenPGP application ."""
controller = ctx . obj [ 'controller' ] click . echo ( 'OpenPGP version: %d.%d.%d' % controller . version ) retries = controller . get_remaining_pin_tries ( ) click . echo ( 'PIN tries remaining: {}' . format ( retries . pin ) ) click . echo ( 'Reset code tries remaining: {}' . format ( retries . reset ) ) click . echo...
def get_url ( self , path ) : """Construct a full url to the v3alpha API given a specific path : param path : : return : url"""
host = ( '[' + self . host + ']' if ( self . host . find ( ':' ) != - 1 ) else self . host ) base_url = self . protocol + '://' + host + ':' + str ( self . port ) return base_url + '/v3alpha/' + path . lstrip ( "/" )
def set_corrected_pval ( self , nt_method , pvalue ) : """Add object attribute based on method name ."""
self . method_flds . append ( nt_method ) fieldname = "" . join ( [ "p_" , nt_method . fieldname ] ) setattr ( self , fieldname , pvalue )
def _Rforce ( self , R , phi = 0. , t = 0. ) : """NAME : _ Rforce PURPOSE : evaluate the radial force for this potential INPUT : R - Galactocentric cylindrical radius phi - azimuth t - time OUTPUT : the radial force HISTORY : 2010-11-24 - Written - Bovy ( NYU )"""
return self . _A * math . exp ( - ( t - self . _to ) ** 2. / 2. / self . _sigma2 ) / R * math . sin ( self . _alpha * math . log ( R ) - self . _m * ( phi - self . _omegas * t - self . _gamma ) )
def get_organization_id ( server_config , label ) : """Return the ID of the organization with label ` ` label ` ` . : param server _ config : A dict of information about the server being talked to . The dict should include the keys " url " , " auth " and " verify " . : param label : A string label that will b...
response = requests . get ( server_config [ 'url' ] + '/katello/api/v2/organizations' , data = json . dumps ( { 'search' : 'label={}' . format ( label ) } ) , auth = server_config [ 'auth' ] , headers = { 'content-type' : 'application/json' } , verify = server_config [ 'verify' ] , ) response . raise_for_status ( ) dec...
def register_index ( self , index ) : """Registers a given index : * Creates and opens an index for it ( if it doesn ' t exist yet ) * Sets some default values on it ( unless they ' re already set ) Args : index ( PonyWhoosh . Index ) : An instance of PonyWhoosh . Index class"""
self . _indexes [ index . _name ] = index self . create_index ( index ) return index
def get_indented_block ( prefix_lines ) : """Returns an integer . The return value is the number of lines that belong to block begun on the first line . Parameters prefix _ lines : list of basestring pairs Each pair corresponds to a line of SHPAML source code . The first element of each pair is indentat...
prefix , line = prefix_lines [ 0 ] len_prefix = len ( prefix ) # Find the first nonempty line with len ( prefix ) < = len ( prefix ) i = 1 while i < len ( prefix_lines ) : new_prefix , line = prefix_lines [ i ] if line and len ( new_prefix ) <= len_prefix : break i += 1 # Rewind to exclude empty lin...
def get_all_bandwidth_groups ( self ) : """Get all managed bandwidth groups . return bandwidth _ groups of type : class : ` IBandwidthGroup ` The array of managed bandwidth groups ."""
bandwidth_groups = self . _call ( "getAllBandwidthGroups" ) bandwidth_groups = [ IBandwidthGroup ( a ) for a in bandwidth_groups ] return bandwidth_groups
def _update_object_map ( self , obj_map ) : """stub"""
creation_time = obj_map [ 'creationTime' ] obj_map [ 'creationTime' ] = dict ( ) obj_map [ 'creationTime' ] [ 'year' ] = creation_time . year obj_map [ 'creationTime' ] [ 'month' ] = creation_time . month obj_map [ 'creationTime' ] [ 'day' ] = creation_time . day obj_map [ 'creationTime' ] [ 'hour' ] = creation_time . ...
def set_ttl ( self , key , ttl ) : """Sets time to live for @ key to @ ttl seconds - > # bool True if the timeout was set"""
return self . _client . expire ( self . get_key ( key ) , ttl )
def get_easter_saturday ( self , year ) : "Return the Easter Saturday date"
sunday = self . get_easter_sunday ( year ) return sunday - timedelta ( days = 1 )
def get_command_line_key_for_unknown_config_file_setting ( self , key ) : """Compute a commandline arg key to be used for a config file setting that doesn ' t correspond to any defined configargparse arg ( and so doesn ' t have a user - specified commandline arg key ) . Args : key : The config file key that...
key_without_prefix_chars = key . strip ( self . prefix_chars ) command_line_key = self . prefix_chars [ 0 ] * 2 + key_without_prefix_chars return command_line_key
def data_find_all ( data , path , dyn_cls = False ) : """Find and return all element - as - tuples in tuple ` ` data ` ` using simplified XPath ` ` path ` ` ."""
path_parts = path . split ( "/" ) try : sub_elms = tuple ( el for el in data if isinstance ( el , ( tuple , list ) ) and el [ 0 ] == path_parts [ 0 ] ) except IndexError : return None if len ( path_parts ) > 1 : ret = [ ] for sub_elm in sub_elms : for x in data_find_all ( sub_elm , "/" . join ( ...
def non_rotational_device ( self , name , controller_port , device , non_rotational ) : """Sets a flag in the device information which indicates that the medium is not based on rotational technology , i . e . that the access times are more or less independent of the position on the medium . This may or may no...
if not isinstance ( name , basestring ) : raise TypeError ( "name can only be an instance of type basestring" ) if not isinstance ( controller_port , baseinteger ) : raise TypeError ( "controller_port can only be an instance of type baseinteger" ) if not isinstance ( device , baseinteger ) : raise TypeError...
def ImportDNS ( self , config , token = None ) : """Import a dns configuration file into the helper Note : This requires that you have the latest token . To get the latest token , run the GrabDNS command first ."""
if not token : raise Exception ( "You must have the dns token set first." ) self . dns = CotendoDNS ( [ token , config ] ) return True
def pretokenized_t2t_dataset ( dataset_name = gin . REQUIRED , text2self = False , data_dir = gin . REQUIRED , dataset_split = "train" , batch_size = gin . REQUIRED , sequence_length = gin . REQUIRED , vocabulary = None ) : """Loads the Tensor2tensor dataset specified by dataset _ name . Args : dataset _ name :...
del vocabulary filepattern = os . path . join ( data_dir , dataset_name + "-" + dataset_split + "-*" ) filenames = tf . gfile . Glob ( filepattern ) tf . logging . info ( "Found %s files matching %s" % ( len ( filenames ) , filepattern ) ) if not filenames : raise ValueError ( "No matching files found" ) dataset = ...
def get_rolls ( self , root_symbol , start , end , offset ) : """Get the rolls , i . e . the session at which to hop from contract to contract in the chain . Parameters root _ symbol : str The root symbol for which to calculate rolls . start : Timestamp Start of the date range . end : Timestamp End ...
oc = self . asset_finder . get_ordered_contracts ( root_symbol ) front = self . _get_active_contract_at_offset ( root_symbol , end , 0 ) back = oc . contract_at_offset ( front , 1 , end . value ) if back is not None : end_session = self . trading_calendar . minute_to_session_label ( end ) first = self . _active...
def rectify ( self , frames ) : """Rectify frames passed as ( left , right ) pair of OpenCV Mats . Remapping is done with nearest neighbor for speed ."""
new_frames = [ ] for i , side in enumerate ( ( "left" , "right" ) ) : new_frames . append ( cv2 . remap ( frames [ i ] , self . undistortion_map [ side ] , self . rectification_map [ side ] , cv2 . INTER_NEAREST ) ) return new_frames
def users_identity ( self , ** kwargs ) -> SlackResponse : """Get a user ' s identity ."""
self . _validate_xoxp_token ( ) return self . api_call ( "users.identity" , http_verb = "GET" , params = kwargs )
def filter ( self , drop_duplicates = False , drop_improper_mate_pairs = False , min_mapping_quality = None , min_base_quality = None , filters = None ) : '''Return a new PileupCollection that includes only pileup elements satisfying the specified criteria . Parameters drop _ duplicates ( optional , default F...
if filters is None : filters = [ ] if drop_duplicates : filters . append ( lambda e : not e . alignment . is_duplicate ) if drop_improper_mate_pairs : filters . append ( lambda e : e . alignment . is_proper_pair ) if min_mapping_quality is not None : filters . append ( lambda e : e . alignment . mapping...
def compose ( f2nimages , outfile ) : """Takes f2nimages and writes them into one single png file , side by side . f2nimages is a list of horizontal lines , where each line is a list of f2nimages . For instance : [ image1 , image2 ] , [ image3 , image4] The sizes of these images have to " match " , so tha...
# We start by doing some checks , and try to print out helpfull error messages . verbosity = [ ] colourmodes = [ ] for i , line in enumerate ( f2nimages ) : for j , img in enumerate ( line ) : if img . verbose : print "Checking line %i, image %i (verbose)..." % ( i + 1 , j + 1 ) img . ch...
def _format_value ( self , operation , key , indent ) : """A value that exists in the operation but has value None is displayed . A value that does not exist in the operation is left out entirely . The value name in the operation must match the value name in the template , but the location does not have to ma...
v = self . _find_value ( operation , key ) if v == "NOT_FOUND" : return [ ] if not isinstance ( v , list ) : v = [ v ] if not len ( v ) : v = [ None ] key = key + ":" lines = [ ] for s in v : # Access control rules are stored in tuples . if isinstance ( s , tuple ) : s = "{}: {}" . format ( * s ...
def unflag_message ( current ) : """remove flag of a message . . code - block : : python # request : ' view ' : ' _ zops _ flag _ message ' , ' key ' : key , # response : ' status ' : ' OK ' , ' code ' : 200,"""
current . output = { 'status' : 'OK' , 'code' : 200 } FlaggedMessage ( current ) . objects . filter ( user_id = current . user_id , message_id = current . input [ 'key' ] ) . delete ( )
def error_msg_callback ( self , callback ) : """Set the error message callback ."""
if callable ( callback ) : self . _error_msg_callback = callback else : self . _error_msg_callback = None
def devices ( self ) : """Return state of start action task ."""
return [ StartActionItem ( self . start_action , i , self . state , self . path , self . raw ) for i in range ( len ( self . raw [ ROOT_START_ACTION ] ) ) ]
def sentence2freqt ( docgraph , root , successors = None , include_pos = False , escape_func = FREQT_ESCAPE_FUNC ) : """convert a sentence subgraph into a FREQT string ."""
if successors is None : successors = sorted_bfs_successors ( docgraph , root ) if root in successors : # root node has children / subgraphs embed_str = u"" . join ( sentence2freqt ( docgraph , child , successors , include_pos = include_pos , escape_func = escape_func ) for child in successors [ root ] ) ret...
def checkAndRaise ( pageNum , itemsPerPage ) : """Check and Raise an Exception if needed Args : pageNum ( int ) : Page number itemsPerPage ( int ) : Number of items per Page Raises : ErrPaginationLimits : If we are out of limits"""
if pageNum < 1 : raise ErrPaginationLimits ( ErrPaginationLimits . ERR_PAGE_NUM ) if itemsPerPage < Settings . itemsPerPageMin or itemsPerPage > Settings . itemsPerPageMax : raise ErrPaginationLimits ( ErrPaginationLimits . ERR_ITEMS_PER_PAGE )
def mad ( a , axis = None , c = 1.4826 , return_med = False ) : """Compute normalized median absolute difference Can also return median array , as this can be expensive , and often we want both med and nmad Note : 1.4826 = 1/0.6745"""
a = checkma ( a ) # return np . ma . median ( np . fabs ( a - np . ma . median ( a ) ) ) / c if a . count ( ) > 0 : if axis is None : med = fast_median ( a ) out = fast_median ( np . fabs ( a - med ) ) * c else : med = np . ma . median ( a , axis = axis ) # This is necessary for ...
def delete ( self , record ) : """Removes a record from an query . Does not destroy the passed + record + , but marks any joining records for destruction ( in the case of a many - to - many relationship ) or sets the foreign key of + record + to None ( in the case of a one - to - many relationship ) . Only in...
# note : does ( and should ) not delete or destroy the record if self . record : self . _validate_record ( record ) if self . join_args : # Need to find out who has the foreign key # If record has it , set to None , then done . # If one level up has it , mark the record for destruction final_tab...
def checkversion ( doc , # type : Union [ CommentedSeq , CommentedMap ] metadata , # type : CommentedMap enable_dev # type : bool ) : # type : ( . . . ) - > Tuple [ Union [ CommentedSeq , CommentedMap ] , Text ] """Checks the validity of the version of the give CWL document . Returns the document and the validate...
cdoc = None # type : Optional [ CommentedMap ] if isinstance ( doc , CommentedSeq ) : if not isinstance ( metadata , CommentedMap ) : raise Exception ( "Expected metadata to be CommentedMap" ) lc = metadata . lc metadata = copy . deepcopy ( metadata ) metadata . lc . data = copy . copy ( lc . da...
def _update_plot ( self , key , element , bars , lims , ranges ) : """Process the bars and draw the offset line as necessary . If a color map is set in the style of the ' main ' ViewableElement object , color the bars appropriately , respecting the required normalization settings ."""
main = self . adjoined . main _ , y1 = element . range ( 1 ) offset = self . offset * y1 range_item , main_range , dim = get_sideplot_ranges ( self , element , main , ranges ) # Check if plot is colormapped plot_type = Store . registry [ 'matplotlib' ] . get ( type ( range_item ) ) if isinstance ( plot_type , PlotSelec...
def write_memory ( addr , buf , progress = None , progress_addr = 0 , progress_size = 0 ) : """Writes a buffer into memory . This routine assumes that memory has already been erased ."""
xfer_count = 0 xfer_bytes = 0 xfer_total = len ( buf ) xfer_base = addr while xfer_bytes < xfer_total : if __verbose and xfer_count % 512 == 0 : print ( "Addr 0x%x %dKBs/%dKBs..." % ( xfer_base + xfer_bytes , xfer_bytes // 1024 , xfer_total // 1024 ) ) if progress and xfer_count % 2 == 0 : progr...
def list ( self , resource , url_prefix , auth , session , send_opts ) : """List metadata keys associated with the given resource . Args : resource ( intern . resource . boss . BossResource ) : List keys associated with this resource . url _ prefix ( string ) : Protocol + host such as https : / / api . thebos...
req = self . get_metadata_request ( resource , 'GET' , 'application/json' , url_prefix , auth ) prep = session . prepare_request ( req ) resp = session . send ( prep , ** send_opts ) if resp . status_code == 200 : keys_dict = resp . json ( ) return keys_dict [ 'keys' ] err = ( 'List failed on {}, got HTTP respo...
def remove_exception_type ( self , exc ) : """Removes an exception type from being handled during the reconnect logic . Parameters exc : Type [ : class : ` BaseException ` ] The exception class to handle . Returns : class : ` bool ` Whether it was successfully removed ."""
old_length = len ( self . _valid_exception ) self . _valid_exception = tuple ( x for x in self . _valid_exception if x is not exc ) return len ( self . _valid_exception ) != old_length
def get_comment_collection ( cmt_id ) : """Extract the collection where the comment is written"""
query = """SELECT id_bibrec FROM "cmtRECORDCOMMENT" WHERE id=%s""" recid = run_sql ( query , ( cmt_id , ) ) record_primary_collection = guess_primary_collection_of_a_record ( recid [ 0 ] [ 0 ] ) return record_primary_collection
def is_inbound_presence_filter ( cb ) : """Return true if ` cb ` has been decorated with : func : ` inbound _ presence _ filter ` ."""
try : handlers = get_magic_attr ( cb ) except AttributeError : return False hs = HandlerSpec ( ( _apply_inbound_presence_filter , ( ) ) ) return hs in handlers
def _predicted ( self ) : """The predicted values of y ( ' yhat ' ) ."""
return np . squeeze ( np . matmul ( self . xwins , np . expand_dims ( self . solution , axis = - 1 ) ) )
def me ( self ) : """获取使用特定 cookies 的 Me 实例 : return : cookies对应的Me对象 : rtype : Me"""
from . me import Me headers = dict ( Default_Header ) headers [ 'Host' ] = 'zhuanlan.zhihu.com' res = self . _session . get ( Get_Me_Info_Url , headers = headers ) json_data = res . json ( ) url = json_data [ 'profileUrl' ] name = json_data [ 'name' ] motto = json_data [ 'bio' ] photo = json_data [ 'avatar' ] [ 'templa...
def calculo ( self ) : """Calculate procedure"""
T = self . kwargs [ "T" ] rho = self . kwargs [ "rho" ] P = self . kwargs [ "P" ] # Composition alternate definition if self . _composition == "A" : A = self . kwargs [ "A" ] elif self . _composition == "xa" : xa = self . kwargs [ "xa" ] A = xa / ( 1 - ( 1 - xa ) * ( 1 - Mw / Ma ) ) # Thermodynamic definiti...
def svdd ( self , data : [ 'SASdata' , str ] = None , code : str = None , id : str = None , input : [ str , list , dict ] = None , kernel : str = None , savestate : str = None , solver : str = None , weight : str = None , procopts : str = None , stmtpassthrough : str = None , ** kwargs : dict ) -> 'SASresults' : ""...
def reboot ( self , comment = None ) : """Send reboot command to this node . : param str comment : comment to audit : raises NodeCommandFailed : reboot failed with reason : return : None"""
self . make_request ( NodeCommandFailed , method = 'update' , resource = 'reboot' , params = { 'comment' : comment } )
def get_abundance_iso_decay ( self , cycle ) : """returns the decayed stable isotopes . Parameters cycle : integer The cycle ."""
import nuutils as u masses_for_this_cycle = self . se . get ( cycle , 'mass' ) self . _read_iso_abund_marco ( [ min ( masses_for_this_cycle ) , max ( masses_for_this_cycle ) ] , cycle ) u . stable_specie ( ) self . decay ( self . mass_frac ) self . index_for_all_species = u . cl self . index_for_stable_species = u . ba...
def encipher ( self , string ) : """Encipher string using Playfair cipher according to initialised key . Punctuation and whitespace are removed from the input . If the input plaintext is not an even number of characters , an ' X ' will be appended . Example : : ciphertext = Playfair ( key = ' zgptfoihmuwdrcny...
string = self . remove_punctuation ( string ) string = re . sub ( r'[J]' , 'I' , string ) if len ( string ) % 2 == 1 : string += 'X' ret = '' for c in range ( 0 , len ( string ) , 2 ) : ret += self . encipher_pair ( string [ c ] , string [ c + 1 ] ) return ret
def _command ( self , msg ) : """Send a command to the tv ."""
logger . debug ( 'send command to %s' , "ws://{}:{}" . format ( self . ip , self . port ) ) ; try : websocket = yield from websockets . connect ( "ws://{}:{}" . format ( self . ip , self . port ) , timeout = self . timeout_connect ) except : logger . debug ( 'command failed to connect to %s' , "ws://{}:{}" . fo...
def write_to_screen ( self , cli , screen , mouse_handlers , write_position ) : """Render the prompt to a ` Screen ` instance . : param screen : The : class : ` ~ prompt _ toolkit . layout . screen . Screen ` class to which the output has to be written ."""
sizes = self . _divide_heigths ( cli , write_position ) if self . report_dimensions_callback : self . report_dimensions_callback ( cli , sizes ) if sizes is None : self . window_too_small . write_to_screen ( cli , screen , mouse_handlers , write_position ) else : # Draw child panes . ypos = write_position ....
def process_ems ( self , doc : Document ) -> List [ Document ] : """Factory method to wrap input JSON docs in an ETK Document object . Args : doc ( Document ) : process on this document Returns : a Document object and a KnowledgeGraph object"""
new_docs = list ( ) for a_em in self . em_lst : if a_em . document_selector ( doc ) : self . log ( " processing with " + str ( type ( a_em ) ) + ". Process" , "info" , doc . doc_id , doc . url ) fresh_docs = a_em . process_document ( doc ) # Allow ETKModules to return nothing in lieu of an e...
def append ( self , tr ) : """Add a new transform to the end of this chain . Parameters tr : instance of Transform The transform to use ."""
self . transforms . append ( tr ) tr . changed . connect ( self . _subtr_changed ) self . _rebuild_shaders ( ) self . update ( )
def update ( self , ** kwargs ) : """Add , remove or modify a share ' s title . Input : * ` ` title ` ` The share title , if any ( optional ) * * NOTE * * : Passing ` ` None ` ` or calling this method with an empty argument list will remove the share ' s title . Output : * None Example : : share = cli...
if 'title' in kwargs : params = { "title" : kwargs [ 'title' ] } else : params = { "title" : None } response = GettRequest ( ) . post ( "/shares/%s/update?accesstoken=%s" % ( self . sharename , self . user . access_token ( ) ) , params ) if response . http_status == 200 : self . __init__ ( self . user , ** ...
def pass_service ( * names ) : """Injects a service instance into the kwargs"""
def decorator ( f ) : @ functools . wraps ( f ) def wrapper ( * args , ** kwargs ) : for name in names : kwargs [ name ] = service_proxy ( name ) return f ( * args , ** kwargs ) return wrapper return decorator
def verify_list_items ( my_list , item ) : """This function checks if all elements in a list are identical to a supplied item . Args : my _ list : A list of items to be verified item : The item to be checked against every element in the list Returns : True if all elements in the list equal to the item , f...
item_check = all ( v == item for v in my_list ) return item_check
def remove_citation_metadata ( graph ) : """Remove the metadata associated with a citation . Best practice is to add this information programmatically ."""
for u , v , k in graph . edges ( keys = True ) : if CITATION not in graph [ u ] [ v ] [ k ] : continue for key in list ( graph [ u ] [ v ] [ k ] [ CITATION ] ) : if key not in _CITATION_KEEP_KEYS : del graph [ u ] [ v ] [ k ] [ CITATION ] [ key ]
def persistant_error ( request , message , extra_tags = '' , fail_silently = False , * args , ** kwargs ) : """Adds a persistant message with the ` ` ERROR ` ` level ."""
add_message ( request , ERROR_PERSISTENT , message , extra_tags = extra_tags , fail_silently = fail_silently , * args , ** kwargs )
def from_payload ( self , payload ) : """Init frame from binary data ."""
self . node_id = payload [ 0 ] self . order = payload [ 1 ] * 256 + payload [ 2 ] self . placement = payload [ 3 ] self . name = bytes_to_string ( payload [ 4 : 68 ] ) self . velocity = Velocity ( payload [ 68 ] ) self . node_type = NodeTypeWithSubtype ( payload [ 69 ] * 256 + payload [ 70 ] ) self . product_group = pa...
def lrange ( self , key , start , end ) : """Returns the specified elements of the list stored at key . : param key : The list ' s key : type key : : class : ` str ` , : class : ` bytes ` : param int start : zero - based index to start retrieving elements from : param int end : zero - based index at which t...
return self . _execute ( [ b'LRANGE' , key , start , end ] )
def length_limits ( max_length_limit , length_limit_step ) : """Generates the length limits"""
string_len = len ( str ( max_length_limit ) ) return [ str ( i ) . zfill ( string_len ) for i in xrange ( length_limit_step , max_length_limit + length_limit_step - 1 , length_limit_step ) ]
def state ( self , state ) : """Set the current build state and record the time to maintain history . Note ! This is different from the dataset state . Setting the build set is commiteed to the progress table / database immediately . The dstate is also set , but is not committed until the bundle is committed ...
assert state != 'build_bundle' self . buildstate . state . current = state self . buildstate . state [ state ] = time ( ) self . buildstate . state . lasttime = time ( ) self . buildstate . state . error = False self . buildstate . state . exception = None self . buildstate . state . exception_type = None self . builds...
def end_session ( self , end_tcsession = True , sid = None ) : """End this test session . A session can be ended in three ways , depending on the value of the end _ tcsession parameter : - end _ tcsession = None : Stop using session locally , do not contact server . - end _ tcsession = False : End clien...
if not sid or sid == self . _sid : if not self . started ( ) : return False sid = self . _sid self . _sid = None self . _rest . del_header ( 'X-STC-API-Session' ) if end_tcsession is None : if self . _dbg_print : print ( '===> detached from session' ) return True try : if end...
def user ( self , extra_params = None ) : """The User currently assigned to the Ticket"""
if self . get ( 'assigned_to_id' , None ) : users = self . space . users ( id = self [ 'assigned_to_id' ] , extra_params = extra_params ) if users : return users [ 0 ]
def create_analysisrequest ( client , request , values , analyses = None , partitions = None , specifications = None , prices = None ) : """This is meant for general use and should do everything necessary to create and initialise an AR and any other required auxilliary objects ( Sample , SamplePartition , Analy...
# Don ' t pollute the dict param passed in values = dict ( values . items ( ) ) # Create the Analysis Request ar = _createObjectByType ( 'AnalysisRequest' , client , tmpID ( ) ) ar . processForm ( REQUEST = request , values = values ) # Resolve the services uids and set the analyses for this Analysis Request service_ui...
def get_cost_per_kg ( self , comp ) : """Get best estimate of minimum cost / kg based on known data Args : comp : Composition as a pymatgen . core . structure . Composition Returns : float of cost / kg"""
comp = comp if isinstance ( comp , Composition ) else Composition ( comp ) return self . get_cost_per_mol ( comp ) / ( comp . weight . to ( "kg" ) * const . N_A )
def get_url ( self ) : """Assuming that the repo has been cloned locally , get its default upstream URL ."""
cmd = { 'hg' : 'hg paths default' , 'git' : 'git config --local --get remote.origin.url' , } [ self . vcs_type ] with chdir ( self . folder ) : r = self . run ( cmd ) return r . output . replace ( '\n' , '' )
def _draw_background ( self , divisions = 10 ) : """Draws the background of the dial : param divisions : the number of divisions between ' ticks ' shown on the dial : return : None"""
self . canvas . create_arc ( 2 , 2 , self . size - 2 , self . size - 2 , style = tk . PIESLICE , start = - 60 , extent = 30 , fill = 'red' ) self . canvas . create_arc ( 2 , 2 , self . size - 2 , self . size - 2 , style = tk . PIESLICE , start = - 30 , extent = 60 , fill = 'yellow' ) self . canvas . create_arc ( 2 , 2 ...
def send ( email , subject = None , from_email = None , to_email = None , cc = None , bcc = None , reply_to = None , smtp = None ) : """Send markdown email Args : email ( str / obj ) : A markdown string or EmailContent object subject ( str ) : subject line from _ email ( str ) : sender email address to _ ...
if is_string ( email ) : email = EmailContent ( email ) from_email = sanitize_email_address ( from_email or email . headers . get ( 'from' ) ) to_email = sanitize_email_address ( to_email or email . headers . get ( 'to' ) ) cc = sanitize_email_address ( cc or email . headers . get ( 'cc' ) ) bcc = sanitize_email_ad...
def __SetBaseHeaders ( self , http_request , client ) : """Fill in the basic headers on http _ request ."""
# TODO ( craigcitro ) : Make the default a little better here , and # include the apitools version . user_agent = client . user_agent or 'apitools-client/1.0' http_request . headers [ 'user-agent' ] = user_agent http_request . headers [ 'accept' ] = 'application/json' http_request . headers [ 'accept-encoding' ] = 'gzi...
def is_present ( conf , atom ) : '''Tell if a given package or DEPEND atom is present in the configuration files tree . Warning : This only works if the configuration files tree is in the correct format ( the one enforced by enforce _ nice _ config ) CLI Example : . . code - block : : bash salt ' * ' po...
if conf in SUPPORTED_CONFS : if not isinstance ( atom , portage . dep . Atom ) : atom = portage . dep . Atom ( atom , allow_wildcard = True ) has_wildcard = '*' in atom package_file = _get_config_file ( conf , six . text_type ( atom ) ) # wildcards are valid in confs if has_wildcard : ...
def between ( self , start , end ) : """Adds new ` BETWEEN ` condition : param start : int or datetime compatible object ( in SNOW user ' s timezone ) : param end : int or datetime compatible object ( in SNOW user ' s timezone ) : raise : - QueryTypeError : if start or end arguments is of an invalid type"""
if hasattr ( start , 'strftime' ) and hasattr ( end , 'strftime' ) : dt_between = ( 'javascript:gs.dateGenerate("%(start)s")' "@" 'javascript:gs.dateGenerate("%(end)s")' ) % { 'start' : start . strftime ( '%Y-%m-%d %H:%M:%S' ) , 'end' : end . strftime ( '%Y-%m-%d %H:%M:%S' ) } elif isinstance ( start , int ) and is...
def main ( ) : """Entry point to dcgan"""
print ( "|------- new changes!!!!!!!!!" ) # to get the dataset and net configuration train_data , val_data = get_dataset ( dataset ) netG = get_netG ( ) netD = get_netD ( ) loss , trainerG , trainerD = get_configurations ( netG , netD ) # set labels real_label = mx . nd . ones ( ( opt . batch_size , ) , ctx = ctx ) fak...
def merge ( args ) : """% prog merge merged _ bams bams1 _ dir bams2 _ dir . . . Merge BAM files . Treat the bams with the same prefix as a set . Output the commands first ."""
from jcvi . apps . grid import MakeManager p = OptionParser ( merge . __doc__ ) p . set_sep ( sep = "_" , help = "Separator to group per prefix" ) opts , args = p . parse_args ( args ) if len ( args ) < 2 : sys . exit ( not p . print_help ( ) ) merged_bams = args [ 0 ] bamdirs = args [ 1 : ] mkdir ( merged_bams ) b...
def weeks_per_year ( year ) : '''Number of ISO weeks in a year'''
# 53 weeks : any year starting on Thursday and any leap year starting on Wednesday jan1 = jwday ( gregorian . to_jd ( year , 1 , 1 ) ) if jan1 == THU or ( jan1 == WED and isleap ( year ) ) : return 53 else : return 52
def SeriesXmlRewriterFactory ( chart_type , chart_data ) : """Return a | _ BaseSeriesXmlRewriter | subclass appropriate to * chart _ type * ."""
XL_CT = XL_CHART_TYPE RewriterCls = { # There are 73 distinct chart types , only specify non - category # types , others default to _ CategorySeriesXmlRewriter . Stock - type # charts are multi - plot charts , so no guaratees on how they turn # out . XL_CT . BUBBLE : _BubbleSeriesXmlRewriter , XL_CT . BUBBLE_THREE_D_EF...
def select ( self , fixed ) : """Return a subset of variables according to ` ` fixed ` ` ."""
names = [ n for n in self . names ( ) if self [ n ] . isfixed == fixed ] return Variables ( { n : self [ n ] for n in names } )
def transformer_aux_tiny ( ) : """Set of hyperparameters ."""
hparams = transformer . transformer_tiny ( ) hparams . shared_embedding_and_softmax_weights = False hparams . add_hparam ( "shift_values" , "1,2" ) return hparams
def to_jd ( year , month , day ) : '''Obtain Julian day for Indian Civil date'''
gyear = year + 78 leap = isleap ( gyear ) # / / Is this a leap year ? # 22 - leap = 21 if leap , 22 non - leap start = gregorian . to_jd ( gyear , 3 , 22 - leap ) if leap : Caitra = 31 else : Caitra = 30 if month == 1 : jd = start + ( day - 1 ) else : jd = start + Caitra m = month - 2 m = min ( ...
def transform ( input_fragment , parameter_values , managed_policy_loader ) : """Translates the SAM manifest provided in the and returns the translation to CloudFormation . : param dict input _ fragment : the SAM template to transform : param dict parameter _ values : Parameter values provided by the user : r...
sam_parser = Parser ( ) translator = Translator ( managed_policy_loader . load ( ) , sam_parser ) return translator . translate ( input_fragment , parameter_values = parameter_values )
def set_subplot_xlabel ( self , row , column , text ) : """Set a label for the x - axis of a subplot . : param row , column : specify the subplot . : param text : text of the label ."""
subplot = self . get_subplot_at ( row , column ) subplot . set_xlabel ( text )
def filepattern ( self , * args , ** kwargs ) : """Returns a list of filepatterns , one for each problem ."""
return [ p . filepattern ( * args , ** kwargs ) for p in self . problems ]
def train ( ) : """Training loop for awd language model ."""
ntasgd = False best_val = float ( 'Inf' ) start_train_time = time . time ( ) parameters = model . collect_params ( ) param_dict_avg = None t = 0 avg_trigger = 0 n = 5 valid_losses = [ ] for epoch in range ( args . epochs ) : total_L = 0.0 start_epoch_time = time . time ( ) start_log_interval_time = time . t...
def SparseSegmentSqrtN ( a , idxs , ids ) : """Sparse segmented sum / sqrt ( n = len ( idxs ) ) op ."""
func = lambda _idxs : np . divide ( reduce ( np . add , a [ idxs ] [ _idxs ] ) , np . math . sqrt ( len ( _idxs ) ) ) return seg_map ( func , a , ids ) ,