signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def info ( self , message ) : '''Logs an informational message to stdout . This method should only be used by the Runner .'''
return self . _log ( message = message . upper ( ) , stream = sys . stdout )
def sound_mode ( self ) : """Return the matched current sound mode as a string ."""
sound_mode_matched = self . _parent_avr . match_sound_mode ( self . _parent_avr . sound_mode_raw ) return sound_mode_matched
def _decode_transfer_block_data ( self , data ) : """Take a byte array and extract the data from it Decode the response returned by a DAP _ TransferBlock CMSIS - DAP command and return it as an array of bytes ."""
assert self . get_empty ( ) is False if data [ 0 ] != Command . DAP_TRANSFER_BLOCK : raise ValueError ( 'DAP_TRANSFER_BLOCK response error' ) if data [ 3 ] != DAP_TRANSFER_OK : if data [ 3 ] == DAP_TRANSFER_FAULT : raise DAPAccessIntf . TransferFaultError ( ) elif data [ 3 ] == DAP_TRANSFER_WAIT : ...
def fmt_sentence ( text ) : """English sentence formatter . First letter is always upper case . Example : " Do you want to build a snow man ? " * * 中文文档 * * 句子格式 。 每句话的第一个单词第一个字母大写 。"""
text = text . strip ( ) if len ( text ) == 0 : # if empty string , return it return text else : text = text . lower ( ) # lower all char # delete redundant empty space chunks = [ chunk for chunk in text . split ( " " ) if len ( chunk ) >= 1 ] chunks [ 0 ] = chunks [ 0 ] [ 0 ] . upper ( ) + chunk...
def from_signature ( message , signature ) : """Attempts to create PublicKey object by deriving it from the message and signature . Args : message ( bytes ) : The message to be verified . signature ( Signature ) : The signature for message . The recovery _ id must not be None ! Returns : PublicKey : ...
if signature . recovery_id is None : raise ValueError ( "The signature must have a recovery_id." ) msg = get_bytes ( message ) pub_keys = bitcoin_curve . recover_public_key ( msg , signature , signature . recovery_id ) for k , recid in pub_keys : if signature . recovery_id is not None and recid == signature . r...
def _collect_unused ( self , start : GridQubit , used : Set [ GridQubit ] ) -> Set [ GridQubit ] : """Lists all the qubits that are reachable from given qubit . Args : start : The first qubit for which connectivity should be calculated . Might be a member of used set . used : Already used qubits , which can...
def collect ( n : GridQubit , visited : Set [ GridQubit ] ) : visited . add ( n ) for m in self . _c_adj [ n ] : if m not in used and m not in visited : collect ( m , visited ) visited = set ( ) # type : Set [ GridQubit ] collect ( start , visited ) return visited
def format_kwargs ( attrs , params ) : """Modify attribute with argument values . Parameters attrs : dict Attributes to be assigned to function output . The values of the attributes in braces will be replaced the the corresponding args values . params : dict A BoundArguments . arguments dictionary stori...
attrs_mapping = { 'cell_methods' : { 'YS' : 'years' , 'MS' : 'months' } , 'long_name' : { 'YS' : 'Annual' , 'MS' : 'Monthly' } } for key , val in attrs . items ( ) : mba = { } # Add formatting { } around values to be able to replace them with _ attrs _ mapping using format . for k , v in params . items ( ) ...
def to_native_string ( string , encoding = 'ascii' ) : """Given a string object , regardless of type , returns a representation of that string in the native string type , encoding and decoding where necessary . This assumes ASCII unless told otherwise ."""
out = None if isinstance ( string , builtin_str ) : out = string else : if is_py2 : out = string . encode ( encoding ) else : out = string . decode ( encoding ) return out
def extract_tabular ( self , header = '' , prefix = '' , suffix = '' , table_type = '' , * args , ** kwargs ) : """Method for performing the tabular data extraction . : param result : A dictionary containing the extracted data so far : param table _ type : Can be " rows " or " columns " . This determines the ty...
if type ( header ) in [ str , unicode ] : try : header_list = self . get_tree_tag ( header ) table_headers = [ prefix + h . text + suffix for h in header_list ] except XPathError : raise Exception ( "Invalid %s selector for table header - %s" % ( self . __selector_type__ , header ) ) ...
def split_locale ( locale : Text ) -> Tuple [ Text , Optional [ Text ] ] : """Decompose the locale into a normalized tuple . The first item is the locale ( as lowercase letters ) while the second item is either the country as lower case either None if no country was supplied ."""
items = re . split ( r'[_\-]' , locale . lower ( ) , 1 ) try : return items [ 0 ] , items [ 1 ] except IndexError : return items [ 0 ] , None
def _detect ( self ) : """Detect high level calls which return a value that are never used"""
results = [ ] for c in self . slither . contracts : for f in c . functions + c . modifiers : if f . contract != c : continue unused_return = self . detect_unused_return_values ( f ) if unused_return : info = "{}.{} ({}) does not use the value returned by external call...
def _rdump_value_to_numpy ( s ) : """Convert a R dump formatted value to Numpy equivalent For example , " c ( 1 , 2 ) " becomes ` ` array ( [ 1 , 2 ] ) ` ` Only supports a few R data structures . Will not work with European decimal format ."""
if "structure" in s : vector_str , shape_str = re . findall ( r'c\([^\)]+\)' , s ) shape = [ int ( d ) for d in shape_str [ 2 : - 1 ] . split ( ',' ) ] if '.' in vector_str : arr = np . array ( [ float ( v ) for v in vector_str [ 2 : - 1 ] . split ( ',' ) ] ) else : arr = np . array ( [ ...
def main ( ) -> None : """" Execute the main routine ."""
parser = argparse . ArgumentParser ( description = __doc__ ) parser . add_argument ( "--outdir" , help = "output directory" , default = os . path . dirname ( __file__ ) ) args = parser . parse_args ( ) outdir = pathlib . Path ( args . outdir ) if not outdir . exists ( ) : raise FileNotFoundError ( "Output directory...
def record_add_types ( object_id , input_params = { } , always_retry = True , ** kwargs ) : """Invokes the / record - xxxx / addTypes API method . For more info , see : https : / / wiki . dnanexus . com / API - Specification - v1.0.0 / Types # API - method % 3A - % 2Fclass - xxxx % 2FaddTypes"""
return DXHTTPRequest ( '/%s/addTypes' % object_id , input_params , always_retry = always_retry , ** kwargs )
def get_resource ( self ) : """Return the associated resource ."""
references = { "resource_id" : None , "parent_id" : None , "grandparent_id" : None } for model_cls , regexp in self . _regexp . iteritems ( ) : match = regexp . search ( self . resource_ref ) if match is not None : references . update ( match . groupdict ( ) ) return model_cls . get ( ** referen...
def get_url ( self , obj ) : """The URL at which the detail page should appear ."""
if not hasattr ( obj , 'get_absolute_url' ) or not obj . get_absolute_url ( ) : raise ImproperlyConfigured ( "No URL configured. You must either \ set a ``get_absolute_url`` method on the %s model or override the %s view's \ ``get_url`` method" % ( obj . __class__ . __name__ , self . __class__ . __name__ ) ) return...
def update ( self , instance_id : str , details : UpdateDetails , async_allowed : bool ) -> UpdateServiceSpec : """Further readings ` CF Broker API # Update < https : / / docs . cloudfoundry . org / services / api . html # updating _ service _ instance > ` _ : param instance _ id : Instance id provided by the pla...
raise NotImplementedError ( )
def expire_token ( self , token ) : """Given a token , makes a request to the authentication server to expire it immediately . This is considered a responsible way to log out a user . If you simply remove the session your application has for the user without expiring their token , the user is not _ really _ l...
r = requests . post ( self . _login_uri ( "/oauth/token/expire" ) , data = { "client_id" : self . client_id , "client_secret" : self . client_secret , "token" : token , } ) if r . status_code != 200 : raise ApiError ( "Failed to expire token!" , r ) return True
def run ( self ) : """Start the game loop"""
global world self . __is_running = True while ( self . __is_running ) : # Our game loop # Catch our events self . __handle_events ( ) # Update our clock self . __clock . tick ( self . preferred_fps ) elapsed_milliseconds = self . __clock . get_time ( ) if 2 in self . event_flags : self . ela...
def update_trigger ( self , trigger ) : """Updates on the Alert API the trigger record having the ID of the specified Trigger object : the remote record is updated with data from the local Trigger object . : param trigger : the Trigger with updated data : type trigger : ` pyowm . alertapi30 . trigger . Trigge...
assert trigger is not None assert isinstance ( trigger . id , str ) , "Value must be a string" the_time_period = { "start" : { "expression" : "after" , "amount" : trigger . start_after_millis } , "end" : { "expression" : "after" , "amount" : trigger . end_after_millis } } the_conditions = [ dict ( name = c . weather_pa...
def calculate_all_micas ( self ) : """Calculate the MICA ( Most Informative Common Ancestor ) of every class - pair"""
G = self . G ics = self . _information_content_frame ( ) classes = list ( dfs . dfs_preorder_nodes ( G ) ) # mica _ df = pd . DataFrame ( index = classes , columns = classes ) # mica _ ic _ df = pd . DataFrame ( index = classes , columns = classes ) ncs = len ( classes ) ic_grid = np . empty ( [ ncs , ncs ] ) mica_arrs...
def hrmint ( xvals , yvals , x ) : """Evaluate a Hermite interpolating polynomial at a specified abscissa value . https : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / hrmint _ c . html : param xvals : Abscissa values . : type xvals : Array of floats : param yvals : Ordinate and...
work = stypes . emptyDoubleVector ( int ( 2 * len ( yvals ) + 1 ) ) n = ctypes . c_int ( len ( xvals ) ) xvals = stypes . toDoubleVector ( xvals ) yvals = stypes . toDoubleVector ( yvals ) x = ctypes . c_double ( x ) f = ctypes . c_double ( 0 ) df = ctypes . c_double ( 0 ) libspice . hrmint_c ( n , xvals , yvals , x , ...
def del_qos ( self , port_name ) : """Deletes the Qos rule on the given port ."""
command = ovs_vsctl . VSCtlCommand ( 'del-qos' , [ port_name ] ) self . run_command ( [ command ] )
def pci_contents ( self , use_dict = None , as_class = dict ) : """Return the contents of an object as a dict ."""
if _debug : PCI . _debug ( "pci_contents use_dict=%r as_class=%r" , use_dict , as_class ) # make / extend the dictionary of content if use_dict is None : use_dict = as_class ( ) # save the values for k , v in ( ( 'user_data' , self . pduUserData ) , ( 'source' , self . pduSource ) , ( 'destination' , self . pdu...
def _is_valid_file ( self , path ) : """Simple check to see if file path exists . Does not check for valid YAML format ."""
return isinstance ( path , basestring ) and os . path . isfile ( path )
def make_options_frame ( self ) : """make the frame that allows for configuration and classification"""
self . tab_frame = ttk . Notebook ( self . option_frame , width = 800 ) self . tab_configure = tk . Frame ( self . tab_frame ) self . tab_classify = tk . Frame ( self . tab_frame ) self . make_configure_tab ( ) self . make_classify_tab ( ) self . tab_frame . add ( self . tab_configure , text = "Configure" ) self . tab_...
def _get_filtered_variants ( self , vcf_file_path , filters = { } ) : """Check if variants follows the filters This function will try to make filters faster for the vcf adapter Args : vcf _ file _ path ( str ) : Path to vcf filters ( dict ) : A dictionary with filters Yields : varian _ line ( str ) : A ...
genes = set ( ) consequences = set ( ) sv_types = set ( ) if filters . get ( 'gene_ids' ) : genes = set ( [ gene_id . strip ( ) for gene_id in filters [ 'gene_ids' ] ] ) if filters . get ( 'consequence' ) : consequences = set ( filters [ 'consequence' ] ) if filters . get ( 'sv_types' ) : sv_types = set ( f...
def process_data ( context ) : """Generate summaries from raw weather station data . The meteorological day end ( typically 2100 or 0900 local time ) is set in the preferences file ` ` weather . ini ` ` . The default value is 2100 ( 2200 during DST ) , following the historical convention for weather station...
logger . info ( 'Generating summary data' ) # get time of last record last_raw = context . raw_data . before ( datetime . max ) if last_raw is None : raise IOError ( 'No data found. Check data directory parameter.' ) # get daytime end hour ( in local time ) day_end_hour , use_dst = get_day_end_hour ( context . para...
def default_props ( reset = False , ** kwargs ) : """Return current default properties Parameters reset : bool if True , reset properties and return default : False"""
global _DEFAULT_PROPS if _DEFAULT_PROPS is None or reset : reset_default_props ( ** kwargs ) return _DEFAULT_PROPS
def media_upload ( self , filename , * args , ** kwargs ) : """: reference : https : / / developer . twitter . com / en / docs / media / upload - media / api - reference / post - media - upload : allowed _ param :"""
f = kwargs . pop ( 'file' , None ) headers , post_data = API . _pack_image ( filename , 4883 , form_field = 'media' , f = f ) kwargs . update ( { 'headers' : headers , 'post_data' : post_data } ) return bind_api ( api = self , path = '/media/upload.json' , method = 'POST' , payload_type = 'media' , allowed_param = [ ] ...
def generate_supremacy_circuit_google_v2 ( qubits : Iterable [ devices . GridQubit ] , cz_depth : int , seed : int ) -> circuits . Circuit : """Generates Google Random Circuits v2 as in github . com / sboixo / GRCS cz _ v2. See also https : / / arxiv . org / abs / 1807.10749 Args : qubits : qubit grid in whic...
non_diagonal_gates = [ ops . pauli_gates . X ** ( 1 / 2 ) , ops . pauli_gates . Y ** ( 1 / 2 ) ] rand_gen = random . Random ( seed ) . random circuit = circuits . Circuit ( ) # Add an initial moment of Hadamards circuit . append ( ops . common_gates . H ( qubit ) for qubit in qubits ) layer_index = 0 if cz_depth : ...
def cgmlst_subspecies_call ( df_relatives ) : """Call Salmonella subspecies based on cgMLST results This method attempts to find the majority subspecies type within curated public genomes above a cgMLST allelic profile distance threshold . Note : ` ` CGMLST _ SUBSPECIATION _ DISTANCE _ THRESHOLD ` ` is the ...
closest_distance = df_relatives [ 'distance' ] . min ( ) if closest_distance > CGMLST_SUBSPECIATION_DISTANCE_THRESHOLD : logging . warning ( 'Min cgMLST distance (%s) above subspeciation distance threshold (%s)' , closest_distance , CGMLST_SUBSPECIATION_DISTANCE_THRESHOLD ) return None else : df_relatives =...
def __make_hash ( cls , innermsg , token , seqnum ) : """return the hash for this innermsg , token , seqnum return digest bytes"""
hobj = hmacNew ( token , digestmod = hashfunc ) hobj . update ( innermsg ) hobj . update ( cls . __byte_packer ( seqnum ) ) return hobj . digest ( )
def deep_update_dict ( origin_dict , override_dict ) : """update origin dict with override dict recursively e . g . origin _ dict = { ' a ' : 1 , ' b ' : { ' c ' : 2 , ' d ' : 4 } } override _ dict = { ' b ' : { ' c ' : 3 } } return : { ' a ' : 1 , ' b ' : { ' c ' : 3 , ' d ' : 4 } }"""
if not override_dict : return origin_dict for key , val in override_dict . items ( ) : if isinstance ( val , dict ) : tmp = deep_update_dict ( origin_dict . get ( key , { } ) , val ) origin_dict [ key ] = tmp elif val is None : # fix # 64 : when headers in test is None , it should inherit fr...
def maybe_rewrite_setup ( toolset , setup_script , setup_options , version , rewrite_setup = 'off' ) : """Helper rule to generate a faster alternative to MSVC setup scripts . We used to call MSVC setup scripts directly in every action , however in newer MSVC versions ( 10.0 + ) they make long - lasting registry...
result = '"{}" {}' . format ( setup_script , setup_options ) # At the moment we only know how to rewrite scripts with cmd shell . if os . name == 'nt' and rewrite_setup != 'off' : basename = os . path . basename ( setup_script ) filename , _ = os . path . splitext ( basename ) setup_script_id = 'b2_{}_{}_{}...
def main ( ) : """NAME aniso _ magic . py DESCRIPTION plots anisotropy data with either bootstrap or hext ellipses SYNTAX aniso _ magic . py [ - h ] [ command line options ] OPTIONS - h plots help message and quits - usr USER : set the user name - f AFILE , specify rmag _ anisotropy formatted file...
dir_path = "." version_num = pmag . get_version ( ) verbose = pmagplotlib . verbose args = sys . argv ipar , ihext , ivec , iboot , imeas , isite , iplot , vec = 0 , 0 , 0 , 1 , 1 , 0 , 1 , 0 hpars , bpars , PDir = [ ] , [ ] , [ ] CS , crd = '-1' , 's' nb = 1000 fmt = 'pdf' ResRecs = [ ] orlist = [ ] outfile , comp , D...
def getimage ( app ) : """Get image file ."""
# append source directory to TEMPLATE _ PATH so template is found srcdir = os . path . abspath ( os . path . dirname ( __file__ ) ) TEMPLATE_PATH . append ( srcdir ) staticbase = '_static' buildpath = os . path . join ( app . outdir , staticbase ) try : os . makedirs ( buildpath ) except OSError : if not os . p...
def set_max ( self ) : """Set the charger to max range for trips ."""
if not self . __maxrange_state : data = self . _controller . command ( self . _id , 'charge_max_range' , wake_if_asleep = True ) if data [ 'response' ] [ 'result' ] : self . __maxrange_state = True self . __manual_update_time = time . time ( )
def unit_type ( scale = None ) : """Returns a palette that maps unit types to rgb colors ."""
# Can specify a scale to match the api or to accept unknown unit types . palette_size = scale or max ( static_data . UNIT_TYPES ) + 1 palette = shuffled_hue ( palette_size ) assert len ( static_data . UNIT_TYPES ) <= len ( distinct_colors ) for i , v in enumerate ( static_data . UNIT_TYPES ) : palette [ v ] = disti...
def update_timestampable_model ( sender , instance , * args , ** kwargs ) : '''Using signals guarantees that timestamps are set no matter what : loading fixtures , bulk inserts , bulk updates , etc . Indeed , the ` save ( ) ` method is * not * called when using fixtures .'''
if not isinstance ( instance , TimestampableModel ) : return if not instance . pk : instance . created_at = now ( ) instance . updated_at = now ( )
def get_area_def ( self , dsid ) : """Get the area definition of the band ."""
if dsid . name != 'HRV' : return super ( HRITMSGFileHandler , self ) . get_area_def ( dsid ) cfac = np . int32 ( self . mda [ 'cfac' ] ) lfac = np . int32 ( self . mda [ 'lfac' ] ) loff = np . float32 ( self . mda [ 'loff' ] ) a = self . mda [ 'projection_parameters' ] [ 'a' ] b = self . mda [ 'projection_parameter...
def flavor_list ( profile = None , ** kwargs ) : '''Return a list of available flavors ( nova flavor - list ) CLI Example : . . code - block : : bash salt ' * ' nova . flavor _ list'''
filters = kwargs . get ( 'filter' , { } ) conn = _auth ( profile , ** kwargs ) return conn . flavor_list ( ** filters )
def _create_filenames ( filename_schema , feed_type ) : """Returns a dictionary of beam filename pairs , keyed on correlation , from the cartesian product of correlations and real , imaginary pairs Given ' beam _ $ ( corr ) _ $ ( reim ) . fits ' returns : ' xx ' : ( ' beam _ xx _ re . fits ' , ' beam _ xx _...
template = FitsFilenameTemplate ( filename_schema ) def _re_im_filenames ( corr , template ) : try : return tuple ( template . substitute ( corr = corr . lower ( ) , CORR = corr . upper ( ) , reim = ri . lower ( ) , REIM = ri . upper ( ) ) for ri in REIM ) except KeyError : raise ValueError ( "I...
def __word2art ( word , font , chr_ignore , letters ) : """Return art word . : param word : input word : type word : str : param font : input font : type font : str : param chr _ ignore : ignore not supported character : type chr _ ignore : bool : param letters : font letters table : type letters : ...
split_list = [ ] result_list = [ ] splitter = "\n" for i in word : if ( ord ( i ) == 9 ) or ( ord ( i ) == 32 and font == "block" ) : continue if ( i not in letters . keys ( ) ) : if ( chr_ignore ) : continue else : raise artError ( str ( i ) + " is invalid." ) ...
def add ( self , byte_sig : str , text_sig : str ) -> None : """Adds a new byte - text signature pair to the database . : param byte _ sig : 4 - byte signature string : param text _ sig : resolved text signature : return :"""
byte_sig = self . _normalize_byte_sig ( byte_sig ) with SQLiteDB ( self . path ) as cur : # ignore new row if it ' s already in the DB ( and would cause a unique constraint error ) cur . execute ( "INSERT OR IGNORE INTO signatures (byte_sig, text_sig) VALUES (?,?)" , ( byte_sig , text_sig ) , )
def from_payload ( self , payload ) : """Init frame from binary data ."""
self . major_version = payload [ 0 ] * 256 + payload [ 1 ] self . minor_version = payload [ 2 ] * 256 + payload [ 3 ]
def _register_signal_handler ( self , description , signal , handler ) : """Registers a handler for the given signal . : param description : a short description of the signal to handle . : param signal : the signal to handle . : param handler : the function to use for handling the signal ."""
from flask import signals if not signals . signals_available : self . app . logger . warn ( 'blinker needs to be installed in order to support %s' . format ( description ) ) self . app . logger . info ( 'Enabling {}' . format ( description ) ) # Weak references won ' t work if handlers are methods rather than funct...
def from_config ( cls , cp , section , variable_args ) : """Initialize this class from a config file . Bounds on ` ` f0 ` ` , ` ` tau ` ` , ` ` final _ mass ` ` and ` ` final _ spin ` ` should be specified by providing ` ` min - { param } ` ` and ` ` max - { param } ` ` . If the ` ` f0 ` ` or ` ` tau ` ` para...
tag = variable_args variable_args = set ( variable_args . split ( pycbc . VARARGS_DELIM ) ) # get f0 and tau f0 = bounded . get_param_bounds_from_config ( cp , section , tag , 'f0' ) tau = bounded . get_param_bounds_from_config ( cp , section , tag , 'tau' ) # see if f0 and tau should be renamed if cp . has_option_tag ...
def get_context_query_errors ( self ) : """A more straitfoward calculation of the context - specific errors relative to the query : returns : matrix of observed contexts and values : rtype : matrix of [ before ] [ after ] [ query ] { types } with types being any base or a deletion ."""
if self . _context_query_errors : return self . _context_query_errors if len ( self . _query_errors ) < 3 : return { } nts = [ 'A' , 'C' , 'G' , 'T' ] poss = [ 'A' , 'C' , 'G' , 'T' , '-' ] r = { } for i in nts : if i not in r : r [ i ] = { } for j in nts : if j not in r [ i ] : ...
def GetFormatSpecification ( cls ) : """Retrieves the format specification . Returns : FormatSpecification : format specification ."""
format_specification = specification . FormatSpecification ( cls . NAME ) format_specification . AddNewSignature ( b'ElfFile\x00' , offset = 0 ) return format_specification
def server ( self ) : """UDP server to listen for responses ."""
server = getattr ( self , "_server" , None ) if server is None : log . debug ( "Binding datagram server to %s" , self . bind ) server = DatagramServer ( self . bind , self . _response_received ) self . _server = server return server
def send_fax ( self , payload_outbox , ** kwargs ) : # noqa : E501 """Send a fax # noqa : E501 With this API call you will be able to send a fax ( one or more files ) to one or more destinations . If you are a corporate member and you don ' t have a fax number set your * * from * * parameter to * * NO _ NUMBER * ...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async' ) : return self . send_fax_with_http_info ( payload_outbox , ** kwargs ) # noqa : E501 else : ( data ) = self . send_fax_with_http_info ( payload_outbox , ** kwargs ) # noqa : E501 return data
def export ( self , node ) : """Export tree starting at ` node ` ."""
attriter = self . attriter or ( lambda attr_values : attr_values ) return self . __export ( node , self . dictcls , attriter , self . childiter )
def counts ( self , expTime , cycleTime , ap_scale = 1.6 , ndiv = 5 ) : """Computes counts per pixel , total counts , sky counts etc given current magnitude , seeing etc . You should run a check on the instrument parameters before calling this . expTime : exposure time per frame ( seconds ) cycleTime : sa...
# code directly translated from Java equivalent . g = get_root ( self ) . globals # Set the readout speed readSpeed = g . ipars . readSpeed ( ) if readSpeed == 'Fast' : gain = GAIN_FAST read = RNO_FAST elif readSpeed == 'Slow' : gain = GAIN_SLOW read = RNO_SLOW else : raise DriverError ( 'CountsFram...
def which ( file ) : """> > > which ( " sh " ) is not None True > > > which ( " bogus - executable - that - doesn ' t - exist " ) is None True"""
for path in os . environ [ "PATH" ] . split ( os . pathsep ) : if os . path . exists ( os . path . join ( path , file ) ) : return os . path . join ( path , file ) return None
def get_object_as_string ( obj ) : """Converts any object to JSON - like readable format , ready to be printed for debugging purposes : param obj : Any object : return : string"""
if isinstance ( obj , str ) : return obj if isinstance ( obj , list ) : return '\r\n\;' . join ( [ get_object_as_string ( item ) for item in obj ] ) attrs = vars ( obj ) as_string = ', ' . join ( "%s: %s" % item for item in attrs . items ( ) ) return as_string
def _parse_upgrade_data ( data ) : '''Helper method to parse upgrade data from the NX - OS device .'''
upgrade_result = { } upgrade_result [ 'upgrade_data' ] = None upgrade_result [ 'succeeded' ] = False upgrade_result [ 'upgrade_required' ] = False upgrade_result [ 'upgrade_non_disruptive' ] = False upgrade_result [ 'upgrade_in_progress' ] = False upgrade_result [ 'installing' ] = False upgrade_result [ 'module_data' ]...
def cufflinks ( args ) : """% prog cufflinks folder reference Run cufflinks on a folder containing tophat results ."""
p = OptionParser ( cufflinks . __doc__ ) p . add_option ( "--gtf" , help = "Reference annotation [default: %default]" ) p . set_cpus ( ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) folder , reference = args cpus = opts . cpus gtf = opts . gtf transcripts = "tra...
def node_changed ( self , node ) : """Calls : meth : ` QAbstractItemModel . dataChanged ` with given Node index . : param node : Node . : type node : AbstractCompositeNode or GraphModelNode : return : Method success . : rtype : bool"""
index = self . get_node_index ( node ) if index is not None : self . dataChanged . emit ( index , index ) return True else : return False
def _cleanup_pods ( namespace , labels ) : """Remove all pods with these labels in this namespace"""
api = kubernetes . client . CoreV1Api ( ) pods = api . list_namespaced_pod ( namespace , label_selector = format_labels ( labels ) ) for pod in pods . items : try : api . delete_namespaced_pod ( pod . metadata . name , namespace ) logger . info ( 'Deleted pod: %s' , pod . metadata . name ) excep...
def get_absolute_url ( self ) : """If override _ url was given , use that . Otherwise , if the content belongs to a blog , use a blog url . If not , use a regular article url ."""
if self . override_url : return self . override_url if self . destination . is_blog : return reverse ( 'blog_entry_detail' , args = [ self . destination . slug , self . slug ] ) return reverse ( 'article_detail' , args = [ self . slug ] )
def from_soup_tag ( tag ) : "Creates an instance from a given soup tag ."
sections = [ Section . from_soup_tag ( s ) for s in tag . findAll ( 'section' ) ] return Course ( tag [ 'name' ] , tag [ 'dept' ] , int ( tag [ 'num' ] ) , tag [ 'credmin' ] , tag [ 'credmax' ] , tag [ 'gradetype' ] , [ s for s in sections if s . is_valid ] )
def _compute_nonlinear_soil_term ( self , C , lnSA_AB , delta_C , delta_D ) : """Compute mean value on site class C / D ( equation 4 on page 22 without the first term )"""
lnSA_CD = ( # line 1 equation 4 without first term ( lnSA _ AB ) C [ 'c29' ] * delta_C + # line 2 and 3 ( C [ 'c30as' ] * np . log ( np . exp ( lnSA_AB ) + 0.03 ) + C [ 'c43' ] ) * delta_D ) return lnSA_CD
def get_context_data ( self , ** kwargs ) : """Add forms into the context dictionary ."""
context = { } if 'forms' not in kwargs : context [ 'forms' ] = self . get_forms ( ) else : context [ 'forms' ] = kwargs [ 'forms' ] return context
def select ( self , * args , ** kwargs ) : """Python3 raises ` ValueError ` if socket is closed , because fd = = - 1"""
try : return super ( PatroniSequentialThreadingHandler , self ) . select ( * args , ** kwargs ) except ValueError as e : raise select . error ( 9 , str ( e ) )
def from_array ( filename , data , iline = 189 , xline = 193 , format = SegySampleFormat . IBM_FLOAT_4_BYTE , dt = 4000 , delrt = 0 ) : """Create a new SEGY file from an n - dimentional array . Create a structured SEGY file with defaulted headers from a 2 - , 3 - or 4 - dimensional array . ilines , xlines , off...
dt = int ( dt ) delrt = int ( delrt ) data = np . asarray ( data ) dimensions = len ( data . shape ) if dimensions not in range ( 2 , 5 ) : problem = "Expected 2, 3, or 4 dimensions, {} was given" . format ( dimensions ) raise ValueError ( problem ) spec = segyio . spec ( ) spec . iline = iline spec . xline = x...
def _lei16 ( ins ) : '''Compares & pops top 2 operands out of the stack , and checks if the 1st operand < = 2nd operand ( top of the stack ) . Pushes 0 if False , 1 if True . 16 bit signed version'''
output = _16bit_oper ( ins . quad [ 2 ] , ins . quad [ 3 ] ) output . append ( 'call __LEI16' ) output . append ( 'push af' ) REQUIRES . add ( 'lei16.asm' ) return output
def pformat ( self ) : '''Manually pformat to force using " " " . . . " " " and supress escaping apostrophe'''
result = "{\n" indent1 = " " * 4 indent2 = " " * 8 for line_no , code_objects in sorted ( self . items ( ) ) : result += '%s%i: [\n' % ( indent1 , line_no ) for code_object in code_objects : result += '%s"""<%s:%s>""",\n' % ( indent2 , code_object . PART_TYPE , code_object . content ) result += '%s]...
def _unregister_bundle_factories ( self , bundle ) : # type : ( Bundle ) - > None """Unregisters all factories of the given bundle : param bundle : A bundle"""
with self . __factories_lock : # Find out which factories must be removed to_remove = [ factory_name for factory_name in self . __factories if self . get_factory_bundle ( factory_name ) is bundle ] # Remove all of them for factory_name in to_remove : try : self . unregister_factory ( fac...
def simple_reciprocal ( x , a , b ) : """reciprocal function to fit convergence data"""
if isinstance ( x , list ) : y_l = [ ] for x_v in x : y_l . append ( a + b / x_v ) y = np . array ( y_l ) else : y = a + b / x return y
def get_vertical_and_horizontal ( lines ) : """Extracts vertical and horizontal lines lists : param lines : list of lines coordinates : return : vertical _ lines , horitontal _ lines ( 2 lists of coordinates )"""
# TODO : add some angle tolerance when lines are not perfectly aligned ( eg : # scanned pdf ) vertical_lines = sorted ( [ e for e in lines if e [ 1 ] == e [ 3 ] ] , key = lambda tup : ( tup [ 1 ] , tup [ 0 ] ) ) horitontal_lines = sorted ( [ e for e in lines if e [ 0 ] == e [ 2 ] ] ) if len ( vertical_lines ) > 0 : ...
def get_parts ( self , parts = None , reference_level = 0 ) : """Recursively returns a depth - first list of all known magic parts"""
if parts is None : parts = list ( ) new_reference_level = reference_level else : self . _level_in_section = self . _level + reference_level new_reference_level = self . _level_in_section parts . append ( self . my_osid_object ) if self . _child_parts is None : if self . has_magic_children ( ) : ...
def fit ( self , X = None , y = None , ** kwargs ) : """Fit the blocks of this pipeline . Sequentially call the ` fit ` and the ` produce ` methods of each block , capturing the outputs each ` produce ` method before calling the ` fit ` method of the next one . During the whole process a context dictionary ...
context = { 'X' : X , 'y' : y } context . update ( kwargs ) last_block_name = list ( self . blocks . keys ( ) ) [ - 1 ] for block_name , block in self . blocks . items ( ) : LOGGER . debug ( "Fitting block %s" , block_name ) try : fit_args = self . _get_block_args ( block_name , block . fit_args , conte...
def modify ( self , SQL , params = '' , verbose = True ) : """Wrapper for CRUD operations to make them distinct from queries and automatically pass commit ( ) method to cursor . Parameters SQL : str The SQL query to execute params : sequence Mimics the native parameter substitution of sqlite3 verbose : ...
# Make sure the database isn ' t locked self . conn . commit ( ) if SQL . lower ( ) . startswith ( 'select' ) : print ( 'Use self.query method for queries.' ) else : self . list ( SQL , params ) self . conn . commit ( ) if verbose : print ( 'Number of records modified: {}' . format ( self . list...
def _str_member_list ( self , name ) : """Generate a member listing , autosummary : : table where possible , and a table where not ."""
out = [ ] if self [ name ] : out += [ '.. rubric:: %s' % name , '' ] prefix = getattr ( self , '_name' , '' ) if prefix : prefix = '~%s.' % prefix autosum = [ ] others = [ ] for param , param_type , desc in self [ name ] : param = param . strip ( ) # Check if the referenc...
def validate_target ( func , * args , ** kwargs ) : """A decorator that ensures that the specified target _ id exists and is valid . Expects the target ID to be either the ' target _ id ' param in kwargs , or the first positional parameter . Raises a NoSuchTargetException if the target does not exist ."""
def inner ( self , * args , ** kwargs ) : # find the target param target_id = None if 'target_id' in kwargs and kwargs [ 'target_id' ] != None : target_id = kwargs [ 'target_id' ] else : target_id = 0 # if there was a target specified , check that it ' s valid if not self . target_is...
def parse_number_from_substring ( substring ) -> Optional [ float ] : '''Returns the number in the expected string " N : 12.3 " , where " N " is the key , and " 12.3 " is a floating point value For the temp - deck or thermocycler ' s temperature response , one expected input is something like " T : none " , w...
try : value = substring . split ( ':' ) [ 1 ] if value . strip ( ) . lower ( ) == 'none' : return None return round ( float ( value ) , GCODE_ROUNDING_PRECISION ) except ( ValueError , IndexError , TypeError , AttributeError ) : log . exception ( 'Unexpected argument to parse_number_from_substri...
def from_string ( cls , string , * , default_func = None ) : '''Construct a NetAddress from a string and return a ( host , port ) pair . If either ( or both ) is missing and default _ func is provided , it is called with ServicePart . HOST or ServicePart . PORT to get a default .'''
if not isinstance ( string , str ) : raise TypeError ( f'address must be a string: {string}' ) host , port = _split_address ( string ) if default_func : host = host or default_func ( ServicePart . HOST ) port = port or default_func ( ServicePart . PORT ) if not host or not port : raise ValueErro...
def analyze_db_reading ( job_prefix , reading_queue = 'run_db_reading_queue' ) : """Run various analysis on a particular reading job ."""
# Analyze reach failures log_strs = get_logs_from_db_reading ( job_prefix , reading_queue ) indra_log_strs = [ ] all_reach_logs = [ ] log_stats = [ ] for log_str in log_strs : log_str , reach_logs = separate_reach_logs ( log_str ) all_reach_logs . extend ( reach_logs ) indra_log_strs . append ( log_str ) ...
def _setup_metric_group_values ( self ) : """Return the list of MetricGroupValues objects for this metrics response , by processing its metrics response string . The lines in the metrics response string are : : MetricsResponse : MetricsGroup { 0 , * } < emptyline > a third empty line at the end MetricsGro...
mg_defs = self . _metrics_context . metric_group_definitions metric_group_name = None resource_uri = None dt_timestamp = None object_values = None metric_group_values = list ( ) state = 0 for mr_line in self . _metrics_response_str . splitlines ( ) : if state == 0 : if object_values is not None : # Store th...
def _truncate ( f , n ) : """Truncates / pads a float ` f ` to ` n ` decimal places without rounding From https : / / stackoverflow . com / a / 783927/1307974 ( CC - BY - SA )"""
s = "{}" . format ( f ) if "e" in s or "E" in s : return "{0:.{1}f}" . format ( f , n ) i , p , d = s . partition ( "." ) return "." . join ( [ i , ( d + "0" * n ) [ : n ] ] )
def merge ( cls , edge1 , edge2 ) : """Merges multi - color information from two supplied : class : ` BGEdge ` instances into a new : class : ` BGEdge ` Since : class : ` BGEdge ` represents an undirected edge , created edge ' s vertices are assign according to the order in first supplied edge . Accounts for su...
if edge1 . vertex1 != edge2 . vertex1 and edge1 . vertex1 != edge2 . vertex2 : raise ValueError ( "Edges to be merged do not connect same vertices" ) forward = edge1 . vertex1 == edge2 . vertex1 if forward and edge1 . vertex2 != edge2 . vertex2 : raise ValueError ( "Edges to be merged do not connect same vertic...
def read_nb ( filename , solution ) -> nbformat . NotebookNode : """Takes in a filename of a notebook and returns a notebook object containing only the cell outputs to export ."""
with open ( filename , 'r' ) as f : nb = nbformat . read ( f , as_version = 4 ) email = find_student_email ( nb ) preamble = nbformat . v4 . new_markdown_cell ( source = '# ' + email , metadata = { 'tags' : [ 'q_email' ] } ) tags_to_check = TAGS if not solution else SOL_TAGS cells = ( [ preamble ] + [ remove_input ...
def offline ( f ) : """This decorator allows you to access ` ` ctx . peerplays ` ` which is an instance of PeerPlays with ` ` offline = True ` ` ."""
@ click . pass_context @ verbose def new_func ( ctx , * args , ** kwargs ) : ctx . obj [ "offline" ] = True ctx . peerplays = PeerPlays ( ** ctx . obj ) ctx . blockchain = ctx . peerplays set_shared_peerplays_instance ( ctx . peerplays ) return ctx . invoke ( f , * args , ** kwargs ) return update_w...
def _process_mgi_note_vocevidence_view ( self , limit ) : """Here we fetch the free text descriptions of the phenotype associations . Triples : < annot _ id > dc : description " description text " : param limit : : return :"""
line_counter = 0 if self . test_mode : graph = self . testgraph else : graph = self . graph model = Model ( graph ) LOG . info ( "getting free text descriptions for annotations" ) raw = '/' . join ( ( self . rawdir , 'mgi_note_vocevidence_view' ) ) with open ( raw , 'r' , encoding = "utf8" ) as csvfile : fi...
def integral ( self , xbin1 = None , xbin2 = None , width = False , error = False , overflow = False ) : """Compute the integral and error over a range of bins"""
if xbin1 is None : xbin1 = 0 if overflow else 1 if xbin2 is None : xbin2 = - 1 if overflow else - 2 nbinsx = self . nbins ( axis = 0 , overflow = True ) xbin1 %= nbinsx xbin2 %= nbinsx options = 'width' if width else '' if error : error = ROOT . Double ( ) integral = super ( _Hist , self ) . IntegralAnd...
def create_or_update_role ( self , name , azure_roles , ttl = "" , max_ttl = "" , mount_point = DEFAULT_MOUNT_POINT ) : """Create or update a Vault role . The provided Azure roles must exist for this call to succeed . See the Azure secrets roles docs for more information about roles . Supported methods : PO...
params = { 'azure_roles' : json . dumps ( azure_roles ) , 'ttl' : ttl , 'max_ttl' : max_ttl , } api_path = '/v1/{mount_point}/roles/{name}' . format ( mount_point = mount_point , name = name ) return self . _adapter . post ( url = api_path , json = params , )
def _get_ip ( ) : """Get IP address for the docker host"""
cmd_netstat = [ 'netstat' , '-nr' ] p1 = subprocess . Popen ( cmd_netstat , stdout = subprocess . PIPE ) cmd_grep = [ 'grep' , '^0\.0\.0\.0' ] p2 = subprocess . Popen ( cmd_grep , stdin = p1 . stdout , stdout = subprocess . PIPE ) cmd_awk = [ 'awk' , '{ print $2 }' ] p3 = subprocess . Popen ( cmd_awk , stdin = p2 . std...
def _readXputMaps ( self , mapCards , directory , session , spatial = False , spatialReferenceID = 4236 , replaceParamFile = None ) : """GSSHA Project Read Map Files from File Method"""
if self . mapType in self . MAP_TYPES_SUPPORTED : for card in self . projectCards : if ( card . name in mapCards ) and self . _noneOrNumValue ( card . value ) : filename = card . value . strip ( '"' ) # Invoke read method on each map self . _invokeRead ( fileIO = RasterMa...
def create_helper_trans_node ( op_name , input_node , node_name ) : """create extra transpose node for dot operator"""
node_name = op_name + "_" + node_name trans_node = onnx . helper . make_node ( 'Transpose' , inputs = [ input_node ] , outputs = [ node_name ] , name = node_name ) return trans_node
def cursor ( self ) : """Return cursor object that can be used to make queries and fetch results from the database ."""
self . _assert_open ( ) if self . mars_enabled : in_tran = self . _conn . tds72_transaction if in_tran and self . _dirty : try : return _MarsCursor ( self , self . _conn . create_session ( self . _tzinfo_factory ) , self . _tzinfo_factory ) except ( socket . error , OSError ) as e : ...
def process_mappings ( self ) : """Process the mappings for a Frame Relay switch . Removes duplicates and adds the mappings to the node properties"""
for mapping_a in self . mappings : for mapping_b in self . mappings : if mapping_a [ 'source' ] == mapping_b [ 'dest' ] : self . mappings . remove ( mapping_b ) break self . node [ 'properties' ] [ 'mappings' ] = { } mappings = self . node [ 'properties' ] [ 'mappings' ] for mapping ...
def _combine_contract ( self , years , wages ) : """Combine the contract wages and year . Match the wages with the year and add to a dictionary representing the player ' s contract . Parameters years : list A list where each element is a string denoting the season , such as '2017-18 ' . wages : list ...
contract = { } for i in range ( len ( years ) ) : contract [ years [ i ] ] = wages [ i ] return contract
def insert ( self , iterable , index = 0 , data = None , weight = 1.0 ) : """Insert new node into tree Args : iterable ( hashable ) : key used to find in the future . data ( object ) : data associated with the key index ( int ) : an index used for insertion . weight ( float ) : the wait given for the item...
if index == len ( iterable ) : self . is_terminal = True self . key = iterable self . weight = weight if data : self . data . add ( data ) else : if iterable [ index ] not in self . children : self . children [ iterable [ index ] ] = TrieNode ( ) self . children [ iterable [ inde...
def usergroups_users_update ( self , * , usergroup : str , users : List [ str ] , ** kwargs ) -> SlackResponse : """Update the list of users for a User Group Args : usergroup ( str ) : The encoded ID of the User Group to update . e . g . ' S0604QSJC ' users ( list ) : A list user IDs that represent the enti...
self . _validate_xoxp_token ( ) kwargs . update ( { "usergroup" : usergroup , "users" : users } ) return self . api_call ( "usergroups.users.update" , json = kwargs )
def delete ( self , name = None ) : "Delete the shelve data file ."
logger . info ( 'clearing shelve data' ) self . close ( ) for path in Path ( self . create_path . parent , self . create_path . name ) , Path ( self . create_path . parent , self . create_path . name + '.db' ) : logger . debug ( f'clearing {path} if exists: {path.exists()}' ) if path . exists ( ) : path...
def get_spider_stats ( self ) : '''Gather spider based stats'''
self . logger . debug ( "Gathering spider stats" ) the_dict = { } spider_set = set ( ) total_spider_count = 0 keys = self . redis_conn . keys ( 'stats:crawler:*:*:*' ) for key in keys : # we only care about the spider elements = key . split ( ":" ) spider = elements [ 3 ] if spider not in the_dict : ...
def _getSyntaxBySourceFileName ( self , name ) : """Get syntax by source name of file , which is going to be highlighted"""
for regExp , xmlFileName in self . _extensionToXmlFileName . items ( ) : if regExp . match ( name ) : return self . _getSyntaxByXmlFileName ( xmlFileName ) else : raise KeyError ( "No syntax for " + name )
def localize ( self , formatter , translator ) : """Return a localized version of the ` localizable _ string ` passed to the consturctor . It is formatted using the ` formatter ` with the ` args ` and ` kwargs ` passed to the constructor of : class : ` UserError ` ."""
return self . localizable_string . localize ( formatter , translator , * self . args , ** self . kwargs )
def current ( self ) : """get the index of the currently executing chain element : return int : current chain index"""
if not self . started : return None return count_group ( self . group , cached = self . cached )