signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def vararg_decorator ( f ) : '''Decorator to handle variable argument decorators .'''
@ wraps ( f ) def decorator ( * args , ** kwargs ) : if len ( args ) == 1 and len ( kwargs ) == 0 and callable ( args [ 0 ] ) : return f ( args [ 0 ] ) else : return lambda realf : f ( realf , * args , ** kwargs ) return decorator
def wait_for_compute_zone_operation ( compute , project_name , operation , zone ) : """Poll for compute zone operation until finished ."""
logger . info ( "wait_for_compute_zone_operation: " "Waiting for operation {} to finish..." . format ( operation [ "name" ] ) ) for _ in range ( MAX_POLLS ) : result = compute . zoneOperations ( ) . get ( project = project_name , operation = operation [ "name" ] , zone = zone ) . execute ( ) if "error" in resul...
def create_reader ( self , name , * args , ** kwargs ) : """Create a new reader instance for a given format ."""
self . _check_format ( name ) return self . _formats [ name ] [ 'reader' ] ( * args , ** kwargs )
def process ( self , candidates ) : """: arg list candidates : list of Candidates : returns : list of Candidates where score is at least min _ score , if and only if one or more Candidates have at least min _ score . Otherwise , returns original list of Candidates ."""
high_score_candidates = [ c for c in candidates if c . score >= self . min_score ] if high_score_candidates != [ ] : return high_score_candidates return candidates
def emailComment ( comment , obj , request ) : """Send an email to the author about a new comment"""
if not obj . author . frog_prefs . get ( ) . json ( ) [ 'emailComments' ] : return if obj . author == request . user : return html = render_to_string ( 'frog/comment_email.html' , { 'user' : comment . user , 'comment' : comment . comment , 'object' : obj , 'action_type' : 'commented on' , 'image' : isinstance (...
def _onPrevBookmark ( self ) : """Previous Bookmark action triggered . Move cursor"""
for block in qutepart . iterateBlocksBackFrom ( self . _qpart . textCursor ( ) . block ( ) . previous ( ) ) : if self . isBlockMarked ( block ) : self . _qpart . setTextCursor ( QTextCursor ( block ) ) return
def transformer_moe_2k ( ) : """Base transformers model with moe . Will have the following architecture : * No encoder . * Layer 0 : a - sep ( self - attention - unmasked separable convolutions ) * Layer 1 : a - sep * Layer 2 : a - sep * Layer 3 : a - sep * Layer 4 : a - sep * Decoder architecture :...
hparams = transformer_moe_8k ( ) hparams . batch_size = 2048 hparams . default_ff = "sep" # hparams . layer _ types contains the network architecture : encoder_archi = "a/a/a/a/a" decoder_archi = "a-sepm/a-sepm/a-moe/a-sepm/a-sepm" hparams . layer_types = "{}#{}" . format ( encoder_archi , decoder_archi ) return hparam...
def headers ( self ) : '''An instance of : class : ` HeaderDict ` , a case - insensitive dict - like view on the response headers .'''
self . __dict__ [ 'headers' ] = hdict = HeaderDict ( ) hdict . dict = self . _headers return hdict
def _set_TC1 ( self , v , load = False ) : """Setter method for TC1 , mapped from YANG variable / policy _ map / class / scheduler / strict _ priority / TC1 ( shaping - rate - limit ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ TC1 is considered as a private metho...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = RestrictedClassType ( base_type = RestrictedClassType ( base_type = long , restriction_dict = { 'range' : [ '0..18446744073709551615' ] } , int_size = 64 ) , restriction_dict = { 'range' : [ u'28000 .. 100000000' ] } ) , is_l...
def send_message ( self , number , content ) : """Send message : param str number : phone number with cc ( country code ) : param str content : body text of the message"""
outgoing_message = TextMessageProtocolEntity ( content . encode ( "utf-8" ) if sys . version_info >= ( 3 , 0 ) else content , to = self . normalize_jid ( number ) ) self . toLower ( outgoing_message ) return outgoing_message
def _memoizeArgsOnly ( max_cache_size = 1000 ) : """Python 2.4 compatible memoize decorator . It creates a cache that has a maximum size . If the cache exceeds the max , it is thrown out and a new one made . With such behavior , it is wise to set the cache just a little larger that the maximum expected need ....
def wrapper ( f ) : def fn ( * args ) : try : return fn . cache [ args ] except KeyError : if fn . count >= max_cache_size : fn . cache = { } fn . count = 0 fn . cache [ args ] = result = f ( * args ) fn . count += 1 ...
def Henry_H_at_T ( T , H , Tderiv , T0 = None , units = None , backend = None ) : """Evaluate Henry ' s constant H at temperature T Parameters T : float Temperature ( with units ) , assumed to be in Kelvin if ` ` units = = None ` ` H : float Henry ' s constant Tderiv : float ( optional ) dln ( H ) / d...
be = get_backend ( backend ) if units is None : K = 1 else : K = units . Kelvin if T0 is None : T0 = 298.15 * K return H * be . exp ( Tderiv * ( 1 / T - 1 / T0 ) )
async def wait_change ( self ) : """Wait for the list to change ."""
future = asyncio . Future ( loop = self . loop ) self . _change_futures . add ( future ) future . add_done_callback ( self . _change_futures . discard ) await future
def _GenDiscoveryDoc ( service_class_names , output_path , hostname = None , application_path = None ) : """Write discovery documents generated from the service classes to file . Args : service _ class _ names : A list of fully qualified ProtoRPC service names . output _ path : The directory to output the dis...
output_files = [ ] service_configs = GenApiConfig ( service_class_names , hostname = hostname , config_string_generator = discovery_generator . DiscoveryGenerator ( ) , application_path = application_path ) for api_name_version , config in service_configs . iteritems ( ) : discovery_name = api_name_version + '.disc...
def build_spotify_api ( ) : """Build the Spotify API for future use"""
data = datatools . get_data ( ) if "spotify_client_id" not in data [ "discord" ] [ "keys" ] : logger . warning ( "No API key found with name 'spotify_client_id'" ) logger . info ( "Please add your Spotify client id with name 'spotify_client_id' " "in data.json to use Spotify features of the music module" ) ...
def configure_host_cache ( host_ref , datastore_ref , swap_size_MiB , host_cache_manager = None ) : '''Configures the host cahe of the specified host host _ ref The vim . HostSystem object representing the host that contains the requested disks . datastore _ ref The vim . Datastore opject representing the...
hostname = get_managed_object_name ( host_ref ) if not host_cache_manager : props = get_properties_of_managed_object ( host_ref , [ 'configManager.cacheConfigurationManager' ] ) if not props . get ( 'configManager.cacheConfigurationManager' ) : raise salt . exceptions . VMwareObjectRetrievalError ( 'Hos...
def check_background_commands_complete ( self ) : """Check whether any background commands are running or to be run . If none are , return True . If any are , return False ."""
unstarted_command_exists = False self . shutit_obj . log ( 'In check_background_commands_complete: all background objects: ' + str ( self . background_objects ) , level = logging . DEBUG ) self . shutit_obj . log ( 'Login id: ' + str ( self . login_id ) , level = logging . DEBUG ) for background_object in self . backgr...
def get_arca_base ( self , pull = True ) : """Returns the name and tag of image that has the basic build dependencies installed with just pyenv installed , with no python installed . ( Builds or pulls the image if it doesn ' t exist locally . )"""
name = self . get_arca_base_name ( ) tag = arca . __version__ pyenv_installer = "https://raw.githubusercontent.com/pyenv/pyenv-installer/master/bin/pyenv-installer" dockerfile = f""" FROM debian:stretch-slim RUN apt-get update && \ apt-get install -y make build-essential libssl-d...
def _compute_integral_x ( self ) : """Computes the integral of x , \\ int _ V x , over all atomic " triangles " , i . e . , areas cornered by a node , an edge midpoint , and a circumcenter ."""
# The integral of any linear function over a triangle is the average of # the values of the function in each of the three corners , times the # area of the triangle . right_triangle_vols = self . cell_partitions node_edges = self . idx_hierarchy corner = self . node_coords [ node_edges ] edge_midpoints = 0.5 * ( corner...
def iter_blocks ( block_list ) : """A generator for blocks contained in a block list . Yields tuples containing the block name , the depth that the block was found at , and finally a handle to the block itself ."""
# queue the block and the depth of the block queue = [ ( block , 0 ) for block in block_list if isinstance ( block , kurt . Block ) ] while queue : block , depth = queue . pop ( 0 ) assert block . type . text yield block . type . text , depth , block for arg in block . args : if hasattr ( arg , ...
def _list_records_internal ( self , rtype = None , name = None , content = None , identifier = None ) : """Filter and list DNS entries of domain zone on Easyname . Easyname shows each entry in a HTML table row and each attribute on a table column . Args : [ rtype ] ( str ) : Filter by DNS rtype ( e . g . A ...
name = self . _full_name ( name ) if name is not None else name if self . _records is None : records = [ ] rows = self . _get_dns_entry_trs ( ) for index , row in enumerate ( rows ) : self . _log ( 'DNS list entry' , row ) try : rec = { } if row . has_attr ( 'ondblcli...
def do_create ( self , params ) : """\x1b [1mNAME \x1b [0m create - Creates a znode \x1b [1mSYNOPSIS \x1b [0m create < path > < value > [ ephemeral ] [ sequence ] [ recursive ] [ async ] \x1b [1mOPTIONS \x1b [0m * ephemeral : make the znode ephemeral ( default : false ) * sequence : make the znode seque...
try : kwargs = { "acl" : None , "ephemeral" : params . ephemeral , "sequence" : params . sequence } if not self . in_transaction : kwargs [ "makepath" ] = params . recursive if params . asynchronous and not self . in_transaction : self . client_context . create_async ( params . path , decode...
def cli ( env , group_id , name , description ) : """Edit details of a security group ."""
mgr = SoftLayer . NetworkManager ( env . client ) data = { } if name : data [ 'name' ] = name if description : data [ 'description' ] = description if not mgr . edit_securitygroup ( group_id , ** data ) : raise exceptions . CLIAbort ( "Failed to edit security group" )
def parsesamplesheet ( self ) : """Parses the sample sheet ( SampleSheet . csv ) to determine certain values important for the creation of the assembly report"""
# Open the sample sheet with open ( self . samplesheet , "r" ) as samplesheet : # Iterate through the sample sheet samples , prev , header = False , 0 , [ ] for count , line in enumerate ( samplesheet ) : # Remove new lines , and split on commas # line = line . decode ( ' utf - 8 ' ) # Turn from bytes to st...
def get_transform_matrix ( from_frame , to_frame ) : """Compose sequential matrix transformations ( static or dynamic ) to get a single transformation matrix from a given path through the Astropy transformation machinery . Parameters from _ frame : ` ~ astropy . coordinates . BaseCoordinateFrame ` subclass ...
path , distance = coord . frame_transform_graph . find_shortest_path ( from_frame , to_frame ) matrices = [ ] currsys = from_frame for p in path [ 1 : ] : # first element is fromsys so we skip it trans = coord . frame_transform_graph . _graph [ currsys ] [ p ] if isinstance ( trans , coord . DynamicMatrixTransf...
def convert ( self , imtls , nsites , idx = 0 ) : """Convert a probability map into a composite array of length ` nsites ` and dtype ` imtls . dt ` . : param imtls : DictArray instance : param nsites : the total number of sites : param idx : index on the z - axis ( default 0)"""
curves = numpy . zeros ( nsites , imtls . dt ) for imt in curves . dtype . names : curves_by_imt = curves [ imt ] for sid in self : curves_by_imt [ sid ] = self [ sid ] . array [ imtls ( imt ) , idx ] return curves
def is_dir ( path ) : """Determine if a Path or string is a directory on the file system ."""
try : return path . expanduser ( ) . absolute ( ) . is_dir ( ) except AttributeError : return os . path . isdir ( os . path . abspath ( os . path . expanduser ( str ( path ) ) ) )
def push_pq ( self , tokens ) : """Creates and Load object , populates it with data , finds its Bus and adds it ."""
logger . debug ( "Pushing PQ data: %s" % tokens ) bus = self . case . buses [ tokens [ "bus_no" ] - 1 ] bus . p_demand = tokens [ "p" ] bus . q_demand = tokens [ "q" ]
def get_first_response ( input_statement , response_list , storage = None ) : """: param input _ statement : A statement , that closely matches an input to the chat bot . : type input _ statement : Statement : param response _ list : A list of statement options to choose a response from . : type response _ li...
logger = logging . getLogger ( __name__ ) logger . info ( 'Selecting first response from list of {} options.' . format ( len ( response_list ) ) ) return response_list [ 0 ]
def _user ( self , user , real_name ) : """Sends the USER message . Required arguments : * user - Username to send . * real _ name - Real name to send ."""
with self . lock : self . send ( 'USER %s 0 * :%s' % ( user , real_name ) ) if self . readable ( ) : self . _recv ( ) self . stepback ( )
def deploy_token_contract ( self , token_supply : int , token_decimals : int , token_name : str , token_symbol : str , token_type : str = 'CustomToken' , ) : """Deploy a token contract ."""
receipt = self . deploy ( contract_name = token_type , args = [ token_supply , token_decimals , token_name , token_symbol ] , ) token_address = receipt [ 'contractAddress' ] assert token_address and is_address ( token_address ) token_address = to_checksum_address ( token_address ) return { token_type : token_address }
def get ( self , entity , id = None , sub_entity = None , offset = 0 , limit = 20 , search_terms = None , sync = True ) : """Get all entities that fufill the given filtering if provided . : todo : Rename search _ terms"""
url = urljoin ( self . host , entity . value + '/' ) url = urljoin ( url , id + '/' ) if id else url url = urljoin ( url , sub_entity . value + '/' ) if sub_entity else url terms = { 'sync' : str ( sync ) . lower ( ) } if search_terms : terms . update ( search_terms ) if not id : terms . update ( { 'limit' : li...
def main ( ) : """Run the workflow ."""
init_logging ( ) LOG . info ( "Starting imaging-pipeline" ) # Read parameters PARFILE = 'parameters.json' if len ( sys . argv ) > 1 : PARFILE = sys . argv [ 1 ] LOG . info ( "JSON parameter file = %s" , PARFILE ) try : with open ( PARFILE , "r" ) as par_file : jspar = json . load ( par_file ) except Ass...
def split ( activeList , decoyList , options ) : """Create training and validation sets"""
# set input variables training_fraction = options . training_fraction decoy_to_active = options . decoy_to_active # take care of default decoy _ to _ active ratio if decoy_to_active is None : decoy_to_active = len ( decoyList ) / len ( activeList ) # verify that there are enough molecules to satisfy the ratio if le...
def combine_ns_runs ( run_list_in , ** kwargs ) : """Combine a list of complete nested sampling run dictionaries into a single ns run . Input runs must contain any repeated threads . Parameters run _ list _ in : list of dicts List of nested sampling runs in dict format ( see data _ processing module doc...
run_list = copy . deepcopy ( run_list_in ) if len ( run_list ) == 1 : run = run_list [ 0 ] else : nthread_tot = 0 for i , _ in enumerate ( run_list ) : check_ns_run ( run_list [ i ] , ** kwargs ) run_list [ i ] [ 'thread_labels' ] += nthread_tot nthread_tot += run_list [ i ] [ 'threa...
def _validate_explicit_consumer_groups ( cls , val ) : """Validate any explicitly specified consumer groups . While the check does not require specifying consumer groups , if they are specified this method should be used to validate them . val = { ' consumer _ group ' : { ' topic ' : [ 0 , 1 ] } }"""
assert isinstance ( val , dict ) for consumer_group , topics in iteritems ( val ) : assert isinstance ( consumer_group , string_types ) # topics are optional assert isinstance ( topics , dict ) or topics is None if topics is not None : for topic , partitions in iteritems ( topics ) : ...
def assert_no_js_errors ( self ) : """Asserts that there are no JavaScript " SEVERE " - level page errors . Works ONLY for Chrome ( non - headless ) and Chrome - based browsers . Does NOT work on Firefox , Edge , IE , and some other browsers : * See https : / / github . com / SeleniumHQ / selenium / issues / ...
try : browser_logs = self . driver . get_log ( 'browser' ) except ( ValueError , WebDriverException ) : # If unable to get browser logs , skip the assert and return . return messenger_library = "//cdnjs.cloudflare.com/ajax/libs/messenger" errors = [ ] for entry in browser_logs : if entry [ 'level' ] == 'SEV...
def _widening_points ( self , function_address ) : """Return the ordered widening points for a specific function . : param int function _ address : Address of the querying function . : return : A list of sorted merge points ( addresses ) . : rtype : list"""
# we are entering a new function . now it ' s time to figure out how to optimally traverse the control flow # graph by generating the sorted merge points try : new_function = self . kb . functions [ function_address ] except KeyError : # the function does not exist return [ ] if function_address not in self . _...
def serialize ( self , account , group , region ) : """Serializes the JSON for the Polling Event Model . : param account : : param group : : param region : : return :"""
return self . dumps ( { 'account' : account , 'detail' : { 'request_parameters' : { 'groupId' : group [ 'GroupId' ] } , 'region' : region , 'collected' : group } } ) . data
def read_last_msg_from_queue ( q ) : """Read all messages from a queue and return the last one . This is useful in many cases where all messages are always the complete state of things . Therefore , intermittent messages can be ignored . Doesn ' t block , returns None if there is no message waiting in the que...
msg = None while True : try : # The list of IPs is always a full list . msg = q . get_nowait ( ) q . task_done ( ) except Queue . Empty : # No more messages , all done for now return msg
def write_krona_plot ( self , sample_names , read_taxonomies , output_krona_filename ) : '''Creates krona plot at the given location . Assumes the krona executable ktImportText is available on the shell PATH'''
tempfiles = [ ] for n in sample_names : tempfiles . append ( tempfile . NamedTemporaryFile ( prefix = 'GraftMkronaInput' , suffix = n ) ) delim = u'\t' for _ , tax , counts in self . _iterate_otu_table_rows ( read_taxonomies ) : for i , c in enumerate ( counts ) : if c != 0 : tempfiles [ i ]...
def _isbn_pairing ( items ) : """Pair ` items ` with same ISBN into ` DataPair ` objects . Args : items ( list ) : list of items , which will be searched . Returns : list : list with paired items . Paired items are removed , ` DataPair ` is added instead ."""
NameWrapper = namedtuple ( "NameWrapper" , [ "name" , "obj" ] ) metas = map ( lambda x : NameWrapper ( _just_name ( x . filename ) , x ) , filter ( lambda x : isinstance ( x , MetadataFile ) , items ) ) ebooks = map ( lambda x : NameWrapper ( _just_name ( x . filename ) , x ) , filter ( lambda x : isinstance ( x , Eboo...
def get_club_members ( self , club_id , limit = None ) : """Gets the member objects for specified club ID . http : / / strava . github . io / api / v3 / clubs / # get - members : param club _ id : The numeric ID for the club . : type club _ id : int : param limit : Maximum number of athletes to return . ( d...
result_fetcher = functools . partial ( self . protocol . get , '/clubs/{id}/members' , id = club_id ) return BatchedResultsIterator ( entity = model . Athlete , bind_client = self , result_fetcher = result_fetcher , limit = limit )
def get_order ( self ) : """Return a list of dicionaries . See ` set _ order ` ."""
return [ dict ( reverse = r [ 0 ] , key = r [ 1 ] ) for r in self . get_model ( ) ]
def exported_disks_paths ( self ) : """Returns : ( list of str ) : The path of the exported disks ."""
return [ os . path . join ( self . _dst , os . path . basename ( disk [ 'path' ] ) ) for disk in self . _collect ( ) ]
def get_balance ( self , address , api_token ) : """returns the balance in wei with some inspiration from PyWallet"""
broadcast_url = self . base_url + '?module=account&action=balance' broadcast_url += '&address=%s' % address broadcast_url += '&tag=latest' if api_token : '&apikey=%s' % api_token response = requests . get ( broadcast_url ) if int ( response . status_code ) == 200 : balance = int ( response . json ( ) . get ( 'r...
def get_endpoints_using_catalog_api ( domain , token ) : """Implements a raw HTTP GET against the entire Socrata portal for the domain in question . This method uses the second of the two ways of getting this information , the catalog API . Parameters domain : str A Socrata data portal domain . " data . sea...
# Token required for all requests . Providing login info instead is also possible but I didn ' t implement it . headers = { "X-App-Token" : token } # The API will return only 100 requests at a time by default . We can ask for more , but the server seems to start # to lag after a certain N requested . Instead , let ' s ...
def read_params_from_config ( cp , prior_section = 'prior' , vargs_section = 'variable_args' , sargs_section = 'static_args' ) : """Loads static and variable parameters from a configuration file . Parameters cp : WorkflowConfigParser An open config parser to read from . prior _ section : str , optional Ch...
# sanity check that each parameter in [ variable _ args ] has a priors section variable_args = cp . options ( vargs_section ) subsections = cp . get_subsections ( prior_section ) tags = set ( [ p for tag in subsections for p in tag . split ( '+' ) ] ) missing_prior = set ( variable_args ) - tags if any ( missing_prior ...
def get_url ( url_base , tenant_id , user , password , type , region ) : """It get the url for a concrete service : param url _ base : keystone url : param tenand _ id : the id of the tenant : param user : the user : param paassword : the password : param type : the type of service : param region : the ...
url = 'http://' + url_base + '/v2.0/tokens' headers = { 'Accept' : 'application/json' } payload = { 'auth' : { 'tenantName' : '' + tenant_id + '' , 'passwordCredentials' : { 'username' : '' + user + '' , 'password' : '' + password + '' } } } try : response = requests . post ( url , headers = headers , data = json ....
def checkIpDetails ( query = None ) : '''Method that checks if the given hash is stored in the md5crack . com website . An example of the json received : " as " : " AS8560 1 \u0026 1 Internet AG " , " city " : " " , " country " : " Germany " , " countryCode " : " DE " , " isp " : " 1 \u0026 1 Internet AG ...
try : apiURL = "http://ip-api.com/json/" + query # Accessing the ip - api . com RESTful API data = urllib2 . urlopen ( apiURL ) . read ( ) # Reading the text data onto python structures apiData = json . loads ( data ) # i3visio structure to be returned jsonData = [ ] if apiData [ "status...
def generate_nucmer_commands ( filenames , outdir = "." , nucmer_exe = pyani_config . NUCMER_DEFAULT , filter_exe = pyani_config . FILTER_DEFAULT , maxmatch = False , ) : """Return a tuple of lists of NUCmer command - lines for ANIm The first element is a list of NUCmer commands , the second a list of delta _ f...
nucmer_cmdlines , delta_filter_cmdlines = [ ] , [ ] for idx , fname1 in enumerate ( filenames [ : - 1 ] ) : for fname2 in filenames [ idx + 1 : ] : ncmd , dcmd = construct_nucmer_cmdline ( fname1 , fname2 , outdir , nucmer_exe , filter_exe , maxmatch ) nucmer_cmdlines . append ( ncmd ) delta...
def authentication_ok ( self ) : '''Checks the authentication and sets the username of the currently connected terminal . Returns True or False'''
username = None password = None if self . authCallback : if self . authNeedUser : username = self . readline ( prompt = self . PROMPT_USER , use_history = False ) if self . authNeedPass : password = self . readline ( echo = False , prompt = self . PROMPT_PASS , use_history = False ) if s...
def Run ( script , container = None , exit_on_error = False , gas = Fixed8 . Zero ( ) , test_mode = True ) : """Runs a script in a test invoke environment Args : script ( bytes ) : The script to run container ( neo . Core . TX . Transaction ) : [ optional ] the transaction to use as the script container Ret...
from neo . Core . Blockchain import Blockchain from neo . SmartContract . StateMachine import StateMachine from neo . EventHub import events bc = Blockchain . Default ( ) accounts = DBCollection ( bc . _db , DBPrefix . ST_Account , AccountState ) assets = DBCollection ( bc . _db , DBPrefix . ST_Asset , AssetState ) val...
def get_op_symbol ( obj , fmt = '%s' , symbol_data = symbol_data , type = type ) : """Given an AST node object , returns a string containing the symbol ."""
return fmt % symbol_data [ type ( obj ) ]
def _get_parallel_regions ( data ) : """Retrieve regions to run in parallel , putting longest intervals first ."""
callable_regions = tz . get_in ( [ "config" , "algorithm" , "callable_regions" ] , data ) if not callable_regions : raise ValueError ( "Did not find any callable regions for sample: %s\n" "Check 'align/%s/*-callableblocks.bed' and 'regions' to examine callable regions" % ( dd . get_sample_name ( data ) , dd . get_s...
def count ( self ) : """Returns the number of rows after aggregation ."""
sql = u'SELECT count() FROM (%s)' % self . as_sql ( ) raw = self . _database . raw ( sql ) return int ( raw ) if raw else 0
def anglez ( self , ** kwargs ) : # pragma : no cover """NAME : anglez PURPOSE : Calculate the vertical angle INPUT : + scipy . integrate . quad keywords OUTPUT : angle _ z ( z , vz ) * vc / ro + estimate of the error HISTORY : 2012-06-01 - Written - Bovy ( IAS )"""
if hasattr ( self , '_anglez' ) : return self . _anglez zmax = self . calczmax ( ) Ez = calcEz ( self . _z , self . _vz , self . _verticalpot ) Tz = self . Tz ( ** kwargs ) self . _anglez = 2. * nu . pi * ( nu . array ( integrate . quad ( _TzIntegrand , 0. , nu . fabs ( self . _z ) , args = ( Ez , self . _verticalp...
def send_string_clipboard ( self , string : str , paste_command : model . SendMode ) : """This method is called from the IoMediator for Phrase expansion using one of the clipboard method . : param string : The to - be pasted string : param paste _ command : Optional paste command . If None , the mouse selection...
logger . debug ( "Sending string via clipboard: " + string ) if common . USING_QT : if paste_command is None : self . __enqueue ( self . app . exec_in_main , self . _send_string_selection , string ) else : self . __enqueue ( self . app . exec_in_main , self . _send_string_clipboard , string , pa...
def _name_value ( self , s ) : """Parse a ( name , value ) tuple from ' name value - length value ' ."""
parts = s . split ( b' ' , 2 ) name = parts [ 0 ] if len ( parts ) == 1 : value = None else : size = int ( parts [ 1 ] ) value = parts [ 2 ] still_to_read = size - len ( value ) if still_to_read > 0 : read_bytes = self . read_bytes ( still_to_read ) value += b'\n' + read_bytes [ : st...
def unset_env ( self , key ) : """Removes an environment variable using the prepended app _ name convention with ` key ` ."""
os . environ . pop ( make_env_key ( self . appname , key ) , None ) self . _registered_env_keys . discard ( key ) self . _clear_memoization ( )
def temperatures ( self ) : """Return a generator with the details of each zone ."""
self . location . status ( ) if self . hotwater : yield { 'thermostat' : 'DOMESTIC_HOT_WATER' , 'id' : self . hotwater . dhwId , 'name' : '' , 'temp' : self . hotwater . temperatureStatus [ 'temperature' ] , # pylint : disable = no - member 'setpoint' : '' } for zone in self . _zones : zone_info = { 'thermo...
def copy_rect ( self , x0 , y0 , x1 , y1 , dx , dy , destination ) : """Copy ( blit ) a rectangle onto another part of the image"""
x0 , y0 , x1 , y1 = self . rect_helper ( x0 , y0 , x1 , y1 ) dx , dy = force_int ( dx , dy ) for x in range ( x0 , x1 + 1 ) : for y in range ( y0 , y1 + 1 ) : d = destination . _offset ( dx + x - x0 , dy + y - y0 ) o = self . _offset ( x , y ) destination . canvas [ d : d + 4 ] = self . canv...
def do_serial ( self , p ) : """Set the serial port , e . g . : / dev / tty . usbserial - A4001ib8"""
try : self . serial . port = p self . serial . open ( ) print 'Opening serial port: %s' % p except Exception , e : print 'Unable to open serial port: %s' % p
def render_services_ctrl ( self , request ) : """Example for rendering the service control panel row You can override the default template and create a custom one if you wish . : param request : : return :"""
urls = self . Urls ( ) urls . auth_activate = 'auth_example_activate' urls . auth_deactivate = 'auth_example_deactivate' urls . auth_reset_password = 'auth_example_reset_password' urls . auth_set_password = 'auth_example_set_password' return render_to_string ( self . service_ctrl_template , { 'service_name' : self . ti...
def data_offerings ( self , ctx , data ) : """Generate a list of installed offerings . @ return : a generator of dictionaries mapping ' name ' to the name of an offering installed on the store ."""
for io in self . original . store . query ( offering . InstalledOffering ) : pp = ixmantissa . IPublicPage ( io . application , None ) if pp is not None and getattr ( pp , 'index' , True ) : warn ( "Use the sharing system to provide public pages," " not IPublicPage" , category = DeprecationWarning , sta...
def list_ ( channel = None ) : '''List installed pecl extensions . CLI Example : . . code - block : : bash salt ' * ' pecl . list'''
pecl_channel_pat = re . compile ( '^([^ ]+)[ ]+([^ ]+)[ ]+([^ ]+)' ) pecls = { } command = 'list' if channel : command = '{0} -c {1}' . format ( command , _cmd_quote ( channel ) ) lines = _pecl ( command ) . splitlines ( ) lines = ( l for l in lines if pecl_channel_pat . match ( l ) ) for line in lines : match ...
def exec_request ( endpoint , func , raise_for_status = False , ** kwargs ) : """Send an https api request"""
try : endpoint = '{0}/api/v1/{1}' . format ( settings . SEAT_URL , endpoint ) headers = { 'X-Token' : settings . SEAT_XTOKEN , 'Accept' : 'application/json' } logger . debug ( headers ) logger . debug ( endpoint ) ret = getattr ( requests , func ) ( endpoint , headers = headers , data = kwargs ) ...
def _right ( self ) : """Index of column following the last column in range"""
left , _ , width , _ = self . _extents return left + width
def valid_id ( opts , id_ ) : '''Returns if the passed id is valid'''
try : if any ( x in id_ for x in ( '/' , '\\' , str ( '\0' ) ) ) : return False return bool ( clean_path ( opts [ 'pki_dir' ] , id_ ) ) except ( AttributeError , KeyError , TypeError , UnicodeDecodeError ) : return False
def _auto_combine ( datasets , concat_dims , compat , data_vars , coords , infer_order_from_coords , ids ) : """Calls logic to decide concatenation order before concatenating ."""
# Arrange datasets for concatenation if infer_order_from_coords : raise NotImplementedError # TODO Use coordinates to determine tile _ ID for each dataset in N - D # Ignore how they were ordered previously # Should look like : # combined _ ids , concat _ dims = _ infer _ tile _ ids _ from _ coords (...
def subgraph_centrality ( CIJ ) : '''The subgraph centrality of a node is a weighted sum of closed walks of different lengths in the network starting and ending at the node . This function returns a vector of subgraph centralities for each node of the network . Parameters CIJ : NxN np . ndarray binary a...
from scipy import linalg vals , vecs = linalg . eig ( CIJ ) # compute eigendecomposition # lambdas = np . diag ( vals ) # compute eigenvector centr . Cs = np . real ( np . dot ( vecs * vecs , np . exp ( vals ) ) ) return Cs
def p_idcall_expr ( p ) : """func _ call : ID arg _ list % prec UMINUS"""
# This can be a function call or a string index p [ 0 ] = make_call ( p [ 1 ] , p . lineno ( 1 ) , p [ 2 ] ) if p [ 0 ] is None : return if p [ 0 ] . token in ( 'STRSLICE' , 'VAR' , 'STRING' ) : entry = SYMBOL_TABLE . access_call ( p [ 1 ] , p . lineno ( 1 ) ) entry . accessed = True return # TODO : Che...
def is_app_linked ( source , pkg , java_package ) : """Returns true if the compile project line exists exists in the file"""
for line in source . split ( "\n" ) : if java_package in line : return True return False
def cas2mach ( cas , h ) : """CAS Mach conversion"""
tas = cas2tas ( cas , h ) M = tas2mach ( tas , h ) return M
def mp_a_trous_kernel ( C0 , wavelet_filter , scale , slice_ind , slice_width , r_or_c = "row" ) : """This is the convolution step of the a trous algorithm . INPUTS : C0 ( no default ) : The current array which is to be decomposed . wavelet _ filter ( no default ) : The filter - bank which is applied to the e...
lower_bound = slice_ind * slice_width upper_bound = ( slice_ind + 1 ) * slice_width if r_or_c == "row" : row_conv = wavelet_filter [ 2 ] * C0 [ : , lower_bound : upper_bound ] row_conv [ ( 2 ** ( scale + 1 ) ) : , : ] += wavelet_filter [ 0 ] * C0 [ : - ( 2 ** ( scale + 1 ) ) , lower_bound : upper_bound ] ro...
def update ( accountable , options ) : """Update an existing issue ."""
issue = accountable . issue_update ( options ) headers = issue . keys ( ) rows = [ headers , [ v for k , v in issue . items ( ) ] ] print_table ( SingleTable ( rows ) )
def from_json ( payload ) : """Convert the JSON expression of a contact information into an instance ` Contact . @ param payload : a JSON expression representing a contact information : [ type : ContactName , value : string , [ is _ primary : boolean , [ is _ verified : boolean ] ] ] @ return : an instance ...
contact_item_number = len ( payload ) assert 2 <= contact_item_number <= 4 , 'Invalid contact information format' is_primary = is_verified = None # Unpack the contact information to each component . if contact_item_number == 2 : ( name , value ) = payload elif contact_item_number == 3 : ( name , value , is_prim...
def _compare_acl ( current , desired , region , key , keyid , profile ) : '''ACLs can be specified using macro - style names that get expanded to something more complex . There ' s no predictable way to reverse it . So expand all syntactic sugar in our input , and compare against that rather than the input it...
ocid = _get_canonical_id ( region , key , keyid , profile ) return __utils__ [ 'boto3.json_objs_equal' ] ( current , _acl_to_grant ( desired , ocid ) )
def rotate ( algorithm , path , ext = "" , destination_dir = None , verbose = False ) : """Programmatic access to the archive rotator : param algorithm : an instance of BaseRotator from algorithms . py : param path : full path to input file : param ext : ( optional ) file extension to preserve : param desti...
paths = Paths ( path , ext , destination_dir ) _move_files ( algorithm , paths , verbose )
def cast ( self , dtype ) : """Cast this Block to use another data type . Parameters dtype : str or numpy . dtype The new data type ."""
for child in self . _children . values ( ) : child . cast ( dtype ) for _ , param in self . params . items ( ) : param . cast ( dtype )
def csw_global_dispatch ( request , url = None , catalog_id = None ) : """pycsw wrapper"""
if request . user . is_authenticated ( ) : # turn on CSW - T settings . REGISTRY_PYCSW [ 'manager' ] [ 'transactions' ] = 'true' env = request . META . copy ( ) # TODO : remove this workaround # HH should be able to pass env [ ' wsgi . input ' ] without hanging # details at https : / / github . com / cga - harvard ...
def begin_training ( self , get_gold_tuples = None , sgd = None , component_cfg = None , ** cfg ) : """Allocate models , pre - process training data and acquire a trainer and optimizer . Used as a contextmanager . get _ gold _ tuples ( function ) : Function returning gold data component _ cfg ( dict ) : Confi...
if get_gold_tuples is None : get_gold_tuples = lambda : [ ] # Populate vocab else : for _ , annots_brackets in get_gold_tuples ( ) : for annots , _ in annots_brackets : for word in annots [ 1 ] : _ = self . vocab [ word ] # noqa : F841 if cfg . get ( "device" ...
def _error_if_word_invalid ( word , valid_words_dictionary , technical_words_dictionary , line_offset , col_offset ) : """Return SpellcheckError if this non - technical word is invalid ."""
word_lower = word . lower ( ) valid_words_result = valid_words_dictionary . corrections ( word_lower ) if technical_words_dictionary : technical_words_result = technical_words_dictionary . corrections ( word ) else : # No technical words available to make an otherwise invalid # result value . technical_words_re...
def _add_file ( self , key , path ) : """Copy a file into the reference package ."""
filename = os . path . basename ( path ) base , ext = os . path . splitext ( filename ) if os . path . exists ( self . file_path ( filename ) ) : with tempfile . NamedTemporaryFile ( dir = self . path , prefix = base , suffix = ext ) as tf : filename = os . path . basename ( tf . name ) shutil . copyfile ( ...
def create_service ( kwargs = None , conn = None , call = None ) : '''. . versionadded : : 2015.8.0 Create a new hosted service CLI Example : . . code - block : : bash salt - cloud - f create _ service my - azure name = my _ service label = my _ service location = ' West US ' '''
if call != 'function' : raise SaltCloudSystemExit ( 'The create_service function must be called with -f or --function.' ) if not conn : conn = get_conn ( ) if kwargs is None : kwargs = { } if 'name' not in kwargs : raise SaltCloudSystemExit ( 'A name must be specified as "name"' ) if 'label' not in kwar...
def make_pydot_graph ( layers , output_shape = True , verbose = False ) : """: parameters : - layers : list List of the layers , as obtained from lasagne . layers . get _ all _ layers - output _ shape : ( default ` True ` ) If ` True ` , the output shape of each layer will be displayed . - verbose : ( def...
import pydotplus as pydot pydot_graph = pydot . Dot ( 'Network' , graph_type = 'digraph' ) pydot_nodes = { } pydot_edges = [ ] for i , layer in enumerate ( layers ) : layer_name = getattr ( layer , 'name' , None ) if layer_name is None : layer_name = layer . __class__ . __name__ layer_type = '{0}' ....
def _gotitem ( self , key , ndim , subset = None ) : """sub - classes to define return a sliced object Parameters key : string / list of selections ndim : 1,2 requested ndim of result subset : object , default None subset to act on"""
if ndim == 2 : if subset is None : subset = self . obj return DataFrameGroupBy ( subset , self . grouper , selection = key , grouper = self . grouper , exclusions = self . exclusions , as_index = self . as_index , observed = self . observed ) elif ndim == 1 : if subset is None : subset = sel...
def accel_toggle_transparency ( self , * args ) : """Callback to toggle transparency ."""
self . transparency_toggled = not self . transparency_toggled self . settings . styleBackground . triggerOnChangedValue ( self . settings . styleBackground , 'transparency' ) return True
def partition_by_vid ( self , ref ) : """A much faster way to get partitions , by vid only"""
from ambry . orm import Partition p = self . session . query ( Partition ) . filter ( Partition . vid == str ( ref ) ) . first ( ) if p : return self . wrap_partition ( p ) else : return None
def run ( self , N = 1 , trace_sort = False ) : '''Run the sampler , store the history of visited points into the member variable ` ` self . samples ` ` and the importance weights into ` ` self . weights ` ` . . . seealso : : : py : class : ` pypmc . tools . History ` : param N : Integer ; the number of...
if N == 0 : return 0 if trace_sort : this_samples , origin = self . _get_samples ( N , trace_sort = True ) self . _calculate_weights ( this_samples , N ) return origin else : this_samples = self . _get_samples ( N , trace_sort = False ) self . _calculate_weights ( this_samples , N )
def to_dict ( self ) : """Return a dictionary representation of the error . : return : A dict with the keys : - attr : Attribute which contains the error , or " < root > " if it refers to the schema root . - errors : A list of dictionary representations of the errors ."""
def exception_to_dict ( e ) : try : return e . to_dict ( ) except AttributeError : return { "type" : e . __class__ . __name__ , "error" : str ( e ) , } result = { "errors" : [ exception_to_dict ( e ) for e in self . errors ] } if self . index is not None : result [ "index" ] = self . index e...
def _out_of_date ( rw_file ) : """Check if a run workflow file points to an older version of manta and needs a refresh ."""
with open ( rw_file ) as in_handle : for line in in_handle : if line . startswith ( "sys.path.append" ) : file_version = line . split ( "/lib/python" ) [ 0 ] . split ( "Cellar/manta/" ) [ - 1 ] if file_version != programs . get_version_manifest ( "manta" ) : return Tr...
def take ( data , indices , axis = 0 , out = None , mode = 'raise' , blen = None , storage = None , create = 'array' , ** kwargs ) : """Take elements from an array along an axis ."""
# setup if out is not None : # argument is only there for numpy API compatibility raise NotImplementedError ( 'out argument is not supported' ) length = len ( data ) if axis == 0 : # check that indices are strictly increasing indices = np . asanyarray ( indices ) if np . any ( indices [ 1 : ] <= indices [ :...
def m ( name = '' , ** kwargs ) : """Print out memory usage at this point in time http : / / docs . python . org / 2 / library / resource . html http : / / stackoverflow . com / a / 15448600/5006 http : / / stackoverflow . com / questions / 110259 / which - python - memory - profiler - is - recommended"""
with Reflect . context ( ** kwargs ) as r : kwargs [ "name" ] = name instance = M_CLASS ( r , stream , ** kwargs ) instance ( )
def logs ( self , ** kwargs ) : """Get log stream for the service . Note : This method works only for services with the ` ` json - file ` ` or ` ` journald ` ` logging drivers . Args : details ( bool ) : Show extra details provided to logs . Default : ` ` False ` ` follow ( bool ) : Keep connection open...
is_tty = self . attrs [ 'Spec' ] [ 'TaskTemplate' ] [ 'ContainerSpec' ] . get ( 'TTY' , False ) return self . client . api . service_logs ( self . id , is_tty = is_tty , ** kwargs )
def tag2id ( self , xs ) : """Map tag ( s ) to id ( s ) Parameters xs : str or list tag or tags Returns int or list id ( s ) of tag ( s )"""
if isinstance ( xs , list ) : return [ self . _tag2id . get ( x , self . UNK ) for x in xs ] return self . _tag2id . get ( xs , self . UNK )
def offset_mode ( data ) : """Compute Mode using a histogram with ` sqrt ( data . size ) ` bins"""
nbins = int ( np . ceil ( np . sqrt ( data . size ) ) ) mind , maxd = data . min ( ) , data . max ( ) histo = np . histogram ( data , nbins , density = True , range = ( mind , maxd ) ) dx = abs ( histo [ 1 ] [ 1 ] - histo [ 1 ] [ 2 ] ) / 2 hx = histo [ 1 ] [ 1 : ] - dx hy = histo [ 0 ] idmax = np . argmax ( hy ) return...
def apply_correlation ( self , sites , imt , residuals , stddev_intra ) : """Apply correlation to randomly sampled residuals . See Parent function"""
# stddev _ intra is repeated if it is only 1 value for all the residuals if stddev_intra . shape [ 0 ] == 1 : stddev_intra = numpy . matlib . repmat ( stddev_intra , len ( sites . complete ) , 1 ) # Reshape ' stddev _ intra ' if needed stddev_intra = stddev_intra . squeeze ( ) if not stddev_intra . shape : stdd...
def get_markets ( self , market ) : """Get the list of markets http : / / business . skyscanner . net / portal / en - GB / Documentation / Markets"""
url = "{url}/{market}" . format ( url = self . MARKET_SERVICE_URL , market = market ) return self . make_request ( url , headers = self . _headers ( ) )
def sensor ( sensor_type , cfg ) : """Creates a camera sensor of the specified type . Parameters sensor _ type : : obj : ` str ` the type of the sensor ( real or virtual ) cfg : : obj : ` YamlConfig ` dictionary of parameters for sensor initialization"""
sensor_type = sensor_type . lower ( ) if sensor_type == 'kinect2' : s = Kinect2Sensor ( packet_pipeline_mode = cfg [ 'pipeline_mode' ] , device_num = cfg [ 'device_num' ] , frame = cfg [ 'frame' ] ) elif sensor_type == 'bridged_kinect2' : s = KinectSensorBridged ( quality = cfg [ 'quality' ] , frame = cfg [ 'fr...