signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def handle_format ( self , t , i ) : """Handle format ."""
if t == '{' : t = self . format_next ( i ) if t == '{' : self . get_single_stack ( ) self . result . append ( t ) else : field , text = self . get_format ( t , i ) self . handle_format_group ( field , text ) else : t = self . format_next ( i ) if t == '}' : se...
def get_repository_lookup_session ( self , proxy , * args , ** kwargs ) : """Gets the repository lookup session . arg proxy ( osid . proxy . Proxy ) : a proxy return : ( osid . repository . RepositoryLookupSession ) - a RepositoryLookupSession raise : OperationFailed - unable to complete request raise : U...
if not self . supports_repository_lookup ( ) : raise Unimplemented ( ) try : from . import sessions except ImportError : raise # OperationFailed ( ) proxy = self . _convert_proxy ( proxy ) try : session = sessions . RepositoryLookupSession ( proxy , runtime = self . _runtime , ** kwargs ) except Att...
def start_supporting_containers ( self , log_syslog = False ) : """Start all supporting containers ( containers required for CKAN to operate ) if they aren ' t already running . : param log _ syslog : A flag to redirect all container logs to host ' s syslog"""
log_syslog = True if self . always_prod else log_syslog # in production we always use log _ syslog driver ( to aggregate all the logs ) task . start_supporting_containers ( self . sitedir , self . target , self . passwords , self . _get_container_name , self . extra_containers , log_syslog = log_syslog )
def complete_event ( self , event_id : str ) : """Complete the specified event ."""
event_ids = DB . get_list ( self . _processed_key ) if event_id not in event_ids : raise KeyError ( 'Unable to complete event. Event {} has not been ' 'processed (ie. it is not in the processed ' 'list).' . format ( event_id ) ) DB . remove_from_list ( self . _processed_key , event_id , pipeline = True ) key = _key...
def _drop_definition ( self ) : """Remove header definition associated with this section ."""
rId = self . _sectPr . remove_headerReference ( self . _hdrftr_index ) self . _document_part . drop_header_part ( rId )
def _digits ( self ) : """0-9"""
self . number += self . key try : if self . compact is False : self . top . body . focus_position = self . items . index ( self . items_com [ max ( int ( self . number ) - 1 , 0 ) ] ) else : self . top . body . focus_position = self . items . index ( self . items [ max ( int ( self . number ) - ...
def insert_entity ( self , entity ) : '''Adds an insert entity operation to the batch . See : func : ` ~ azure . storage . table . tableservice . TableService . insert _ entity ` for more information on inserts . The operation will not be executed until the batch is committed . : param entity : The entity...
request = _insert_entity ( entity ) self . _add_to_batch ( entity [ 'PartitionKey' ] , entity [ 'RowKey' ] , request )
def run ( configobj ) : """Primary Python interface for image registration code This task replaces ' tweakshifts '"""
print ( 'TweakReg Version %s(%s) started at: %s \n' % ( __version__ , __version_date__ , util . _ptime ( ) [ 0 ] ) ) util . print_pkg_versions ( ) # make sure ' updatewcs ' is set to False when running from GUI or if missing # from configObj : if 'updatewcs' not in configobj : configobj [ 'updatewcs' ] = False # Ch...
def to_credentials ( arg ) : '''to _ credentials ( arg ) converts arg into a pair ( key , secret ) if arg can be coerced into such a pair and otherwise raises an error . Possible inputs include : * A tuple ( key , secret ) * A mapping with the keys ' key ' and ' secret ' * The name of a file that can load...
if pimms . is_str ( arg ) : try : return load_credentials ( arg ) except Exception : pass try : return str_to_credentials ( arg ) except Exception : raise ValueError ( 'String "%s" is neither a file containing credentials nor a valid' ' credentials string itself.' % arg )...
def read ( url , encoding = None , cache = None , mode = "rb" ) : """Read from any URL . Internally differentiates between URLs supported by tf . gfile , such as URLs with the Google Cloud Storage scheme ( ' gs : / / . . . ' ) or local paths , and HTTP URLs . This way users don ' t need to know about the unde...
with read_handle ( url , cache , mode = mode ) as handle : data = handle . read ( ) if encoding : data = data . decode ( encoding ) return data
def _addToHosts ( self , node , destinationIP = None ) : """Add an " privateIP hostname " line to the / etc / hosts file . If destinationIP is given , do this on the remote machine . Azure VMs sometimes fail to initialize , causing the appliance to fail . This error is given : Failed to obtain the IP addres...
cmd = "echo %s %s | sudo tee --append /etc/hosts > /dev/null" % ( node . privateIP , node . name ) logger . debug ( "Running command %s on %s" % ( cmd , destinationIP ) ) if destinationIP : subprocess . Popen ( [ "ssh" , "-oStrictHostKeyChecking=no" , "core@%s" % destinationIP , cmd ] ) else : subprocess . Pope...
def set_stable_spot_instance_settings ( self , maximum_bid_price_percentage = None , timeout_for_request = None , allow_fallback = True ) : """Purchase options for stable spot instances . ` maximum _ bid _ price _ percentage ` : Maximum value to bid for stable node spot instances , expressed as a percentage of ...
self . hadoop_settings [ 'stable_spot_instance_settings' ] = { 'maximum_bid_price_percentage' : maximum_bid_price_percentage , 'timeout_for_request' : timeout_for_request , 'allow_fallback' : allow_fallback }
def flatten_union ( table ) : """Extract all union queries from ` table ` . Parameters table : TableExpr Returns Iterable [ Union [ TableExpr , bool ] ]"""
op = table . op ( ) if isinstance ( op , ops . Union ) : return toolz . concatv ( flatten_union ( op . left ) , [ op . distinct ] , flatten_union ( op . right ) ) return [ table ]
def epochs ( ts , variability = None , threshold = 0.0 , minlength = 1.0 , plot = True ) : """Identify " stationary " epochs within a time series , based on a continuous measure of variability . Epochs are defined to contain the points of minimal variability , and to extend as wide as possible with variabilit...
if variability is None : variability = ts . variability_fp ( plot = False ) orig_ndim = ts . ndim if ts . ndim is 1 : ts = ts [ : , np . newaxis ] if variability . ndim is 1 : variability = variability [ : , np . newaxis , np . newaxis ] elif variability . ndim is 2 : variability = variability [ : , np ...
def step ( self , action ) : """Pass action to underlying environment ( s ) or perform special action ."""
# Special codes if action in self . _player_actions ( ) : envs_step_tuples = self . _player_actions ( ) [ action ] ( ) elif self . _wait and action == self . name_to_action_num [ "NOOP" ] : # Ignore no - op , do not pass to environment . envs_step_tuples = self . _last_step_tuples else : # Run action on environ...
def read_config ( self ) : """Reads the configuration . This method can be overloaded to integrate with your application ' s own configuration mechanism . By default , a single ' status ' file is read from the reports ' directory . This should set ` self . status ` to one of the state constants , and make ...
if self . enabled and not os . path . isdir ( self . location ) : try : os . makedirs ( self . location , 0o700 ) except OSError : logger . warning ( "Couldn't create %s, usage statistics won't be " "collected" , self . location ) self . status = Stats . ERRORED status_file = os . path ....
def value ( self ) : """returns the wkid id for use in json calls"""
if self . _wkid == None and self . _wkt is not None : return { "wkt" : self . _wkt } else : return { "wkid" : self . _wkid }
def parse ( url ) : """Parses a database URL in this format : [ database type ] : / / [ username ] : [ password ] @ [ host ] : [ port ] / [ database name ] or , for cloud SQL : [ database type ] : / / [ username ] : [ password ] @ [ project _ id ] : [ instance _ name ] / [ database name ]"""
config = { } url = urlparse . urlparse ( url ) # Remove query strings . path = url . path [ 1 : ] path = path . split ( '?' , 2 ) [ 0 ] try : port = url . port hostname = url . hostname except ValueError : port = None if url . scheme == 'rdbms' : # local appengine stub requires INSTANCE parameter ...
def _configure_root_logger ( self ) : """Initialise logging system"""
root_logger = logging . getLogger ( ) root_logger . setLevel ( logging . DEBUG ) if self . args . verbose : handler = logging . StreamHandler ( sys . stdout ) else : handler = logging . handlers . RotatingFileHandler ( common . LOG_FILE , maxBytes = common . MAX_LOG_SIZE , backupCount = common . MAX_LOG_COUNT )...
def is_list_of_list_of_states ( self , arg ) : """A list of list of states example - [ [ ( ' x1 ' , ' easy ' ) , ( ' x2 ' , ' hard ' ) ] , [ ( ' x1 ' , ' hard ' ) , ( ' x2 ' , ' medium ' ) ] ] Returns True , if arg is a list of list of states else False ."""
if arg is None : return False return all ( [ isinstance ( arg , list ) , all ( isinstance ( i , list ) for i in arg ) , all ( ( isinstance ( i , tuple ) for i in lst ) for lst in arg ) ] )
def get_primary_keys ( conn , table : str , schema = 'public' ) : """Returns primary key columns for a specific table ."""
query = """\ SELECT c.constraint_name AS pkey_constraint_name, c.column_name AS column_name FROM information_schema.key_column_usage AS c JOIN information_schema.table_constraints AS t ON t.constraint_name = c.constraint_name AND t.table_catalog = c.table_catalog AND t.table_schema = c.tab...
def execute ( self , timeSeries ) : """Creates a new TimeSeries containing the smoothed values . : return : TimeSeries object containing the smoothed TimeSeries , including the forecasted values . : rtype : TimeSeries : note : The first normalized value is chosen as the starting point ."""
# determine the number of values to forecast , if necessary self . _calculate_values_to_forecast ( timeSeries ) # extract the required parameters , performance improvement alpha = self . _parameters [ "smoothingFactor" ] beta = self . _parameters [ "trendSmoothingFactor" ] # initialize some variables resultList = [ ] e...
def to_smart_columns ( data , headers = None , padding = 2 ) : """Nicely format the 2 - dimensional list into columns"""
result = '' col_widths = [ ] for row in data : col_counter = 0 for word in row : try : col_widths [ col_counter ] = max ( len ( word ) , col_widths [ col_counter ] ) except IndexError : col_widths . append ( len ( word ) ) col_counter += 1 if headers : col_cou...
def run_ppm_server ( pdb_file , outfile , force_rerun = False ) : """Run the PPM server from OPM to predict transmembrane residues . Args : pdb _ file ( str ) : Path to PDB file outfile ( str ) : Path to output HTML results file force _ rerun ( bool ) : Flag to rerun PPM if HTML results file already exists ...
if ssbio . utils . force_rerun ( outfile = outfile , flag = force_rerun ) : url = 'http://sunshine.phar.umich.edu/upload_file.php' files = { 'userfile' : open ( pdb_file , 'rb' ) } r = requests . post ( url , files = files ) info = r . text # Save results in raw HTML format with open ( outfile ,...
def get_assessment_taken_form_for_create ( self , assessment_offered_id , assessment_taken_record_types ) : """Gets the assessment taken form for creating new assessments taken . A new form should be requested for each create transaction . arg : assessment _ offered _ id ( osid . id . Id ) : the ` ` Id ` ` of t...
if not isinstance ( assessment_offered_id , ABCId ) : raise errors . InvalidArgument ( 'argument is not a valid OSID Id' ) for arg in assessment_taken_record_types : if not isinstance ( arg , ABCType ) : raise errors . InvalidArgument ( 'one or more argument array elements is not a valid OSID Type' ) am...
def __get_git_bin ( ) : """Get git binary location . : return : Check git location"""
git = 'git' alternatives = [ '/usr/bin/git' ] for alt in alternatives : if os . path . exists ( alt ) : git = alt break return git
def merge ( args ) : """% prog merge map1 map2 map3 . . . Convert csv maps to bed format . Each input map is csv formatted , for example : ScaffoldID , ScaffoldPosition , LinkageGroup , GeneticPosition scaffold _ 2707,11508,1,0 scaffold _ 2707,11525,1,1.2 scaffold _ 759,81336,1,9.7"""
p = OptionParser ( merge . __doc__ ) p . add_option ( "-w" , "--weightsfile" , default = "weights.txt" , help = "Write weights to file" ) p . set_outfile ( "out.bed" ) opts , args = p . parse_args ( args ) if len ( args ) < 1 : sys . exit ( not p . print_help ( ) ) maps = args outfile = opts . outfile fp = must_ope...
def parse_connection_string ( connect_str ) : """Parse a connection string such as those provided by the Azure portal . Connection string should be formatted like : ` Key = Value ; Key = Value ; Key = Value ` . The connection string will be parsed into a dictionary . : param connect _ str : The connection str...
connect_info = { } fields = connect_str . split ( ';' ) for field in fields : key , value = field . split ( '=' , 1 ) connect_info [ key ] = value return connect_info
def create_variable_with_length ( self ) : """Append code for creating variable with length of that variable ( for example length of list or dictionary ) with name ` ` { variable } _ len ` ` . It can be called several times and always it ' s done only when that variable still does not exists ."""
variable_name = '{}_len' . format ( self . _variable ) if variable_name in self . _variables : return self . _variables . add ( variable_name ) self . l ( '{variable}_len = len({variable})' )
def color_grid ( data , palette , denom = 9.0 , mask_zeros = True ) : """Convert the given data ( 2d array of numbers or binary strings ) to a 2d array of RGB or RGBA values which can then be visualized as a heat map . Arguments : data - 2d array of numbers or binary strings palette - a seaborn palette ( li...
grid = [ ] try : # If this isn ' t numeric , don ' t bother with this block float ( data [ 0 ] [ 0 ] ) # This is continuous data - we need a colormap rather than palette palette = matplotlib . colors . LinearSegmentedColormap . from_list ( "color_grid" , palette ) palette . set_bad ( alpha = 0 ) except ...
def send_messages ( self , messages ) : """Send one or more EmailMessage objects . Returns : int : Number of email messages sent ."""
if not messages : return new_conn_created = self . open ( ) if not self . connection : # We failed silently on open ( ) . Trying to send would be pointless . return num_sent = 0 for message in messages : sent = self . _send ( message ) if sent : num_sent += 1 if new_conn_created : self . clo...
def register ( name = EopDb . DEFAULT_DBNAME ) : """Decorator for registering an Eop Database Example : . . code - block : : python @ register class SqliteEnvDatabase : # sqlite implementation # this database will be known as ' default ' @ register ( ' json ' ) class JsonEnvDatabase : # JSON imple...
# I had a little trouble setting this function up , due to the fact that # I wanted it to be usable both as a simple decorator ( ` ` @ register ` ` ) # and a decorator with arguments ( ` ` @ register ( ' mydatabase ' ) ` ` ) . # The current implementation allows this dual - use , but it ' s a bit hacky . # In the simpl...
def send ( signal = Any , sender = Anonymous , * arguments , ** named ) : """Send signal from sender to all connected receivers . signal - - ( hashable ) signal value , see connect for details sender - - the sender of the signal if Any , only receivers registered for Any will receive the message . if Anon...
# Call each receiver with whatever arguments it can accept . # Return a list of tuple pairs [ ( receiver , response ) , . . . ] . responses = [ ] for receiver in liveReceivers ( getAllReceivers ( sender , signal ) ) : response = robustapply . robustApply ( receiver , signal = signal , sender = sender , * arguments ...
def find_optconf ( self , pconfs ) : """Find the optimal Parallel configuration ."""
# Save pconfs for future reference . self . set_pconfs ( pconfs ) # Select the partition on which we ' ll be running and set MPI / OMP cores . optconf = self . manager . select_qadapter ( pconfs ) return optconf
def _dataset_load_from_hdx ( self , id_or_name ) : # type : ( str ) - > bool """Loads the dataset given by either id or name from HDX Args : id _ or _ name ( str ) : Either id or name of dataset Returns : bool : True if loaded , False if not"""
if not self . _load_from_hdx ( 'dataset' , id_or_name ) : return False self . _dataset_create_resources ( ) return True
def _obj_index ( self , uri , base_path , marked_path , headers , spr = False ) : """Return an index of objects from within the container . : param uri : : param base _ path : : param marked _ path : : param headers : : param spr : " single page return " Limit the returned data to one page : type spr : ...
object_list = list ( ) l_obj = None container_uri = uri . geturl ( ) while True : marked_uri = urlparse . urljoin ( container_uri , marked_path ) resp = self . http . get ( url = marked_uri , headers = headers ) self . _resp_exception ( resp = resp ) return_list = resp . json ( ) if spr : re...
def should_run ( keywords , post_processor ) : """Check if the postprocessor should run for the current hazard and exposure : param keywords : impact layer keywords : type keywords : dict : param post _ processor : the post processor instance to check : type post _ processor : dict : returns : Tuple with ...
exposure = keywords [ 'exposure_keywords' ] [ 'exposure' ] hazard = keywords [ 'hazard_keywords' ] [ 'hazard' ] try : run_filter = post_processor [ 'run_filter' ] except KeyError : # if no run _ filter is defined we run the postprocessor return True , None msg = tr ( 'Postprocessor "{name}" did not run because ...
def _batch_gvcfs ( data , region , vrn_files , ref_file , out_file = None ) : """Perform batching of gVCF files if above recommended input count ."""
if out_file is None : out_file = vrn_files [ 0 ] # group to get below the maximum batch size , using 200 as the baseline max_batch = int ( dd . get_joint_group_size ( data ) ) if len ( vrn_files ) > max_batch : out = [ ] num_batches = int ( math . ceil ( float ( len ( vrn_files ) ) / max_batch ) ) for i...
def mergeWindows ( data , dimOrder , maxWindowSize , overlapPercent , batchSize , transform , progressCallback = None ) : """Generates sliding windows for the specified dataset and applies the specified transformation function to each window . Where multiple overlapping windows include an element of the input d...
# Determine the dimensions of the input data sourceWidth = data . shape [ dimOrder . index ( 'w' ) ] sourceHeight = data . shape [ dimOrder . index ( 'h' ) ] # Generate the sliding windows and group them into batches windows = generate ( data , dimOrder , maxWindowSize , overlapPercent ) batches = batchWindows ( window...
def display_initialize ( self ) : """Display ' please wait ' message , and narrow build warning ."""
echo ( self . term . home + self . term . clear ) echo ( self . term . move_y ( self . term . height // 2 ) ) echo ( self . term . center ( 'Initializing page data ...' ) . rstrip ( ) ) flushout ( ) if LIMIT_UCS == 0x10000 : echo ( '\n\n' ) echo ( self . term . blink_red ( self . term . center ( 'narrow Python ...
def set_matrix ( self , matrix ) : """Modifies the current transformation matrix ( CTM ) by setting it equal to : obj : ` matrix ` . : param matrix : A transformation : class : ` Matrix ` from user space to device space ."""
cairo . cairo_set_matrix ( self . _pointer , matrix . _pointer ) self . _check_status ( )
def create_with_validation ( raw_properties ) : """Creates new ' PropertySet ' instances after checking that all properties are valid and converting implicit properties into gristed form ."""
assert is_iterable_typed ( raw_properties , basestring ) properties = [ property . create_from_string ( s ) for s in raw_properties ] property . validate ( properties ) return create ( properties )
def _load_neighbors_from_external_source ( self ) -> None : """Loads the neighbors of the node from the igraph ` Graph ` instance that is wrapped by the graph that has this node ."""
graph : SpotifyArtistGraph = self . _graph items : List [ NameExternalIDPair ] = graph . client . similar_artists ( self . external_id ) limit : int = graph . neighbor_count if graph . neighbor_count > 0 else self . _NEIGHBORS_TO_LOAD if len ( items ) > limit : del items [ limit : ] for item in items : neighbor...
def list_permissions ( vhost , runas = None ) : '''Lists permissions for vhost via rabbitmqctl list _ permissions CLI Example : . . code - block : : bash salt ' * ' rabbitmq . list _ permissions / myvhost'''
if runas is None and not salt . utils . platform . is_windows ( ) : runas = salt . utils . user . get_user ( ) res = __salt__ [ 'cmd.run_all' ] ( [ RABBITMQCTL , 'list_permissions' , '-q' , '-p' , vhost ] , reset_system_locale = False , runas = runas , python_shell = False ) return _output_to_dict ( res )
def create_session_config ( log_device_placement = False , enable_graph_rewriter = False , gpu_mem_fraction = 0.95 , use_tpu = False , xla_jit_level = tf . OptimizerOptions . OFF , inter_op_parallelism_threads = 0 , intra_op_parallelism_threads = 0 ) : """The TensorFlow Session config to use ."""
if use_tpu : graph_options = tf . GraphOptions ( ) else : if enable_graph_rewriter : rewrite_options = rewriter_config_pb2 . RewriterConfig ( ) rewrite_options . layout_optimizer = rewriter_config_pb2 . RewriterConfig . ON graph_options = tf . GraphOptions ( rewrite_options = rewrite_opt...
def _integrate_storage ( self , timeseries , position , params , voltage_level , reactive_power_timeseries , ** kwargs ) : """Integrate storage units in the grid . Parameters timeseries : : obj : ` str ` or : pandas : ` pandas . Series < series > ` Parameter used to obtain time series of active power the stor...
# place storage params = self . _check_nominal_power ( params , timeseries ) if isinstance ( position , Station ) or isinstance ( position , BranchTee ) or isinstance ( position , Generator ) or isinstance ( position , Load ) : storage = storage_integration . set_up_storage ( node = position , parameters = params ,...
def neighborSelect ( a , x , y ) : """finds ( local ) minima in a 2d grid : param a : 1d array of displacements from the source positions : type a : numpy array with length numPix * * 2 in float : returns : array of indices of local minima , values of those minima : raises : AttributeError , KeyError"""
dim = int ( np . sqrt ( len ( a ) ) ) values = [ ] x_mins = [ ] y_mins = [ ] for i in range ( dim + 1 , len ( a ) - dim - 1 ) : if ( a [ i ] < a [ i - 1 ] and a [ i ] < a [ i + 1 ] and a [ i ] < a [ i - dim ] and a [ i ] < a [ i + dim ] and a [ i ] < a [ i - ( dim - 1 ) ] and a [ i ] < a [ i - ( dim + 1 ) ] and a [...
def render_tooltip ( self , tooltip , obj ) : """Render the tooltip for this column for an object"""
if self . tooltip_attr : val = getattr ( obj , self . tooltip_attr ) elif self . tooltip_value : val = self . tooltip_value else : return False setter = getattr ( tooltip , TOOLTIP_SETTERS . get ( self . tooltip_type ) ) if self . tooltip_type in TOOLTIP_SIZED_TYPES : setter ( val , self . tooltip_image...
def DeregisterCredentials ( cls , credentials ) : """Deregisters a path specification credentials . Args : credentials ( Credentials ) : credentials . Raises : KeyError : if credential object is not set for the corresponding type indicator ."""
if credentials . type_indicator not in cls . _credentials : raise KeyError ( 'Credential object not set for type indicator: {0:s}.' . format ( credentials . type_indicator ) ) del cls . _credentials [ credentials . type_indicator ]
def start_agent ( self , cfgin = True ) : """CLI interface to start 12 - factor service"""
default_conf = { "threads" : { "result" : { "number" : 0 , "function" : None } , "worker" : { "number" : 0 , "function" : None } , } , "interval" : { "refresh" : 900 , "heartbeat" : 300 , "reporting" : 300 , "test" : 60 } , "heartbeat-hook" : False } indata = { } if cfgin : indata = json . load ( sys . stdin ) elif...
def connect ( self ) : """| coro | Connect to ubisoft , automatically called when needed"""
if time . time ( ) < self . _login_cooldown : raise FailedToConnect ( "login on cooldown" ) resp = yield from self . session . post ( "https://connect.ubi.com/ubiservices/v2/profiles/sessions" , headers = { "Content-Type" : "application/json" , "Ubi-AppId" : self . appid , "Authorization" : "Basic " + self . token ...
def policy_list ( request , ** kwargs ) : """List of QoS Policies ."""
policies = neutronclient ( request ) . list_qos_policies ( ** kwargs ) . get ( 'policies' ) return [ QoSPolicy ( p ) for p in policies ]
def firstElementChild ( self ) -> Optional [ AbstractNode ] : """First Element child node . If this node has no element child , return None ."""
for child in self . childNodes : if child . nodeType == Node . ELEMENT_NODE : return child return None
def get_user ( self , username = "~" ) : """get info about user ( if no user specified , use the one initiating request ) : param username : str , name of user to get info about , default = " ~ " : return : dict"""
url = self . _build_url ( "users/%s/" % username , _prepend_namespace = False ) response = self . _get ( url ) check_response ( response ) return response
def get_students ( self ) : """Get user objects that are students ( quickly ) ."""
users = User . objects . filter ( user_type = "student" , graduation_year__gte = settings . SENIOR_GRADUATION_YEAR ) users = users . exclude ( id__in = EXTRA ) return users
def get_domain ( value ) : """domain = dot - atom / domain - literal / obs - domain obs - domain = atom * ( " . " atom ) )"""
domain = Domain ( ) leader = None if value [ 0 ] in CFWS_LEADER : leader , value = get_cfws ( value ) if not value : raise errors . HeaderParseError ( "expected domain but found '{}'" . format ( value ) ) if value [ 0 ] == '[' : token , value = get_domain_literal ( value ) if leader is not None : ...
def optimized_binary_search_lower ( tab , logsize ) : """Binary search in a table using bit operations : param tab : boolean monotone table of size : math : ` 2 ^ \\ textrm { logsize } ` with tab [ 0 ] = False : param int logsize : : returns : last i such that not tab [ i ] : complexity : O ( logsize )"...
lo = 0 intervalsize = ( 1 << logsize ) >> 1 while intervalsize > 0 : if not tab [ lo | intervalsize ] : lo |= intervalsize intervalsize >>= 1 return lo
def get_versions_from_webpage ( self ) : """Get version details from Zenodo webpage ( it is not available in the REST api )"""
res = requests . get ( 'https://zenodo.org/record/' + self . data [ 'conceptrecid' ] ) soup = BeautifulSoup ( res . text , 'html.parser' ) version_rows = soup . select ( '.well.metadata > table.table tr' ) if len ( version_rows ) == 0 : # when only 1 version return [ { 'recid' : self . data [ 'id' ] , 'name' : '1' ...
def get_probes_config ( self ) : """Return the configuration of the RPM probes ."""
probes = { } probes_table = junos_views . junos_rpm_probes_config_table ( self . device ) probes_table . get ( ) probes_table_items = probes_table . items ( ) for probe_test in probes_table_items : test_name = py23_compat . text_type ( probe_test [ 0 ] ) test_details = { p [ 0 ] : p [ 1 ] for p in probe_test [ ...
def get ( self , request , * args , ** kwargs ) : """Return a : class : ` . django . http . JsonResponse ` . Example : : ' results ' : [ ' text ' : " foo " , ' id ' : 123 ' more ' : true"""
self . widget = self . get_widget_or_404 ( ) self . term = kwargs . get ( 'term' , request . GET . get ( 'term' , '' ) ) self . object_list = self . get_queryset ( ) context = self . get_context_data ( ) return JsonResponse ( { 'results' : [ { 'text' : self . widget . label_from_instance ( obj ) , 'id' : obj . pk , } f...
def _add_edge ( self , s_a , s_b , ** edge_labels ) : """Add an edge in the graph from ` s _ a ` to statement ` s _ b ` , where ` s _ a ` and ` s _ b ` are tuples of statements of the form ( irsb _ addr , stmt _ idx ) ."""
# Is that edge already in the graph ? # If at least one is new , then we are not redoing the same path again if ( s_a , s_b ) not in self . graph . edges ( ) : self . graph . add_edge ( s_a , s_b , ** edge_labels ) self . _new = True l . info ( "New edge: %s --> %s" , s_a , s_b )
def team_status ( self , team , event ) : """Get status of a team at an event . : param team : Team whose status to get . : param event : Event team is at . : return : Status object ."""
return Status ( self . _get ( 'team/%s/event/%s/status' % ( self . team_key ( team ) , event ) ) )
def long_description ( * filenames ) : """Provide a long description ."""
res = [ '' ] for filename in filenames : with open ( filename ) as fp : for line in fp : res . append ( ' ' + line ) res . append ( '' ) res . append ( '\n' ) return EMPTYSTRING . join ( res )
def delete_user ( name , runas = None ) : '''Deletes a user via rabbitmqctl delete _ user . CLI Example : . . code - block : : bash salt ' * ' rabbitmq . delete _ user rabbit _ user'''
if runas is None and not salt . utils . platform . is_windows ( ) : runas = salt . utils . user . get_user ( ) res = __salt__ [ 'cmd.run_all' ] ( [ RABBITMQCTL , 'delete_user' , name ] , reset_system_locale = False , python_shell = False , runas = runas ) msg = 'Deleted' return _format_response ( res , msg )
def get_environ ( self , sock ) : """Create WSGI environ entries to be merged into each request ."""
cipher = sock . cipher ( ) ssl_environ = { "wsgi.url_scheme" : "https" , "HTTPS" : "on" , 'SSL_PROTOCOL' : cipher [ 1 ] , 'SSL_CIPHER' : cipher [ 0 ] # # SSL _ VERSION _ INTERFACE string The mod _ ssl program version # # SSL _ VERSION _ LIBRARY string The OpenSSL program version } return ssl_environ
def release_branches ( self ) : """A dictionary that maps branch names to : class : ` Release ` objects ."""
self . ensure_release_scheme ( 'branches' ) return dict ( ( r . revision . branch , r ) for r in self . releases . values ( ) )
def value_type ( self ) : """The attribute ' s type , note that this is the type of the attribute ' s value and not its affect on the item ( i . e . negative or positive ) . See ' type ' for that ."""
redundantprefix = "value_is_" vtype = self . _attribute . get ( "description_format" ) if vtype and vtype . startswith ( redundantprefix ) : return vtype [ len ( redundantprefix ) : ] else : return vtype
def get_all_for_resource ( identifier , configuration = None ) : # type : ( str , Optional [ Configuration ] ) - > List [ ' ResourceView ' ] """Read all resource views for a resource given by identifier from HDX and returns list of ResourceView objects Args : identifier ( str ) : Identifier of resource config...
resourceview = ResourceView ( configuration = configuration ) success , result = resourceview . _read_from_hdx ( 'resource view' , identifier , 'id' , ResourceView . actions ( ) [ 'list' ] ) resourceviews = list ( ) if success : for resourceviewdict in result : resourceview = ResourceView ( resourceviewdict...
def filter_to_pass_and_reject ( in_file , paired , out_dir = None ) : """Filter VCF to only those with a strict PASS / REJECT : somatic + germline . Removes low quality calls filtered but also labeled with REJECT ."""
from bcbio . heterogeneity import bubbletree out_file = "%s-prfilter.vcf.gz" % utils . splitext_plus ( in_file ) [ 0 ] if out_dir : out_file = os . path . join ( out_dir , os . path . basename ( out_file ) ) if not utils . file_uptodate ( out_file , in_file ) : with file_transaction ( paired . tumor_data , out_...
def update ( xCqNck7t , ** kwargs ) : """Updates the Dict with the given values . Turns internal dicts into Dicts ."""
def dict_list_val ( inlist ) : l = [ ] for i in inlist : if type ( i ) == dict : l . append ( Dict ( ** i ) ) elif type ( i ) == list : l . append ( make_list ( i ) ) elif type ( i ) == bytes : l . append ( i . decode ( 'UTF-8' ) ) else : ...
def transform ( self , func ) : """Apply a transformation to tokens in this : class : ` . FeatureSet ` \ . Parameters func : callable Should take four parameters : token , value in document ( e . g . count ) , value in : class : ` . FeatureSet ` ( e . g . overall count ) , and document count ( i . e . num...
features = { } for i , feature in self . features . iteritems ( ) : feature_ = [ ] for f , v in feature : t = self . lookup [ f ] v_ = func ( f , v , self . counts [ t ] , self . documentCounts [ t ] ) if v_ : feature_ . append ( ( f , v_ ) ) features [ i ] = Feature ( fe...
def configure ( self , src_dir , build_dir , ** kwargs ) : """This function builds the cmake configure command ."""
del kwargs ex_path = self . _ex_args . get ( "project_path" ) if ex_path : src_dir = os . path . join ( src_dir , ex_path ) return [ { "args" : [ "cmake" , src_dir ] + self . _config_args , "cwd" : build_dir } ]
def main ( show_details : [ '-l' ] = False , cols : [ '-w' , '--width' ] = '' , * files ) : '''List information about a particular file or set of files : param show _ details : Whether to show detailed info about files : param cols : specify screen width'''
print ( files ) print ( show_details ) print ( cols )
def forum_post_list ( self , creator_id = None , creator_name = None , topic_id = None , topic_title_matches = None , topic_category_id = None , body_matches = None ) : """Return a list of forum posts . Parameters : creator _ id ( int ) : creator _ name ( str ) : topic _ id ( int ) : topic _ title _ match...
params = { 'search[creator_id]' : creator_id , 'search[creator_name]' : creator_name , 'search[topic_id]' : topic_id , 'search[topic_title_matches]' : topic_title_matches , 'search[topic_category_id]' : topic_category_id , 'search[body_matches]' : body_matches } return self . _get ( 'forum_posts.json' , params )
def colorize ( lead , num , color ) : """Print ' lead ' = ' num ' in ' color '"""
if num != 0 and ANSIBLE_COLOR and color is not None : return "%s%s%-15s" % ( stringc ( lead , color ) , stringc ( "=" , color ) , stringc ( str ( num ) , color ) ) else : return "%s=%-4s" % ( lead , str ( num ) )
def to_map_with_default ( value , default_value ) : """Converts value into map object or returns default when conversion is not possible : param value : the value to convert . : param default _ value : the default value . : return : map object or emptu map when conversion is not supported ."""
result = MapConverter . to_nullable_map ( value ) return result if result != None else default_value
def parse_date ( self , value ) : """A lazy method to parse anything to date . If input data type is : - string : parse date from it - integer : use from ordinal - datetime : use date part - date : just return it"""
if value is None : raise Exception ( "Unable to parse date from %r" % value ) elif isinstance ( value , string_types ) : return self . str2date ( value ) elif isinstance ( value , int ) : return date . fromordinal ( value ) elif isinstance ( value , datetime ) : return value . date ( ) elif isinstance (...
def u_distance_stats_sqr ( x , y , ** kwargs ) : """u _ distance _ stats _ sqr ( x , y , * , exponent = 1) Computes the unbiased estimators for the squared distance covariance and squared distance correlation between two random vectors , and the individual squared distance variances . Parameters x : array...
if _can_use_fast_algorithm ( x , y , ** kwargs ) : return _u_distance_stats_sqr_fast ( x , y ) else : return _distance_sqr_stats_naive_generic ( x , y , matrix_centered = _u_distance_matrix , product = u_product , ** kwargs )
def get_request_token ( cls , consumer_key , redirect_uri = 'http://example.com/' , state = None ) : '''Returns the request token that can be used to fetch the access token'''
headers = { 'X-Accept' : 'application/json' , } url = 'https://getpocket.com/v3/oauth/request' payload = { 'consumer_key' : consumer_key , 'redirect_uri' : redirect_uri , } if state : payload [ 'state' ] = state return cls . _make_request ( url , payload , headers ) [ 0 ] [ 'code' ]
def optimal_orientation ( self , t_gps ) : """Return the optimal orientation in right ascension and declination for a given GPS time . Parameters t _ gps : float Time in gps seconds Returns ra : float Right ascension that is optimally oriented for the detector dec : float Declination that is optim...
ra = self . longitude + ( self . gmst_estimate ( t_gps ) % ( 2.0 * np . pi ) ) dec = self . latitude return ra , dec
def pywt_pad_mode ( pad_mode , pad_const = 0 ) : """Convert ODL - style padding mode to pywt - style padding mode . Parameters pad _ mode : str The ODL padding mode to use at the boundaries . pad _ const : float , optional Value to use outside the signal boundaries when ` ` pad _ mode ` ` is ' constant ...
pad_mode = str ( pad_mode ) . lower ( ) if pad_mode == 'constant' and pad_const != 0.0 : raise ValueError ( 'constant padding with constant != 0 not supported ' 'for `pywt` back-end' ) try : return PAD_MODES_ODL2PYWT [ pad_mode ] except KeyError : raise ValueError ( "`pad_mode` '{}' not understood" . format...
def get_tmp_filename ( tmp_dir = gettempdir ( ) , prefix = "tmp" , suffix = ".txt" , result_constructor = FilePath ) : """Generate a temporary filename and return as a FilePath object tmp _ dir : the directory to house the tmp _ filename prefix : string to append to beginning of filename Note : It is very use...
# check not none if not tmp_dir : tmp_dir = "" # if not current directory , append " / " if not already on path elif not tmp_dir . endswith ( "/" ) : tmp_dir += "/" chars = "abcdefghigklmnopqrstuvwxyz" picks = chars + chars . upper ( ) + "0123456790" return result_constructor ( tmp_dir ) + result_constructor ( ...
def get ( self , name ) : """Get the vrrp configurations for a single node interface Args : name ( string ) : The name of the interface for which vrrp configurations will be retrieved . Returns : A dictionary containing the vrrp configurations on the interface . Returns None if no vrrp configurations ar...
# Validate the interface and vrid are specified interface = name if not interface : raise ValueError ( "Vrrp.get(): interface must contain a value." ) # Get the config for the interface . Return None if the # interface is not defined config = self . get_block ( 'interface %s' % interface ) if config is None : r...
def force_disconnect ( self , session_id , connection_id ) : """Sends a request to disconnect a client from an OpenTok session : param String session _ id : The session ID of the OpenTok session from which the client will be disconnected : param String connection _ id : The connection ID of the client that wi...
endpoint = self . endpoints . force_disconnect_url ( session_id , connection_id ) response = requests . delete ( endpoint , headers = self . json_headers ( ) , proxies = self . proxies , timeout = self . timeout ) if response . status_code == 204 : pass elif response . status_code == 400 : raise ForceDisconnect...
def create_list_str ( help_string = NO_HELP , default = NO_DEFAULT ) : # type : ( str , Union [ List [ str ] , NO _ DEFAULT _ TYPE ] ) - > List [ str ] """Create a List [ str ] parameter : param help _ string : : param default : : return :"""
# noinspection PyTypeChecker return ParamFunctions ( help_string = help_string , default = default , type_name = "List[str]" , function_s2t = convert_string_to_list_str , function_t2s = convert_list_str_to_string , )
def get_any_node ( self , addr , is_syscall = None , anyaddr = False , force_fastpath = False ) : """Get an arbitrary CFGNode ( without considering their contexts ) from our graph . : param int addr : Address of the beginning of the basic block . Set anyaddr to True to support arbitrary address . : param bool...
# fastpath : directly look in the nodes list if not anyaddr : try : return self . _nodes_by_addr [ addr ] [ 0 ] except ( KeyError , IndexError ) : pass if force_fastpath : return None # slower path # if self . _ node _ lookup _ index is not None : # pass # the slowest path # try to show a wa...
def words ( query ) : """lines ( query ) - - print the number of words in a given file"""
filename = support . get_file_name ( query ) if ( os . path . isfile ( filename ) ) : with open ( filename ) as openfile : print len ( openfile . read ( ) . split ( ) ) else : print 'File not found : ' + filename
def get_family_hierarchy_design_session ( self , proxy = None ) : """Gets the ` ` OsidSession ` ` associated with the family hierarchy design service . arg : proxy ( osid . proxy . Proxy ) : a proxy return : ( osid . relationship . FamilyHierarchyDesignSession ) - a ` ` HierarchyDesignSession ` ` for families...
if not self . supports_family_hierarchy_design ( ) : raise Unimplemented ( ) try : from . import sessions except ImportError : raise OperationFailed ( ) proxy = self . _convert_proxy ( proxy ) try : session = sessions . FamilyHierarchyDesignSession ( proxy = proxy , runtime = self . _runtime ) except At...
def _parse_engine ( engine ) : """Parse the engine uri to determine where to store loggs"""
engine = ( engine or '' ) . strip ( ) backend , path = URI_RE . match ( engine ) . groups ( ) if backend not in SUPPORTED_BACKENDS : raise NotImplementedError ( "Logg supports only {0} for now." . format ( SUPPORTED_BACKENDS ) ) log . debug ( 'Found engine: {0}' . format ( engine ) ) return backend , path
def split_parameter_types ( parameters ) : """Split a parameter types declaration into individual types . The input is the left hand side of a signature ( the part before the arrow ) , excluding the parentheses . : sig : ( str ) - > List [ str ] : param parameters : Comma separated parameter types . : ret...
if parameters == "" : return [ ] # only consider the top level commas , ignore the ones in [ ] commas = [ ] bracket_depth = 0 for i , char in enumerate ( parameters ) : if ( char == "," ) and ( bracket_depth == 0 ) : commas . append ( i ) elif char == "[" : bracket_depth += 1 elif char =...
def start_child_span ( operation_name , tracer = None , parent = None , tags = None ) : """Start a new span as a child of parent _ span . If parent _ span is None , start a new root span . : param operation _ name : operation name : param tracer : Tracer or None ( defaults to opentracing . tracer ) : param ...
tracer = tracer or opentracing . tracer return tracer . start_span ( operation_name = operation_name , child_of = parent . context if parent else None , tags = tags )
def wiki_request ( self , params ) : """Make a request to the MediaWiki API using the given search parameters Args : params ( dict ) : Request parameters Returns : A parsed dict of the JSON response Note : Useful when wanting to query the MediaWiki site for some value that is not part of the wrapper A...
params [ "format" ] = "json" if "action" not in params : params [ "action" ] = "query" limit = self . _rate_limit last_call = self . _rate_limit_last_call if limit and last_call and last_call + self . _min_wait > datetime . now ( ) : # call time to quick for rate limited api requests , wait wait_time = ( last_c...
def output_file ( self , _container ) : """Find and writes the output path of a chroot container ."""
p = local . path ( _container ) if p . exists ( ) : if not ui . ask ( "Path '{0}' already exists." " Overwrite?" . format ( p ) ) : sys . exit ( 0 ) CFG [ "container" ] [ "output" ] = str ( p )
def _ValidateFSM ( self ) : """Checks state names and destinations for validity . Each destination state must exist , be a valid name and not be a reserved name . There must be a ' Start ' state and if ' EOF ' or ' End ' states are specified , they must be empty . Returns : True if FSM is valid . Rais...
# Must have ' Start ' state . if 'Start' not in self . states : raise TextFSMTemplateError ( "Missing state 'Start'." ) # ' End / EOF ' state ( if specified ) must be empty . if self . states . get ( 'End' ) : raise TextFSMTemplateError ( "Non-Empty 'End' state." ) if self . states . get ( 'EOF' ) : raise T...
def _netstat_linux ( ) : '''Return netstat information for Linux distros'''
ret = [ ] cmd = 'netstat -tulpnea' out = __salt__ [ 'cmd.run' ] ( cmd ) for line in out . splitlines ( ) : comps = line . split ( ) if line . startswith ( 'tcp' ) : ret . append ( { 'proto' : comps [ 0 ] , 'recv-q' : comps [ 1 ] , 'send-q' : comps [ 2 ] , 'local-address' : comps [ 3 ] , 'remote-address'...
def __gen_node_href ( self , layer , node_id ) : """generates a complete xlink : href for any node ( token node , structure node etc . ) in the docgraph . This will only work AFTER the corresponding PAULA files have been created ( and their file names are registered in ` ` self . paulamap ` ` ) ."""
if istoken ( self . dg , node_id ) : base_paula_id = self . paulamap [ 'tokenization' ] else : base_paula_id = self . paulamap [ 'hierarchy' ] [ layer ] return '{0}.xml#{1}' . format ( base_paula_id , node_id )
def validate ( ) : """Display error messages and exit if no lore environment can be found ."""
if not os . path . exists ( os . path . join ( ROOT , APP , '__init__.py' ) ) : message = ansi . error ( ) + ' Python module not found.' if os . environ . get ( 'LORE_APP' ) is None : message += ' $LORE_APP is not set. Should it be different than "%s"?' % APP else : message += ' $LORE_APP is...
def get_set ( self , project , articleset , ** filters ) : """List the articlesets in a project"""
url = URL . articleset . format ( ** locals ( ) ) return self . request ( url , ** filters )
async def getNodeByNdef ( self , ndef ) : '''Return a single Node by ( form , valu ) tuple . Args : ndef ( ( str , obj ) ) : A ( form , valu ) ndef tuple . valu must be normalized . Returns : ( synapse . lib . node . Node ) : The Node or None .'''
buid = s_common . buid ( ndef ) return await self . getNodeByBuid ( buid )
def _load_profile ( self , profile_name ) : """Load a profile by name Called by load _ user _ options"""
# find the profile default_profile = self . _profile_list [ 0 ] for profile in self . _profile_list : if profile . get ( 'default' , False ) : # explicit default , not the first default_profile = profile if profile [ 'display_name' ] == profile_name : break else : if profile_name : # name sp...