signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def format_value ( self ) : """Return the formatted ( interpreted ) data according to ` data _ type ` ."""
return format_value ( self . data_type , self . data , self . parent . stringpool_main . getString )
def in_units ( self , units , equivalence = None , ** kwargs ) : """Creates a copy of this array with the data converted to the supplied units , and returns it . Optionally , an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions . Parameters units : Unit ...
units = _sanitize_units_convert ( units , self . units . registry ) if equivalence is None : conv_data = _check_em_conversion ( self . units , units , registry = self . units . registry ) if any ( conv_data ) : new_units , ( conversion_factor , offset ) = _em_conversion ( self . units , conv_data , unit...
def blink ( self , interval : float = 0.2 , n : int = 3 ) : """Blink all the lights on and off at once . NOTE ! Does not remember prior state of lights and will finish with all lights off . : param interval : The length in seconds of an ON / OFF cycle : param n : How many times to cycle ON and OFF : retur...
for i in range ( n ) : self . all_on ( ) time . sleep ( interval / 2 ) self . all_off ( ) time . sleep ( interval / 2 )
def autoregister ( self , cls ) : """Autoregister a class that is encountered for the first time . : param cls : The class that should be registered ."""
params = self . get_meta_attributes ( cls ) return self . register ( cls , params )
def sub ( x , y , context = None ) : """Return ` ` x ` ` - ` ` y ` ` ."""
return _apply_function_in_current_context ( BigFloat , mpfr . mpfr_sub , ( BigFloat . _implicit_convert ( x ) , BigFloat . _implicit_convert ( y ) , ) , context , )
def set_title ( self , index , title ) : """Sets the title of a container page . Parameters index : int Index of the container page title : unicode New title"""
# JSON dictionaries have string keys , so we convert index to a string index = unicode_type ( int ( index ) ) self . _titles [ index ] = title self . send_state ( '_titles' )
def OnReplaceAll ( self , event ) : """Called when a replace all operation is started"""
find_string = event . GetFindString ( ) flags = self . _wxflag2flag ( event . GetFlags ( ) ) replace_string = event . GetReplaceString ( ) findpositions = self . grid . actions . find_all ( find_string , flags ) with undo . group ( _ ( "Replace all" ) ) : self . grid . actions . replace_all ( findpositions , find_s...
def get ( self , address ) : """Get a loopback address by it ' s address . Find all loopback addresses by iterating at either the node level or the engine : : loopback = engine . loopback _ interface . get ( ' 127.0.0.10 ' ) : param str address : ip address of loopback : raises InterfaceNotFound : invalid i...
loopback = super ( LoopbackCollection , self ) . get ( address = address ) if loopback : return loopback raise InterfaceNotFound ( 'Loopback address specified was not found' )
def write_template ( data , results_dir , parent ) : """Write the html template : param dict data : the dict containing all data for output : param str results _ dir : the ouput directory for results : param str parent : the parent directory"""
print ( "Generating html report..." ) partial = time . time ( ) j_env = Environment ( loader = FileSystemLoader ( os . path . join ( results_dir , parent , 'templates' ) ) ) template = j_env . get_template ( 'report.html' ) report_writer = ReportWriter ( results_dir , parent ) report_writer . write_report ( template . ...
def map_providers ( self , query = 'list_nodes' , cached = False ) : '''Return a mapping of what named VMs are running on what VM providers based on what providers are defined in the configuration and VMs'''
if cached is True and query in self . __cached_provider_queries : return self . __cached_provider_queries [ query ] pmap = { } for alias , drivers in six . iteritems ( self . opts [ 'providers' ] ) : for driver , details in six . iteritems ( drivers ) : fun = '{0}.{1}' . format ( driver , query ) ...
def analyze ( self , structure , n = 0 ) : """Performs Voronoi analysis and returns the polyhedra around atom n in Schlaefli notation . Args : structure ( Structure ) : structure to analyze n ( int ) : index of the center atom in structure Returns : voronoi index of n : < c3 , c4 , c6 , c6 , c7 , c8 , c...
center = structure [ n ] neighbors = structure . get_sites_in_sphere ( center . coords , self . cutoff ) neighbors = [ i [ 0 ] for i in sorted ( neighbors , key = lambda s : s [ 1 ] ) ] qvoronoi_input = np . array ( [ s . coords for s in neighbors ] ) voro = Voronoi ( qvoronoi_input , qhull_options = self . qhull_optio...
def on_variables_request ( self , py_db , request ) : '''Variables can be asked whenever some place returned a variables reference ( so , it can be a scope gotten from on _ scopes _ request , the result of some evaluation , etc . ) . Note that in the DAP the variables reference requires a unique int . . . the w...
arguments = request . arguments # : : type arguments : VariablesArguments variables_reference = arguments . variablesReference thread_id = py_db . suspended_frames_manager . get_thread_id_for_variable_reference ( variables_reference ) if thread_id is not None : self . api . request_get_variable_json ( py_db , reque...
def getAlertContacts ( self , alertContacts = None , offset = None , limit = None ) : """Get Alert Contacts"""
url = self . baseUrl url += "getAlertContacts?apiKey=%s" % self . apiKey if alertContacts : url += "&alertContacts=%s" % alertContacts if offset : url += "&offset=%s" % offset if limit : url += "&limit=%s" % limit url += "&format=json" return self . requestApi ( url )
def update_or_create ( cls , with_status = False , ** kwargs ) : """Update or create active directory configuration . : param dict kwargs : kwargs to satisfy the ` create ` constructor arguments if the element doesn ' t exist or attributes to change : raises CreateElementFailed : failed creating element : r...
element , updated , created = super ( ActiveDirectoryServer , cls ) . update_or_create ( defer_update = True , ** kwargs ) if not created : domain_controller = kwargs . pop ( 'domain_controller' , [ ] ) if domain_controller : current_dc_list = element . domain_controller for dc in domain_controller ...
def get_ngrams ( path ) : """Returns a list of n - grams read from the file at ` path ` ."""
with open ( path , encoding = 'utf-8' ) as fh : ngrams = [ ngram . strip ( ) for ngram in fh . readlines ( ) ] return ngrams
def cookies ( self ) : """Returns a list of all cookies in cookie string format ."""
return [ line . strip ( ) for line in self . conn . issue_command ( "GetCookies" ) . split ( "\n" ) if line . strip ( ) ]
def policy_map_class_scheduler_strict_priority_priority_number ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) policy_map = ET . SubElement ( config , "policy-map" , xmlns = "urn:brocade.com:mgmt:brocade-policer" ) po_name_key = ET . SubElement ( policy_map , "po-name" ) po_name_key . text = kwargs . pop ( 'po_name' ) class_el = ET . SubElement ( policy_map , "class" ) cl_name_key = ET . SubEl...
def visit_ListComp ( self , node : ast . ListComp ) -> None : """Represent the list comprehension by dumping its source code ."""
if node in self . _recomputed_values : value = self . _recomputed_values [ node ] text = self . _atok . get_text ( node ) self . reprs [ text ] = value self . generic_visit ( node = node )
def get_sequence_alignment_strings_as_html ( self , pdb_list = [ ] , reversed = False , width = 80 , line_separator = '\n' , extra_tooltip_class = '' ) : '''Takes a list , pdb _ list , of pdb names e . g . [ ' Model ' , ' Scaffold ' , . . . ] with which the object was created . Using the first element of this lis...
raise Exception ( 'Re-implement using the equivalence classes.' ) sequence_alignment_printer_tuples = self . get_sequence_alignment_printer_objects ( pdb_list = pdb_list , reversed = reversed , width = width , line_separator = line_separator ) if not sequence_alignment_printer_tuples : return '' html = [ ] for sequ...
def path ( self ) : "Returns the path up to the root for the current node ."
if self . parent : return '.' . join ( [ self . parent . path , str ( self . identifier ) ] ) else : return self . identifier if self . identifier else self . __class__ . __name__
def manage_subscription ( ) : """Shows how to interact with a parameter subscription ."""
subscription = processor . create_parameter_subscription ( [ '/YSS/SIMULATOR/BatteryVoltage1' ] ) sleep ( 5 ) print ( 'Adding extra items to the existing subscription...' ) subscription . add ( [ '/YSS/SIMULATOR/Alpha' , '/YSS/SIMULATOR/BatteryVoltage2' , 'MDB:OPS Name/SIMULATOR_PrimBusVoltage1' , ] ) sleep ( 5 ) print...
def main ( self , phase_inc ) : """: param phase _ inc : amount of rotation applied for next clock cycle , must be normalized to - 1 to 1. : rtype : Complex"""
self . phase_acc = self . phase_acc + phase_inc start_x = self . INIT_X start_y = Sfix ( 0.0 , 0 , - 17 ) x , y , phase = self . cordic . main ( start_x , start_y , self . phase_acc ) self . out . real = x self . out . imag = y return self . out
def _wifi_connect ( ) : """Connects to WIFI"""
if not wlan . isconnected ( ) : wlan . active ( True ) print ( "NETWORK: connecting to network %s..." % settings . WIFI_SSID ) wlan . connect ( settings . WIFI_SSID , secret ) while not wlan . isconnected ( ) : print ( "NETWORK: waiting for connection..." ) utime . sleep ( 1 ) print ...
def main ( list_ids , model , contact_server , raw_data_id , show_raw , mysql_cfg = 'mysql_online' ) : """Main function of view . py ."""
if list_ids : preprocessing_desc , _ , _ = _get_system ( model ) raw_datapath = os . path . join ( utils . get_project_root ( ) , preprocessing_desc [ 'data-source' ] ) _list_ids ( raw_datapath ) else : if contact_server : data = _fetch_data_from_server ( raw_data_id , mysql_cfg ) print ...
def get_stp_mst_detail_output_cist_port_link_type ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) get_stp_mst_detail = ET . Element ( "get_stp_mst_detail" ) config = get_stp_mst_detail output = ET . SubElement ( get_stp_mst_detail , "output" ) cist = ET . SubElement ( output , "cist" ) port = ET . SubElement ( cist , "port" ) link_type = ET . SubElement ( port , "link-type" ) link...
def generateName ( nodeName : str , instId : int ) : """Create and return the name for a replica using its nodeName and instanceId . Ex : Alpha : 1"""
if isinstance ( nodeName , str ) : # Because sometimes it is bytes ( why ? ) if ":" in nodeName : # Because in some cases ( for requested messages ) it # already has ' : ' . This should be fixed . return nodeName return "{}:{}" . format ( nodeName , instId )
def prt_txt ( prt , goea_results , prtfmt = None , ** kws ) : """Print GOEA results in text format ."""
objprt = PrtFmt ( ) if prtfmt is None : flds = [ 'GO' , 'NS' , 'p_uncorrected' , 'ratio_in_study' , 'ratio_in_pop' , 'depth' , 'name' , 'study_items' ] prtfmt = objprt . get_prtfmt_str ( flds ) prtfmt = objprt . adjust_prtfmt ( prtfmt ) prt_flds = RPT . get_fmtflds ( prtfmt ) data_nts = MgrNtGOEAs ( goea_result...
def __clean_dict ( dictionary ) : """Takes the dictionary from _ _ parse _ content ( ) and creates a well formatted list : param dictionary : unformatted dict : returns : a list which contains dict ' s as it ' s elements"""
key_dict = { } value_dict = { } final_list = [ ] for key in dictionary . keys ( ) : key_dict [ key ] = "seq" for value in dictionary . values ( ) : value_dict [ value ] = "text" for ( key1 , value1 ) , ( key2 , value2 ) in zip ( key_dict . items ( ) , value_dict . items ( ) ) : final_list . append ( { value...
def gen ( nodes , n , graph ) : # TODO There could be a more convenient way of doing this . This generators # single purpose is to prepare data for multiprocessing ' s starmap function . """Generator for applying multiprocessing . Parameters nodes : list List of nodes in the system . n : int Number of des...
g = graph . copy ( ) for i in range ( 0 , len ( nodes ) , n ) : yield ( nodes [ i : i + n ] , g )
def hlen ( self , name ) : """Returns the number of elements in the Hash . : param name : str the name of the redis key : return : Future ( )"""
with self . pipe as pipe : return pipe . hlen ( self . redis_key ( name ) )
def default_policy ( policy = 'deny' , direction = 'incoming' ) : """Changes the default policy for traffic ` direction ` : param policy : allow , deny or reject : param direction : traffic direction , possible values : incoming , outgoing , routed"""
if policy not in [ 'allow' , 'deny' , 'reject' ] : raise UFWError ( ( 'Unknown policy %s, valid values: ' 'allow, deny, reject' ) % policy ) if direction not in [ 'incoming' , 'outgoing' , 'routed' ] : raise UFWError ( ( 'Unknown direction %s, valid values: ' 'incoming, outgoing, routed' ) % direction ) output ...
def _ps ( osdata ) : '''Return the ps grain'''
grains = { } bsd_choices = ( 'FreeBSD' , 'NetBSD' , 'OpenBSD' , 'MacOS' ) if osdata [ 'os' ] in bsd_choices : grains [ 'ps' ] = 'ps auxwww' elif osdata [ 'os_family' ] == 'Solaris' : grains [ 'ps' ] = '/usr/ucb/ps auxwww' elif osdata [ 'os' ] == 'Windows' : grains [ 'ps' ] = 'tasklist.exe' elif osdata . get...
def pfmerge ( self , dest_key , * keys ) : """Merge multiple HyperLogLog values into an unique value that will approximate the cardinality of the union of the observed Sets of the source HyperLogLog structures . The computed merged HyperLogLog is set to the destination variable , which is created if does no...
return self . _execute ( [ b'PFMERGE' , dest_key ] + list ( keys ) , b'OK' )
def legend_title_header_element ( feature , parent ) : """Retrieve legend title header string from definitions ."""
_ = feature , parent # NOQA header = legend_title_header [ 'string_format' ] return header . capitalize ( )
def get_file ( self , project , build_id , artifact_name , file_id , file_name , ** kwargs ) : """GetFile . Gets a file from the build . : param str project : Project ID or project name : param int build _ id : The ID of the build . : param str artifact _ name : The name of the artifact . : param str file...
route_values = { } if project is not None : route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' ) if build_id is not None : route_values [ 'buildId' ] = self . _serialize . url ( 'build_id' , build_id , 'int' ) query_parameters = { } if artifact_name is not None : query_parame...
def sepa_transfer ( self , account : SEPAAccount , pain_message : str , multiple = False , control_sum = None , currency = 'EUR' , book_as_single = False , pain_descriptor = 'urn:iso:std:iso:20022:tech:xsd:pain.001.001.03' ) : """Custom SEPA transfer . : param account : SEPAAccount to send the transfer from . :...
with self . _get_dialog ( ) as dialog : if multiple : command_class = HKCCM1 else : command_class = HKCCS1 hiccxs , hkccx = self . _find_highest_supported_command ( command_class , return_parameter_segment = True ) seg = hkccx ( account = hkccx . _fields [ 'account' ] . type . from_sepa_...
def everything ( self , content_id = None ) : '''Returns a generator of all labels in the store . If ` ` content _ id ` ` is set , will restrict results to labels containing the provided ` ` content _ id ` ` .'''
if content_id is not None : ranges = [ ( ( content_id , ) , ( content_id , ) ) ] else : ranges = [ ] labels = self . kvl . scan ( self . TABLE , * ranges ) labels = imap ( lambda p : self . _label_from_kvlayer ( * p ) , labels ) return labels
def create_collection ( self , name , type = 2 ) : """Shortcut to create a collection : param name Collection name : param type Collection type ( 2 = document / 3 = edge ) : returns Collection"""
return Collection . create ( name = name , database = self . name , type = type )
def fetch_model_data ( model_querysets , model_ids_to_fetch ) : """Given a dictionary of models to querysets and model IDs to models , fetch the IDs for every model and return the objects in the following structure . model : { id : obj ,"""
return { model : id_dict ( model_querysets [ model ] . filter ( id__in = ids_to_fetch ) ) for model , ids_to_fetch in model_ids_to_fetch . items ( ) }
def describe ( inlist ) : """Returns some descriptive statistics of the passed list ( assumed to be 1D ) . Usage : ldescribe ( inlist ) Returns : n , mean , standard deviation , skew , kurtosis"""
n = len ( inlist ) mm = ( min ( inlist ) , max ( inlist ) ) m = mean ( inlist ) sd = stdev ( inlist ) sk = skew ( inlist ) kurt = kurtosis ( inlist ) return n , mm , m , sd , sk , kurt
def to_json ( self ) : """: return : str"""
json_dict = self . to_json_basic ( ) json_dict [ 'local_control' ] = self . local_control json_dict [ 'status_mode' ] = DSTATUS [ self . status_mode ] json_dict [ 'auto_send' ] = self . auto_send json_dict [ 'mode' ] = DMODE [ self . mode ] json_dict [ 'cool' ] = self . cool json_dict [ 'heater' ] = self . heater json_...
def _refresh ( self ) : """Refreshes the cursor with more data from Mongo . Returns the length of self . _ _ data after refresh . Will exit early if self . _ _ data is already non - empty . Raises OperationFailure when the cursor cannot be refreshed due to an error on the query ."""
if len ( self . __data ) or self . __killed : return len ( self . __data ) if self . __id is None : # Query self . __send_message ( _Query ( self . __query_flags , self . __collection . database . name , self . __collection . name , self . __skip , self . __query_spec ( ) , self . __projection , self . __codec_...
def items2file ( items , filename , encoding = 'utf-8' , modifier = 'w' ) : """json array to file , canonical json format"""
with codecs . open ( filename , modifier , encoding = encoding ) as f : for item in items : f . write ( u"{}\n" . format ( json . dumps ( item , ensure_ascii = False , sort_keys = True ) ) )
def parse ( self , argument ) : """See base class ."""
if isinstance ( argument , six . string_types ) : if argument . lower ( ) in ( 'true' , 't' , '1' ) : return True elif argument . lower ( ) in ( 'false' , 'f' , '0' ) : return False else : raise ValueError ( 'Non-boolean argument to boolean flag' , argument ) elif isinstance ( argume...
def __ipv6_netmask ( value ) : '''validate an IPv6 integer netmask'''
valid , errmsg = False , 'IPv6 netmask (0->128)' valid , value , _ = __int ( value ) valid = ( valid and 0 <= value <= 128 ) return ( valid , value , errmsg )
def K_ball_valve_Crane ( D1 , D2 , angle , fd = None ) : r'''Returns the loss coefficient for a ball valve as shown in [ 1 ] _ . If β = 1: . . math : : K = K _ 1 = K _ 2 = 3f _ d If β < 1 and θ < = 45 ° : . . math : : K _ 2 = \ frac { K + \ sin \ frac { \ theta } { 2 } \ left [ 0.8(1 - \ beta ^ 2) + 2...
if fd is None : fd = ft_Crane ( D2 ) beta = D1 / D2 K1 = 3 * fd angle = radians ( angle ) if beta == 1 : return K1 else : if angle <= pi / 4 : return ( K1 + sin ( angle / 2 ) * ( 0.8 * ( 1 - beta ** 2 ) + 2.6 * ( 1 - beta ** 2 ) ** 2 ) ) / beta ** 4 else : return ( K1 + 0.5 * ( sin ( ang...
def mkdir ( dirs , user = None , group = None , mode = None , use_sudo = True ) : """Create directory with sudo and octal mode , then set ownership ."""
if isinstance ( dirs , basestring ) : dirs = [ dirs ] runner = sudo if use_sudo else run if dirs : modearg = '-m {:o}' . format ( mode ) if mode else '' cmd = 'mkdir -v -p {} {}' . format ( modearg , ' ' . join ( dirs ) ) result = runner ( cmd ) with hide ( 'commands' ) : chown ( dirs , user...
def load_sst ( path = None , url = 'http://nlp.stanford.edu/sentiment/trainDevTestTrees_PTB.zip' ) : """Download and read in the Stanford Sentiment Treebank dataset into a dictionary with a ' train ' , ' dev ' , and ' test ' keys . The dictionary keys point to lists of LabeledTrees . Arguments : path : str ...
if path is None : # find a good temporary path path = os . path . expanduser ( "~/stanford_sentiment_treebank/" ) makedirs ( path , exist_ok = True ) fnames = download_sst ( path , url ) return { key : import_tree_corpus ( value ) for key , value in fnames . items ( ) }
def step_file_should_contain_log_records ( context , filename ) : """Verifies that the command output contains the specified log records ( in any order ) . . . code - block : gherkin Then the file " xxx . log " should contain the log records : | category | level | message | | bar | CURRENT | xxx |"""
assert context . table , "REQUIRE: context.table" context . table . require_columns ( [ "category" , "level" , "message" ] ) format = getattr ( context , "log_record_format" , context . config . logging_format ) for row in context . table . rows : output = LogRecordTable . make_output_for_row ( row , format ) c...
def _compute_or_skip_on_error ( calc , compute_kwargs ) : """Execute the Calc , catching and logging exceptions , but don ' t re - raise . Prevents one failed calculation from stopping a larger requested set of calculations ."""
try : return calc . compute ( ** compute_kwargs ) except Exception : msg = ( "Skipping aospy calculation `{0}` due to error with the " "following traceback: \n{1}" ) logging . warning ( msg . format ( calc , traceback . format_exc ( ) ) ) return None
def order_by ( self , key_selector = identity ) : '''Sorts by a key in ascending order . Introduces a primary sorting order to the sequence . Additional sort criteria should be specified by subsequent calls to then _ by ( ) and then _ by _ descending ( ) . Calling order _ by ( ) or order _ by _ descending ( )...
if self . closed ( ) : raise ValueError ( "Attempt to call order_by() on a " "closed Queryable." ) if not is_callable ( key_selector ) : raise TypeError ( "order_by() parameter key_selector={key_selector} " "is not callable" . format ( key_selector = repr ( key_selector ) ) ) return self . _create_ordered ( ite...
def set_ ( key , value , profile = None ) : '''Set a value into the Redis SDB .'''
if not profile : return False redis_kwargs = profile . copy ( ) redis_kwargs . pop ( 'driver' ) redis_conn = redis . StrictRedis ( ** redis_kwargs ) return redis_conn . set ( key , value )
def getGroups ( self , proteinId ) : """Return a list of protein groups a protein is associated with ."""
return [ self . groups [ gId ] for gId in self . _proteinToGroupIds [ proteinId ] ]
def do ( self ) : """Executes the request represented by this object . The requests library will be used for this purpose . Returns an instance of requests . Response ."""
data = None if self . body is not None and self . body != b'' : data = self . body return requests . request ( self . method , str ( self . url ) , data = data , headers = self . header )
def root ( self , value ) : """Set new XML tree"""
self . _xml = t2s ( value ) self . _root = value
def get_bucket ( ) : """Get listing of S3 Bucket"""
args = parser . parse_args ( ) bucket = s3_bucket ( args . aws_access_key_id , args . aws_secret_access_key , args . bucket_name ) for b in bucket . list ( ) : print ( '' . join ( [ i if ord ( i ) < 128 else ' ' for i in b . name ] ) )
def get_bin_index ( self , value ) : """Used to get the index of the bin to place a particular value ."""
if value == self . max_value : return self . num_bins - 1 return int ( ( value - self . min_value ) / self . bin_size )
def admin_approve_announcement_view ( request , req_id ) : """The administrator approval announcement request page . Admins will view this page through the UI . req _ id : The ID of the AnnouncementRequest"""
req = get_object_or_404 ( AnnouncementRequest , id = req_id ) requested_teachers = req . teachers_requested . all ( ) logger . debug ( requested_teachers ) if request . method == "POST" : form = AnnouncementRequestForm ( request . POST , instance = req ) if form . is_valid ( ) : req = form . save ( comm...
def process_settings ( pelicanobj ) : """Sets user specified MathJax settings ( see README for more details )"""
mathjax_settings = { } # NOTE TO FUTURE DEVELOPERS : Look at the README and what is happening in # this function if any additional changes to the mathjax settings need to # be incorporated . Also , please inline comment what the variables # will be used for # Default settings mathjax_settings [ 'auto_insert' ] = True #...
def common_install_mysql ( self ) : """Install mysql"""
sudo ( "debconf-set-selections <<< 'mysql-server mysql-server/root_password password {0}'" . format ( self . mysql_password ) ) sudo ( "debconf-set-selections <<< 'mysql-server mysql-server/root_password_again password {0}'" . format ( self . mysql_password ) ) sudo ( 'apt-get install mysql-server -y' ) print ( green (...
def parse ( self , fo ) : """Convert HMS output to motifs Parameters fo : file - like File object containing HMS output . Returns motifs : list List of Motif instances ."""
motifs = [ ] m = [ [ float ( x ) for x in fo . readline ( ) . strip ( ) . split ( " " ) ] for i in range ( 4 ) ] matrix = [ [ m [ 0 ] [ i ] , m [ 1 ] [ i ] , m [ 2 ] [ i ] , m [ 3 ] [ i ] ] for i in range ( len ( m [ 0 ] ) ) ] motifs = [ Motif ( matrix ) ] motifs [ - 1 ] . id = self . name return motifs
def trace ( data , name , format = 'png' , datarange = ( None , None ) , suffix = '' , path = './' , rows = 1 , columns = 1 , num = 1 , last = True , fontmap = None , verbose = 1 ) : """Generates trace plot from an array of data . : Arguments : data : array or list Usually a trace from an MCMC sample . name...
if fontmap is None : fontmap = { 1 : 10 , 2 : 8 , 3 : 6 , 4 : 5 , 5 : 4 } # Stand - alone plot or subplot ? standalone = rows == 1 and columns == 1 and num == 1 if standalone : if verbose > 0 : print_ ( 'Plotting' , name ) figure ( ) subplot ( rows , columns , num ) pyplot ( data . tolist ( ) ) ylim...
def cleanup_candidates ( self , node_ip ) : """Removes old TCP hole punching candidates for a designated node if a certain amount of time has passed since they last connected ."""
if node_ip in self . factory . candidates : old_candidates = [ ] for candidate in self . factory . candidates [ node_ip ] : elapsed = int ( time . time ( ) - candidate [ "time" ] ) if elapsed > self . challege_timeout : old_candidates . append ( candidate ) for candidate in old_c...
def wait ( self , timeout : Union [ float , datetime . timedelta ] = None ) -> Awaitable [ None ] : """Block until the internal flag is true . Returns an awaitable , which raises ` tornado . util . TimeoutError ` after a timeout ."""
fut = Future ( ) # type : Future [ None ] if self . _value : fut . set_result ( None ) return fut self . _waiters . add ( fut ) fut . add_done_callback ( lambda fut : self . _waiters . remove ( fut ) ) if timeout is None : return fut else : timeout_fut = gen . with_timeout ( timeout , fut , quiet_except...
def StrSuffixOf ( suffix , input_string ) : """Return True if the concrete value of the input _ string ends with suffix otherwise false . : param suffix : suffix we want to check : param input _ string : the string we want to check : return : True if the input _ string ends with suffix else false"""
return re . match ( r'.*' + suffix . value + '$' , input_string . value ) is not None
def read_input ( self , input_cls , filename , ** kwargs ) : """Read in input and do some minimal preformatting input _ cls - the class to use to read the input filename - input filename"""
input_inst = input_cls ( ) input_inst . read_input ( filename ) return input_inst . get_data ( )
def fast_pop ( self , key = NOT_SET , index = NOT_SET ) : """Pop a specific item quickly by swapping it to the end . Remove value with given key or index ( last item by default ) fast by swapping it to the last place first . Changes order of the remaining items ( item that used to be last goes to the popped...
if index is NOT_SET and key is not NOT_SET : index , popped_value = self . _dict . pop ( key ) elif key is NOT_SET : if index is NOT_SET : index = len ( self . _list ) - 1 key , popped_value2 = self . _list [ - 1 ] else : key , popped_value2 = self . _list [ index ] if index ...
def cancel_signature_request ( self , signature_request_id ) : '''Cancels a SignatureRequest Cancels a SignatureRequest . After canceling , no one will be able to sign or access the SignatureRequest or its documents . Only the requester can cancel and only before everyone has signed . Args : signing _ req...
request = self . _get_request ( ) request . post ( url = self . SIGNATURE_REQUEST_CANCEL_URL + signature_request_id , get_json = False )
def custom_transfer ( transfer_client , source_ep , dest_ep , path_list , interval = DEFAULT_INTERVAL , inactivity_time = DEFAULT_INACTIVITY_TIME , notify = True ) : """Perform a Globus Transfer . Arguments : transfer _ client ( TransferClient ) : An authenticated Transfer client . source _ ep ( str ) : The s...
# TODO : ( LW ) Handle transfers with huge number of files # If a TransferData object is too large , Globus might timeout # before it can be completely uploaded . # So , we need to be able to check the size of the TD object and , if need be , send it early . if interval < 1 : interval = 1 deadline = datetime . utcf...
def set_stop_chars ( self , stop_chars ) : """Set stop characters used when determining end of URL . . . deprecated : : 0.7 Use : func : ` set _ stop _ chars _ left ` or : func : ` set _ stop _ chars _ right ` instead . : param list stop _ chars : list of characters"""
warnings . warn ( "Method set_stop_chars is deprecated, " "use `set_stop_chars_left` or " "`set_stop_chars_right` instead" , DeprecationWarning ) self . _stop_chars = set ( stop_chars ) self . _stop_chars_left = self . _stop_chars self . _stop_chars_right = self . _stop_chars
def webconfiguration_settings ( name , location = '' , settings = None ) : r'''Set the value of webconfiguration settings . : param str name : The name of the IIS PSPath containing the settings . Possible PSPaths are : MACHINE , MACHINE / WEBROOT , IIS : \ , IIS : \ Sites \ sitename , . . . : param str loca...
ret = { 'name' : name , 'changes' : { } , 'comment' : str ( ) , 'result' : None } if not settings : ret [ 'comment' ] = 'No settings to change provided.' ret [ 'result' ] = True return ret ret_settings = { 'changes' : { } , 'failures' : { } , } settings_list = list ( ) for filter , filter_settings in settin...
def autoconf ( self ) : """Implements Munin Plugin Auto - Configuration Option . @ return : True if plugin can be auto - configured , False otherwise ."""
fs = FSinfo ( self . _fshost , self . _fsport , self . _fspass ) return fs is not None
def file_md5 ( self , file_name ) : """Compute MD5 hash of file ."""
file_contents = self . _read_file ( file_name ) file_contents = file_contents + "\n" # Cisco IOS automatically adds this file_contents = file_contents . encode ( "UTF-8" ) return hashlib . md5 ( file_contents ) . hexdigest ( )
def handler ( self , path = '/app' , mode = 'debug' ) : """Handler that executes the application build based on its platform ( using the ` ` project ` ` package ) . param : path ( str ) : the project source code path , default is ' / app ' . param : target ( str ) : the platform target , android - 23 is the def...
options = { 'path' : path } project = builds . from_path ( path ) project . prepare ( ) project . validate ( ) project . build ( mode = mode )
def removeFile ( file ) : """remove a file"""
if "y" in speech . question ( "Are you sure you want to remove " + file + "? (Y/N): " ) : speech . speak ( "Removing " + file + " with the 'rm' command." ) subprocess . call ( [ "rm" , "-r" , file ] ) else : speech . speak ( "Okay, I won't remove " + file + "." )
def fit ( self , X , y = None ) : """X : ANTsImage | string | list of ANTsImage types | list of strings images to register to fixed image y : string | list of strings labels for images"""
moving_images = X if isinstance ( X , ( list , tuple ) ) else [ X ] moving_labels = y if y is not None else [ i for i in range ( len ( moving_images ) ) ] fixed_image = self . fixed_image self . fwdtransforms_ = { } self . invtransforms_ = { } self . warpedmovout_ = { } self . warpedfixout_ = { } for moving_image , mov...
def validate ( self ) : """Validate the current file against the SLD schema . This first normalizes the SLD document , then validates it . Any schema validation error messages are logged at the INFO level . @ rtype : boolean @ return : A flag indicating if the SLD is valid ."""
self . normalize ( ) if self . _node is None : logging . debug ( 'The node is empty, and cannot be validated.' ) return False if self . _schema is None : self . _schema = XMLSchema ( self . _schemadoc ) is_valid = self . _schema . validate ( self . _node ) for msg in self . _schema . error_log : logging...
def median ( data , freq_col = 1 ) : """Compute the median of the < freq _ col > ' th column of the values is < data > . > > > chart _ data . median ( [ ( 10,20 ) , ( 20,4 ) , ( 30,5 ) ] , 0) 20 > > > chart _ data . median ( [ ( 10,20 ) , ( 20,4 ) , ( 30,5 ) ] , 1)"""
nr_data = _nr_data ( data , freq_col ) median_idx = nr_data / 2 i = 0 for d in data : i += d [ freq_col ] if i >= median_idx : return d raise Exception ( "??? median ???" )
def content_language ( self ) -> Optional [ UnstructuredHeader ] : """The ` ` Content - Language ` ` header ."""
try : return cast ( UnstructuredHeader , self [ b'content-language' ] [ 0 ] ) except ( KeyError , IndexError ) : return None
def debit ( self , amount , credit_account , description , debit_memo = "" , credit_memo = "" , datetime = None ) : """Post a debit of ' amount ' and a credit of - amount against this account and credit _ account respectively . note amount must be non - negative ."""
assert amount >= 0 return self . post ( amount , credit_account , description , self_memo = debit_memo , other_memo = credit_memo , datetime = datetime )
def api_run_delete ( run_id ) : """Delete the given run and corresponding entities ."""
data = current_app . config [ "data" ] # type : DataStorage RunFacade ( data ) . delete_run ( run_id ) return "DELETED run %s" % run_id
def create_iteration ( self , num_suggestions ) : """Create an iteration for the experiment group ( works for grid and random ) ."""
from db . models . experiment_groups import ExperimentGroupIteration iteration_config = BaseIterationConfig ( iteration = 0 , num_suggestions = num_suggestions , experiment_ids = [ ] ) return ExperimentGroupIteration . objects . create ( experiment_group = self . experiment_group , data = iteration_config . to_dict ( )...
def _create_buffer ( self ) : """Create the ` Buffer ` for the Python input ."""
python_buffer = Buffer ( name = DEFAULT_BUFFER , complete_while_typing = Condition ( lambda : self . complete_while_typing ) , enable_history_search = Condition ( lambda : self . enable_history_search ) , tempfile_suffix = '.py' , history = self . history , completer = ThreadedCompleter ( self . _completer ) , validato...
def create ( self , password , username , realm = None ) : """Creates a storage password . A ` StoragePassword ` can be identified by < username > , or by < realm > : < username > if the optional realm parameter is also provided . : param password : The password for the credentials - this is the only part of ...
if not isinstance ( username , basestring ) : raise ValueError ( "Invalid name: %s" % repr ( username ) ) if realm is None : response = self . post ( password = password , name = username ) else : response = self . post ( password = password , realm = realm , name = username ) if response . status != 201 : ...
def simple_auc ( spectrum , f_ppm , center = 3.00 , bandwidth = 0.30 ) : """Calculates area under the curve ( no fitting ) Parameters spectrum : array of shape ( n _ transients , n _ points ) Typically the difference of the on / off spectra in each transient . center , bandwidth : float Determine the limi...
range = np . max ( f_ppm ) - np . min ( f_ppm ) dx = float ( range ) / float ( len ( f_ppm ) ) lb = np . floor ( ( np . max ( f_ppm ) - float ( center ) + float ( bandwidth ) / 2 ) / dx ) ub = np . ceil ( ( np . max ( f_ppm ) - float ( center ) - float ( bandwidth ) / 2 ) / dx ) auc = trapz ( spectrum [ ub : lb ] . rea...
def _init ( self , clnt ) : '''initialize api by YunpianClient'''
assert clnt , "clnt is None" self . _clnt = clnt self . _apikey = clnt . apikey ( ) self . _version = clnt . conf ( YP_VERSION , defval = VERSION_V2 ) self . _charset = clnt . conf ( HTTP_CHARSET , defval = CHARSET_UTF8 ) self . _name = self . __class__ . __module__ . split ( '.' ) [ - 1 ]
def cookiejar_from_dict ( cookie_dict ) : """Returns a CookieJar from a key / value dictionary . : param cookie _ dict : Dict of key / values to insert into CookieJar ."""
# return cookiejar if one was passed in if isinstance ( cookie_dict , cookielib . CookieJar ) : return cookie_dict # create cookiejar cj = cookielib . CookieJar ( ) cj = add_dict_to_cookiejar ( cj , cookie_dict ) return cj
def _format_filter ( filters , and_props = [ ] ) : """Transform filters to a comprehensive WQL ` WHERE ` clause . Builds filter from a filter list . - filters : expects a list of dicts , typically : - [ { ' Property ' : value } , . . . ] or - [ { ' Property ' : ( comparison _ op , value ) } , . . . ] NOTE...
def build_where_clause ( fltr ) : f = fltr . pop ( ) wql = "" while f : prop , value = f . popitem ( ) if isinstance ( value , tuple ) : oper = value [ 0 ] value = value [ 1 ] elif isinstance ( value , string_types ) and '%' in value : oper = 'LIKE...
def get_avatar ( from_header , size = 64 , default = "retro" ) : """Get the avatar URL from the email ' s From header . Args : from _ header ( str ) : The email ' s From header . May contain the sender ' s full name . Returns : str : The URL to that sender ' s avatar ."""
params = OrderedDict ( [ ( "s" , size ) , ( "d" , default ) ] ) query = parse . urlencode ( params ) address = email . utils . parseaddr ( from_header ) [ 1 ] value_hash = sha256 ( address . encode ( "utf-8" ) ) . hexdigest ( ) return "https://seccdn.libravatar.org/avatar/{}?{}" . format ( value_hash , query )
def values ( self ) : """: return : key - value dict : { string : any }"""
return dict ( ( k , getattr ( self , k ) ) for k in self . _keys )
def ParseObjs ( self , objs , type_names ) : """Parse one or more objects by testing if it is a known RDF class ."""
for obj in objs : for type_name in self . _RDFTypes ( type_names ) : if isinstance ( obj , self . _GetClass ( type_name ) ) : yield obj
def fw_soaring_data_encode ( self , timestamp , timestampModeChanged , xW , xR , xLat , xLon , VarW , VarR , VarLat , VarLon , LoiterRadius , LoiterDirection , DistToSoarPoint , vSinkExp , z1_LocalUpdraftSpeed , z2_DeltaRoll , z1_exp , z2_exp , ThermalGSNorth , ThermalGSEast , TSE_dot , DebugVar1 , DebugVar2 , ControlM...
return MAVLink_fw_soaring_data_message ( timestamp , timestampModeChanged , xW , xR , xLat , xLon , VarW , VarR , VarLat , VarLon , LoiterRadius , LoiterDirection , DistToSoarPoint , vSinkExp , z1_LocalUpdraftSpeed , z2_DeltaRoll , z1_exp , z2_exp , ThermalGSNorth , ThermalGSEast , TSE_dot , DebugVar1 , DebugVar2 , Con...
def forward ( self , device_port , local_port = None ) : '''adb port forward . return local _ port'''
if local_port is None : for s , lp , rp in self . forward_list ( ) : if s == self . device_serial ( ) and rp == 'tcp:%d' % device_port : return int ( lp [ 4 : ] ) return self . forward ( device_port , next_local_port ( self . server_host ) ) else : self . cmd ( "forward" , "tcp:%d" % loc...
def as_widget ( self , widget = None , attrs = None , only_initial = False ) : """Renders the field ."""
attrs = attrs or { } attrs . update ( self . form . get_widget_attrs ( self ) ) if hasattr ( self . field , 'widget_css_classes' ) : css_classes = self . field . widget_css_classes else : css_classes = getattr ( self . form , 'widget_css_classes' , None ) if css_classes : attrs . update ( { 'class' : css_cl...
def gaussian_bags_of_words ( Y , vocab = vocab1k , sigma = 1 , bag_size = [ 25 , 50 ] , ** kwargs ) : """Generate Gaussian bags of words based on label assignments Args : Y : np . array of true labels sigma : ( float ) the standard deviation of the Gaussian distributions bag _ size : ( list ) the min and ma...
def make_distribution ( sigma , num_words ) : p = abs ( np . random . normal ( 0 , sigma , num_words ) ) return p / sum ( p ) num_words = len ( vocab ) word_dists = { y : make_distribution ( sigma , num_words ) for y in set ( Y ) } bag_sizes = np . random . choice ( range ( min ( bag_size ) , max ( bag_size ) )...
def movie ( args ) : """% prog movie test . tour test . clm ref . contigs . last Plot optimization history ."""
p = OptionParser ( movie . __doc__ ) p . add_option ( "--frames" , default = 500 , type = "int" , help = "Only plot every N frames" ) p . add_option ( "--engine" , default = "ffmpeg" , choices = ( "ffmpeg" , "gifsicle" ) , help = "Movie engine, output MP4 or GIF" ) p . set_beds ( ) opts , args , iopts = p . set_image_o...
def ensure_unicode ( str_or_unicode ) : """tests , if the input is ` ` str ` ` or ` ` unicode ` ` . if it is ` ` str ` ` , it will be decoded from ` ` UTF - 8 ` ` to unicode ."""
if isinstance ( str_or_unicode , str ) : return str_or_unicode . decode ( 'utf-8' ) elif isinstance ( str_or_unicode , unicode ) : return str_or_unicode else : raise ValueError ( "Input '{0}' should be a string or unicode, " "but its of type {1}" . format ( str_or_unicode , type ( str_or_unicode ) ) )
def compute_voltages ( grid , configs_raw , potentials_raw ) : """Given a list of potential distribution and corresponding four - point spreads , compute the voltages Parameters grid : crt _ grid object the grid is used to infer electrode positions configs _ raw : Nx4 array containing the measurement co...
# we operate on 0 - indexed arrays , config holds 1 - indexed values # configs = configs _ raw - 1 voltages = [ ] for config , potentials in zip ( configs_raw , potentials_raw ) : print ( 'config' , config ) e3_node = grid . get_electrode_node ( config [ 2 ] ) e4_node = grid . get_electrode_node ( config [ ...
def rev_reg_id ( cd_id : str , tag : Union [ str , int ] ) -> str : """Given a credential definition identifier and a tag , return the corresponding revocation registry identifier , repeating the issuer DID from the input identifier . : param cd _ id : credential definition identifier : param tag : tag to u...
return '{}:4:{}:CL_ACCUM:{}' . format ( cd_id . split ( ":" , 1 ) [ 0 ] , cd_id , tag )
def process_tables ( key , value , fmt , meta ) : """Processes the attributed tables ."""
global has_unnumbered_tables # pylint : disable = global - statement # Process block - level Table elements if key == 'Table' : # Inspect the table if len ( value ) == 5 : # Unattributed , bail out has_unnumbered_tables = True if fmt in [ 'latex' ] : return [ RawBlock ( 'tex' , r'\begin{...