signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def add_comment ( self , comment ) : """Adds a comment to a bug . If the bug object does not have a bug ID ( ie you are creating a bug ) then you will need to also call ` put ` on the : class : ` Bugsy ` class . > > > bug . add _ comment ( " I like sausages " ) > > > bugzilla . put ( bug ) If it does have...
# If we have a key post immediately otherwise hold onto it until # put ( bug ) is called if 'id' in self . _bug : self . _bugsy . request ( 'bug/{}/comment' . format ( self . _bug [ 'id' ] ) , method = 'POST' , json = { "comment" : comment } ) else : self . _bug [ 'comment' ] = comment
def wait_time ( departure , now = None ) : """Calculate waiting time until the next departure time in ' HH : MM ' format . Return time - delta ( as ' MM : SS ' ) from now until next departure time in the future ( ' HH : MM ' ) given as ( year , month , day , hour , minute , seconds ) . Time - deltas shorter t...
now = now or datetime . datetime . now ( ) yn , mn , dn = now . year , now . month , now . day hour , minute = map ( int , departure . split ( ':' ) ) dt = datetime . datetime ( yn , mn , dn , hour = hour , minute = minute ) delta = ( dt - now ) . seconds if ( dt - now ) . days < 0 : delta = 0 if delta < 3600 : ...
def _submit_and_wait ( cmd , cores , config , output_dir ) : """Submit command with batch script specified in configuration , wait until finished"""
batch_script = "submit_bcl2fastq.sh" if not os . path . exists ( batch_script + ".finished" ) : if os . path . exists ( batch_script + ".failed" ) : os . remove ( batch_script + ".failed" ) with open ( batch_script , "w" ) as out_handle : out_handle . write ( config [ "process" ] [ "bcl2fastq_ba...
def _ingest_dict ( self , input_dict , schema_dict , path_to_root ) : '''a helper method for ingesting keys , value pairs in a dictionary : return : valid _ dict'''
valid_dict = { } # construct path to root for rules rules_path_to_root = re . sub ( '\[\d+\]' , '[0]' , path_to_root ) # iterate over keys in schema dict for key , value in schema_dict . items ( ) : key_path = path_to_root if not key_path == '.' : key_path += '.' key_path += key rules_key_path =...
def send_order ( self , accounts , code = '000001' , price = 9 , amount = 100 , order_direction = ORDER_DIRECTION . BUY , order_model = ORDER_MODEL . LIMIT ) : """[ summary ] Arguments : accounts { [ type ] } - - [ description ] code { [ type ] } - - [ description ] price { [ type ] } - - [ description ] ...
try : # print ( code , price , amount ) return self . call_post ( 'orders' , { 'client' : accounts , "action" : 'BUY' if order_direction == 1 else 'SELL' , "symbol" : code , "type" : order_model , "priceType" : 0 if order_model == ORDER_MODEL . LIMIT else 4 , "price" : price , "amount" : amount } ) except json . de...
def _process ( self , metric ) : """We skip any locking code due to the fact that this is now a single process per collector"""
try : self . queue . put ( metric , block = False ) except Queue . Full : self . _throttle_error ( 'Queue full, check handlers for delays' )
def iter_links ( self , elements ) : '''Iterate the document root for links . Returns : iterable : A iterator of : class : ` LinkedInfo ` .'''
for element in elements : if not isinstance ( element , Element ) : continue for link_infos in self . iter_links_element ( element ) : yield link_infos
def _download_one_night_of_atlas_data ( mjd , log , archivePath ) : """* summary of function * * * Key Arguments : * * - ` ` mjd ` ` - - the mjd of the night of data to download - ` ` archivePath ` ` - - the path to the root of the local archive"""
# SETUP A DATABASE CONNECTION FOR THE remote database global dbSettings # SETUP ALL DATABASE CONNECTIONS atlasMoversDBConn = database ( log = log , dbSettings = dbSettings ) . connect ( ) cmd = "rsync -avzL --include='*.dph' --include='*.meta' --include='*/' --exclude='*' dyoung@atlas-base-adm01.ifa.hawaii.edu:/atlas/r...
def do_help ( self , arg ) : """Help command . Usage : help [ command ] Parameters : command : Optional - command name to display detailed help"""
cmds = arg . split ( ) if cmds : func = getattr ( self , 'do_{}' . format ( cmds [ 0 ] ) ) if func : _LOGGING . info ( func . __doc__ ) else : _LOGGING . error ( 'Command %s not found' , cmds [ 0 ] ) else : _LOGGING . info ( "Available command list: " ) for curr_cmd in dir ( self . _...
def distance ( self , a , b ) : r"""Gives the distance between two model parameter vectors : math : ` \ vec { a } ` and : math : ` \ vec { b } ` . By default , this is the vector 1 - norm of the difference : math : ` \ mathbf { Q } ( \ vec { a } - \ vec { b } ) ` rescaled by : attr : ` ~ Model . Q ` . : par...
return np . apply_along_axis ( lambda vec : np . linalg . norm ( vec , 1 ) , 1 , self . Q * ( a - b ) )
def parse_fits ( self , fit_name ) : '''USE PARSE _ ALL _ FITS unless otherwise necessary Isolate fits by the name of the fit ; we also set ' specimen _ tilt _ correction ' to zero in order to only include data in geographic coordinates - THIS NEEDS TO BE GENERALIZED'''
fits = self . fits . loc [ self . fits . specimen_comp_name == fit_name ] . loc [ self . fits . specimen_tilt_correction == 0 ] fits . reset_index ( inplace = True ) means = self . means . loc [ self . means . site_comp_name == fit_name ] . loc [ self . means . site_tilt_correction == 0 ] means . reset_index ( inplace ...
def getOrderedGlyphSet ( self ) : """Return OrderedDict [ glyphName , glyph ] sorted by glyphOrder ."""
compiler = self . context . compiler if compiler is not None : return compiler . glyphSet from ufo2ft . util import makeOfficialGlyphOrder glyphSet = self . context . font glyphOrder = makeOfficialGlyphOrder ( self . context . font ) return OrderedDict ( ( gn , glyphSet [ gn ] ) for gn in glyphOrder )
def pwl_to_poly ( self ) : """Converts the first segment of the pwl cost to linear quadratic . FIXME : Curve - fit for all segments ."""
if self . pcost_model == PW_LINEAR : x0 = self . p_cost [ 0 ] [ 0 ] y0 = self . p_cost [ 0 ] [ 1 ] x1 = self . p_cost [ 1 ] [ 0 ] y1 = self . p_cost [ 1 ] [ 1 ] m = ( y1 - y0 ) / ( x1 - x0 ) c = y0 - m * x0 self . pcost_model = POLYNOMIAL self . p_cost = ( m , c ) else : return
def tokenize ( text , lowercase = False , deacc = False ) : """Iteratively yield tokens as unicode strings , optionally also lowercasing them and removing accent marks ."""
if lowercase : text = text . lower ( ) if deacc : text = deaccent ( text ) for match in PAT_ALPHABETIC . finditer ( text ) : yield match . group ( )
def local_bifurcation_angles ( neurites , neurite_type = NeuriteType . all ) : '''Get a list of local bifurcation angles in a collection of neurites'''
return map_sections ( _bifurcationfunc . local_bifurcation_angle , neurites , neurite_type = neurite_type , iterator_type = Tree . ibifurcation_point )
def packageProject ( self , dir = os . getcwd ( ) , configuration = 'Shipping' , extraArgs = [ ] ) : """Packages a build of the Unreal project in the specified directory , using common packaging options"""
# Verify that the specified build configuration is valid if configuration not in self . validBuildConfigurations ( ) : raise UnrealManagerException ( 'invalid build configuration "' + configuration + '"' ) # Strip out the ` - NoCompileEditor ` flag if the user has specified it , since the Development version # of t...
def setDatastreamVersionable ( self , pid , dsID , versionable ) : '''Update datastream versionable setting . : param pid : object pid : param dsID : datastream id : param versionable : boolean : returns : boolean success'''
# / objects / { pid } / datastreams / { dsID } ? [ versionable ] http_args = { 'versionable' : versionable } url = 'objects/%(pid)s/datastreams/%(dsid)s' % { 'pid' : pid , 'dsid' : dsID } response = self . put ( url , params = http_args ) # returns response code 200 on success return response . status_code == requests ...
def compare_fetch_with_fs ( self ) : """Compares the fetch entries with the files actually in the payload , and returns a list of all the files that still need to be fetched ."""
files_on_fs = set ( self . payload_files ( ) ) files_in_fetch = set ( self . files_to_be_fetched ( ) ) return list ( files_in_fetch - files_on_fs )
def as_text ( bytes_or_text , encoding = 'utf-8' ) : """Returns the given argument as a unicode string . Args : bytes _ or _ text : A ` bytes ` , ` str , or ` unicode ` object . encoding : A string indicating the charset for decoding unicode . Returns : A ` unicode ` ( Python 2 ) or ` str ` ( Python 3 ) o...
if isinstance ( bytes_or_text , _six . text_type ) : return bytes_or_text elif isinstance ( bytes_or_text , bytes ) : return bytes_or_text . decode ( encoding ) else : raise TypeError ( 'Expected binary or unicode string, got %r' % bytes_or_text )
def page ( self , number = None ) : """If page is given , modify the URL correspondingly , return the current page otherwise ."""
if number is None : return int ( self . url . page ) self . url . page = str ( number )
def get_electron_number ( self , charge = 0 ) : """Return the number of electrons . Args : charge ( int ) : Charge of the molecule . Returns : int :"""
atomic_number = constants . elements [ 'atomic_number' ] . to_dict ( ) return sum ( [ atomic_number [ atom ] for atom in self [ 'atom' ] ] ) - charge
def tconvert ( gpsordate = 'now' ) : """Convert GPS times to ISO - format date - times and vice - versa . Parameters gpsordate : ` float ` , ` astropy . time . Time ` , ` datetime . datetime ` , . . . input gps or date to convert , many input types are supported Returns date : ` datetime . datetime ` or `...
# convert from GPS into datetime try : float ( gpsordate ) # if we can ' float ' it , then its probably a GPS time except ( TypeError , ValueError ) : return to_gps ( gpsordate ) return from_gps ( gpsordate )
def listdir ( self , relpath ) : """Like os . listdir , but reads from the git repository . : returns : a list of relative filenames"""
path = self . _realpath ( relpath ) if not path . endswith ( '/' ) : raise self . NotADirException ( self . rev , relpath ) if path [ 0 ] == '/' or path . startswith ( '../' ) : return os . listdir ( path ) tree = self . _read_tree ( path [ : - 1 ] ) return list ( tree . keys ( ) )
def _convert ( self , image , output = None ) : """Private method for converting a single PNG image to a PDF ."""
with Image . open ( image ) as im : width , height = im . size co = CanvasObjects ( ) co . add ( CanvasImg ( image , 1.0 , w = width , h = height ) ) return WatermarkDraw ( co , tempdir = self . tempdir , pagesize = ( width , height ) ) . write ( output )
def do_map ( input_dict , feature_format , positive_class = None ) : '''Maps a new example to a set of features .'''
# Context of the unseen example ( s ) train_context = input_dict [ 'train_ctx' ] test_context = input_dict [ 'test_ctx' ] # Currently known examples & background knowledge features = input_dict [ 'features' ] format = input_dict [ 'output_format' ] evaluations = domain_map ( features , feature_format , train_context , ...
def sequential_connect ( self ) : """Sequential connect is designed to return a connection to the Rendezvous Server but it does so in a way that the local port ranges ( both for the server and used for subsequent hole punching ) are allocated sequentially and predictably . This is because Delta + 1 type NAT...
# Connect to rendezvous server . try : mappings = sequential_bind ( self . mapping_no + 1 , self . interface ) con = self . server_connect ( mappings [ 0 ] [ "sock" ] ) except Exception as e : log . debug ( e ) log . debug ( "this err" ) return None # First mapping is used to talk to server . mappin...
def dedent ( self , func ) : """Dedent the docstring of a function and substitute with : attr : ` params ` Parameters func : function function with the documentation to dedent and whose sections shall be inserted from the : attr : ` params ` attribute"""
doc = func . __doc__ and self . dedents ( func . __doc__ , stacklevel = 4 ) return self . _set_object_doc ( func , doc )
def _build ( self , inputs ) : """Connects the module into the graph , with input Tensor ` inputs ` . Args : inputs : A Tensor of shape [ b _ 1 , b _ 2 , . . . , b _ preserve _ dims , b _ preserve _ dims + 1 , . . . ] . Returns : A Tensor of shape [ b _ 1 , b _ 2 , . . . , b _ preserve _ dims , b _ resh...
full_input_shape = inputs . get_shape ( ) . as_list ( ) if len ( full_input_shape ) < self . _preserve_dims : raise ValueError ( "Input tensor has {} dimensions, should have at least " "as many as preserve_dims={}" . format ( len ( full_input_shape ) , self . _preserve_dims ) ) self . _input_shape = full_input_shap...
def get_arg_parse ( ) : """Parses the Command Line Arguments using argparse ."""
# Create parser object : objParser = argparse . ArgumentParser ( ) # Add argument to namespace - strCsvPrf results file path : objParser . add_argument ( '-strCsvPrf' , required = True , metavar = '/path/to/my_prior_res' , help = 'Absolute file path of prior pRF results. \ Ignored if in...
def run ( sub_command , exit_handle = None , ** options ) : """Run a command"""
command = Command ( sub_command , exit_handle ) return command . run ( ** options )
def _parse_novel ( csv_file , sps = "new" ) : """Create input of novel miRNAs from miRDeep2"""
read = 0 seen = set ( ) safe_makedir ( "novel" ) with open ( "novel/hairpin.fa" , "w" ) as fa_handle , open ( "novel/miRNA.str" , "w" ) as str_handle : with open ( csv_file ) as in_handle : for line in in_handle : if line . startswith ( "mature miRBase miRNAs detected by miRDeep2" ) : ...
def _generate_pack_target_class ( dev ) : """! @ brief Generates a new target class from a CmsisPackDevice . @ param dev A CmsisPackDevice object . @ return A new subclass of either CoreSightTarget or one of the family classes ."""
try : # Look up the target family superclass . superklass = PackTargets . _find_family_class ( dev ) # Replace spaces and dashes with underscores on the new target subclass name . subclassName = dev . part_number . replace ( ' ' , '_' ) . replace ( '-' , '_' ) # Create a new subclass for this target . ...
def get_pin_tries ( self ) : """Returns the number of PIN retries left , 0 PIN authentication blocked . Note that 15 is the highest value that will be returned even if remaining tries is higher ."""
# Verify without PIN gives number of tries left . _ , sw = self . send_cmd ( INS . VERIFY , 0 , PIN , check = None ) return tries_left ( sw , self . version )
def select ( message = "" , title = "Lackey Input" , options = None , default = None ) : """Creates a dropdown selection dialog with the specified message and options ` default ` must be one of the options . Returns the selected value ."""
if options is None or len ( options ) == 0 : return "" if default is None : default = options [ 0 ] if default not in options : raise ValueError ( "<<default>> not in options[]" ) root = tk . Tk ( ) input_text = tk . StringVar ( ) input_text . set ( message ) PopupList ( root , message , title , options , d...
def credentials_required ( method_func ) : """Decorator for methods that checks that the client has credentials . Throws a CredentialsMissingError when they are absent ."""
def _checkcredentials ( self , * args , ** kwargs ) : if self . username and self . password : return method_func ( self , * args , ** kwargs ) else : raise CredentialsMissingError ( "This is a private method. \ You must provide a username and password when you initialize the \ DocumentCloud cli...
def save ( self ) : """Convert to JSON . Returns ` dict ` JSON data ."""
data = super ( ) . save ( ) data [ 'block_size' ] = list ( self . block_size ) data [ 'block_sentences' ] = self . block_sentences data [ 'traverse_image' ] = self . traverse_image . save ( ) data [ 'traverse_block' ] = self . traverse_block . save ( ) return data
def match_summary ( self , variant , score = lambda x : x . num_reads ( ) ) : '''Convenience method to summarize the evidence for and against a variant using a user - specified score function . See also ` PileupCollection . group _ by _ match ` . Parameters variant : Variant The variant . Must have fields...
split = self . group_by_match ( variant ) def name ( allele_to_pileup_collection ) : return "," . join ( allele_to_pileup_collection ) def aggregate_and_score ( pileup_collections ) : merged = PileupCollection . merge ( * pileup_collections ) return score ( merged ) result = [ ( name ( split . ref ) , aggre...
def _switch_tz_offset_sql ( self , field_name , tzname ) : """Returns the SQL that will convert field _ name to UTC from tzname ."""
field_name = self . quote_name ( field_name ) if settings . USE_TZ : if pytz is None : from django . core . exceptions import ImproperlyConfigured raise ImproperlyConfigured ( "This query requires pytz, " "but it isn't installed." ) tz = pytz . timezone ( tzname ) td = tz . utcoffset ( datet...
def list_global_ips ( self , version = None , identifier = None , ** kwargs ) : """Returns a list of all global IP address records on the account . : param int version : Only returns IPs of this version ( 4 or 6) : param string identifier : If specified , the list will only contain the global ips matching thi...
if 'mask' not in kwargs : mask = [ 'destinationIpAddress[hardware, virtualGuest]' , 'ipAddress' ] kwargs [ 'mask' ] = ',' . join ( mask ) _filter = utils . NestedDict ( { } ) if version : ver = utils . query_filter ( version ) _filter [ 'globalIpRecords' ] [ 'ipAddress' ] [ 'subnet' ] [ 'version' ] = ve...
def get_fields ( self ) : """Calculate fields that can be accessed by authenticated user ."""
ret = OrderedDict ( ) # no rights to see anything if not self . user : return ret # all fields that can be accessed through serializer fields = super ( ModelPermissionsSerializer , self ) . get_fields ( ) # superuser can see all the fields if self . user . is_superuser : return fields # fields that can be acces...
def create_backup ( self , resource , timeout = - 1 ) : """Creates a backup bundle with all the artifacts present on the appliance . At any given point only one backup bundle will exist on the appliance . Args : resource ( dict ) : Deployment Group to create the backup . timeout : Timeout in seconds . Wai...
return self . _client . create ( resource , uri = self . BACKUPS_PATH , timeout = timeout )
def get ( self , sid ) : """Constructs a CertificateContext : param sid : A string that uniquely identifies the Certificate . : returns : twilio . rest . preview . deployed _ devices . fleet . certificate . CertificateContext : rtype : twilio . rest . preview . deployed _ devices . fleet . certificate . Certi...
return CertificateContext ( self . _version , fleet_sid = self . _solution [ 'fleet_sid' ] , sid = sid , )
def _remove_bottleneck ( net_flux , path ) : """Internal function for modifying the net flux matrix by removing a particular edge , corresponding to the bottleneck of a particular path ."""
net_flux = copy . copy ( net_flux ) bottleneck_ind = net_flux [ path [ : - 1 ] , path [ 1 : ] ] . argmin ( ) net_flux [ path [ bottleneck_ind ] , path [ bottleneck_ind + 1 ] ] = 0.0 return net_flux
def tag_sidechain_dihedrals ( self , force = False ) : """Tags each monomer with side - chain dihedral angles force : bool , optional If ` True ` the tag will be run even if ` Residues ` are already tagged ."""
tagged = [ 'chi_angles' in x . tags . keys ( ) for x in self . _monomers ] if ( not all ( tagged ) ) or force : for monomer in self . _monomers : chi_angles = measure_sidechain_torsion_angles ( monomer , verbose = False ) monomer . tags [ 'chi_angles' ] = chi_angles return
def h_boiling_Huang_Sheer ( rhol , rhog , mul , kl , Hvap , sigma , Cpl , q , Tsat , angle = 35. ) : r'''Calculates the two - phase boiling heat transfer coefficient of a liquid and gas flowing inside a plate and frame heat exchanger , as developed in [ 1 ] _ and again in the thesis [ 2 ] _ . Depends on the pro...
do = 0.0146 * angle * ( 2. * sigma / ( g * ( rhol - rhog ) ) ) ** 0.5 Prl = Prandtl ( Cp = Cpl , mu = mul , k = kl ) alpha_l = thermal_diffusivity ( k = kl , rho = rhol , Cp = Cpl ) h = 1.87E-3 * ( kl / do ) * ( q * do / ( kl * Tsat ) ) ** 0.56 * ( Hvap * do ** 2 / alpha_l ** 2 ) ** 0.31 * Prl ** 0.33 return h
def create_key_pair ( self , key_name ) : """Create a new key pair for your account . This will create the key pair within the region you are currently connected to . : type key _ name : string : param key _ name : The name of the new keypair : rtype : : class : ` boto . ec2 . keypair . KeyPair ` : retu...
params = { 'KeyName' : key_name } return self . get_object ( 'CreateKeyPair' , params , KeyPair , verb = 'POST' )
def reduceByKeyAndWindow ( self , func , invFunc , windowDuration , slideDuration = None , numPartitions = None , filterFunc = None ) : """Return a new DStream by applying incremental ` reduceByKey ` over a sliding window . The reduced value of over a new window is calculated using the old window ' s reduce value...
self . _validate_window_param ( windowDuration , slideDuration ) if numPartitions is None : numPartitions = self . _sc . defaultParallelism reduced = self . reduceByKey ( func , numPartitions ) if invFunc : def reduceFunc ( t , a , b ) : b = b . reduceByKey ( func , numPartitions ) r = a . union...
def provision ( self , bug : Bug , uid : str = None , tools : Optional [ List [ Tool ] ] = None , volumes : Optional [ Dict [ str , str ] ] = None , network_mode : str = 'bridge' , ports : Optional [ Dict [ int , int ] ] = None , interactive : bool = False ) -> Container : """Provisions and returns a container for ...
if tools is None : tools = [ ] if volumes is None : volumes = { } if ports is None : ports = { } if uid is None : uid = str ( uuid . uuid4 ( ) ) logger . debug ( "provisioning container for bug %s: %s" , bug . name , uid ) tool_containers = [ self . __installation . tools . provision ( t ) for t in tool...
def _single_store ( self , addr , offset , size , data ) : """Performs a single store ."""
if offset == 0 and size == self . width : self . _contents [ addr ] = data elif offset == 0 : cur = self . _single_load ( addr , size , self . width - size ) self . _contents [ addr ] = data . concat ( cur ) elif offset + size == self . width : cur = self . _single_load ( addr , 0 , offset ) self . ...
def seeds ( args ) : """% prog seeds [ pngfile | jpgfile ] Extract seed metrics from [ pngfile | jpgfile ] . Use - - rows and - - cols to crop image ."""
p = OptionParser ( seeds . __doc__ ) p . set_outfile ( ) opts , args , iopts = add_seeds_options ( p , args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) pngfile , = args pf = opts . prefix or op . basename ( pngfile ) . rsplit ( "." , 1 ) [ 0 ] sigma , kernel = opts . sigma , opts . kernel rows , ...
def _set_vni_mask ( self , v , load = False ) : """Setter method for vni _ mask , mapped from YANG variable / overlay / access _ list / type / vxlan / standard / seq / vni _ mask ( string ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ vni _ mask is considered as a pr...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = RestrictedClassType ( base_type = unicode , restriction_dict = { 'pattern' : u'0|[1-9a-fA-F][0-9a-fA-F]{0,5}' } ) , is_leaf = True , yang_name = "vni-mask" , rest_name = "vni-mask" , parent = self , path_helper = self . _path...
def download_pic ( self , filename : str , url : str , mtime : datetime , filename_suffix : Optional [ str ] = None , _attempt : int = 1 ) -> bool : """Downloads and saves picture with given url under given directory with given timestamp . Returns true , if file was actually downloaded , i . e . updated ."""
urlmatch = re . search ( '\\.[a-z0-9]*\\?' , url ) file_extension = url [ - 3 : ] if urlmatch is None else urlmatch . group ( 0 ) [ 1 : - 1 ] if filename_suffix is not None : filename += '_' + filename_suffix filename += '.' + file_extension # A post is considered " commited " if the json file exists and is not mal...
def visit ( self , node ) : """Visit the right method of the child class according to the node ."""
method = 'visit_' + type ( node ) . __name__ return getattr ( self , method , self . fallback ) ( node )
def create ( self , outcome = values . unset ) : """Create a new FeedbackInstance : param FeedbackInstance . Outcome outcome : Whether the feedback has arrived : returns : Newly created FeedbackInstance : rtype : twilio . rest . api . v2010 . account . message . feedback . FeedbackInstance"""
data = values . of ( { 'Outcome' : outcome , } ) payload = self . _version . create ( 'POST' , self . _uri , data = data , ) return FeedbackInstance ( self . _version , payload , account_sid = self . _solution [ 'account_sid' ] , message_sid = self . _solution [ 'message_sid' ] , )
def must_stop ( self ) : """Return True if the worker must stop when the current loop is over ."""
return bool ( self . terminate_gracefuly and self . end_signal_caught or self . num_loops >= self . max_loops or self . end_forced or self . wanted_end_date and datetime . utcnow ( ) >= self . wanted_end_date )
def match ( self , uri ) : '''Matches an URL and returns a ( handler , target ) tuple'''
if uri in self . static : return self . static [ uri ] , { } for combined , subroutes in self . dynamic : match = combined . match ( uri ) if not match : continue target , groups = subroutes [ match . lastindex - 1 ] groups = groups . match ( uri ) . groupdict ( ) if groups else { } retu...
def bytes_available ( device ) : """Determines the number of bytes available for reading from an AlarmDecoder device : param device : the AlarmDecoder device : type device : : py : class : ` ~ alarmdecoder . devices . Device ` : returns : int"""
bytes_avail = 0 if isinstance ( device , alarmdecoder . devices . SerialDevice ) : if hasattr ( device . _device , "in_waiting" ) : bytes_avail = device . _device . in_waiting else : bytes_avail = device . _device . inWaiting ( ) elif isinstance ( device , alarmdecoder . devices . SocketDevice )...
def _termIsObsolete ( oboTerm ) : """Determine wheter an obo ' Term ' entry is marked as obsolete . : param oboTerm : a dictionary as return by : func : ` maspy . ontology . _ attributeLinesToDict ( ) ` : return : bool"""
isObsolete = False if u'is_obsolete' in oboTerm : if oboTerm [ u'is_obsolete' ] . lower ( ) == u'true' : isObsolete = True return isObsolete
def write_docstring_for_shortcut ( self ) : """Write docstring to editor by shortcut of code editor ."""
# cursor placed below function definition result = self . get_function_definition_from_below_last_line ( ) if result is not None : __ , number_of_lines_of_function = result cursor = self . code_editor . textCursor ( ) for __ in range ( number_of_lines_of_function ) : cursor . movePosition ( QTextCur...
def get_time_from_rfc3339 ( rfc3339 ) : """return time tuple from an RFC 3339 - formatted time string : param rfc3339 : str , time in RFC 3339 format : return : float , seconds since the Epoch"""
try : # py 3 dt = dateutil . parser . parse ( rfc3339 , ignoretz = False ) return dt . timestamp ( ) except NameError : # py 2 # Decode the RFC 3339 date with no fractional seconds ( the # format Origin provides ) . Note that this will fail to parse # valid ISO8601 timestamps not in this exact format . time...
def layout_json_names ( self ) : """Return layout . json names ."""
if self . _layout_json_names is None : self . _layout_json_names = self . layout_json_params . keys ( ) return self . _layout_json_names
def get_callable_signature_as_string ( the_callable ) : """Return a string representing a callable . It is executed as if it would have been declared on the prompt . > > > def foo ( arg1 , arg2 , arg3 = ' val1 ' , arg4 = ' val2 ' , * args , * * argd ) : . . . pass > > > get _ callable _ signature _ as _ str...
args , varargs , varkw , defaults = inspect . getargspec ( the_callable ) tmp_args = list ( args ) args_dict = { } if defaults : defaults = list ( defaults ) else : defaults = [ ] while defaults : args_dict [ tmp_args . pop ( ) ] = defaults . pop ( ) while tmp_args : args_dict [ tmp_args . pop ( ) ] = N...
def get_org_invite_args ( user_id , args ) : """Used by : - ` dx new user ` - ` dx add member ` PRECONDITION : - If / org - x / invite is being called in conjunction with / user / new , then ` _ validate _ new _ user _ input ( ) ` has been called on ` args ` ; otherwise , the parser must perform all the...
org_invite_args = { "invitee" : user_id } org_invite_args [ "level" ] = args . level if "set_bill_to" in args and args . set_bill_to is True : # / org - x / invite is called in conjunction with / user / new . org_invite_args [ "allowBillableActivities" ] = True else : org_invite_args [ "allowBillableActivities"...
def packet_get_samples_per_frame ( data , fs ) : """Gets the number of samples per frame from an Opus packet"""
data_pointer = ctypes . c_char_p ( data ) result = _packet_get_nb_frames ( data_pointer , ctypes . c_int ( fs ) ) if result < 0 : raise OpusError ( result ) return result
def check_version ( chrome_exe ) : '''Raises SystemExit if ` chrome _ exe ` is not a supported browser version . Must run in the main thread to have the desired effect .'''
# mac $ / Applications / Google \ Chrome . app / Contents / MacOS / Google \ Chrome - - version # Google Chrome 64.0.3282.140 # mac $ / Applications / Google \ Chrome \ Canary . app / Contents / MacOS / Google \ Chrome \ Canary - - version # Google Chrome 66.0.3341.0 canary # linux $ chromium - browser - - version # Us...
def _serie_format ( self , serie , value ) : """Format an independent value for the serie"""
kwargs = { 'chart' : self , 'serie' : serie , 'index' : None } formatter = ( serie . formatter or self . formatter or self . _value_format ) kwargs = filter_kwargs ( formatter , kwargs ) return formatter ( value , ** kwargs )
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_interface_type ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) get_stp_brief_info = ET . Element ( "get_stp_brief_info" ) config = get_stp_brief_info output = ET . SubElement ( get_stp_brief_info , "output" ) spanning_tree_info = ET . SubElement ( output , "spanning-tree-info" ) spanning_tree_mode = ET . SubElement ( spanning_tree_info , "spannin...
def format_keyval_to_metadata ( keytype , scheme , key_value , private = False ) : """< Purpose > Return a dictionary conformant to ' securesystemslib . formats . KEY _ SCHEMA ' . If ' private ' is True , include the private key . The dictionary returned has the form : { ' keytype ' : keytype , ' scheme '...
# Does ' keytype ' have the correct format ? # This check will ensure ' keytype ' has the appropriate number # of objects and object types , and that all dict keys are properly named . # Raise ' securesystemslib . exceptions . FormatError ' if the check fails . securesystemslib . formats . KEYTYPE_SCHEMA . check_match ...
def run_multisample_qualimap ( output_dir , work_dir , samples , targqc_full_report ) : """1 . Generates Qualimap2 plots and put into plots _ dirpath 2 . Adds records to targqc _ full _ report . plots"""
plots_dirpath = join ( output_dir , 'plots' ) individual_report_fpaths = [ s . qualimap_html_fpath for s in samples ] if isdir ( plots_dirpath ) and not any ( not can_reuse ( join ( plots_dirpath , f ) , individual_report_fpaths ) for f in listdir ( plots_dirpath ) if not f . startswith ( '.' ) ) : debug ( 'Qualima...
def parse_form_and_query_params ( req_params : dict , sig_params : dict ) -> dict : """Uses the parameter annotations to coerce string params . This is used for HTTP requests , in which the form parameters are all strings , but need to be converted to the appropriate types before validating them . : param d...
# Importing here to prevent circular dependencies . from doctor . types import SuperType , UnionType errors = { } parsed_params = { } for param , value in req_params . items ( ) : # Skip request variables not in the function signature . if param not in sig_params : continue # Skip coercing parameters no...
def get ( self , key ) : """Get a value from the cache . Returns None if the key is not in the cache ."""
value = redis_conn . get ( key ) if value is not None : value = pickle . loads ( value ) return value
def register_instances ( name , instances , region = None , key = None , keyid = None , profile = None ) : '''Add EC2 instance ( s ) to an Elastic Load Balancer . Removing an instance from the ` ` instances ` ` list does not remove it from the ELB . name The name of the Elastic Load Balancer to add EC2 instan...
ret = { 'name' : name , 'result' : True , 'comment' : '' , 'changes' : { } } lb = __salt__ [ 'boto_elb.exists' ] ( name , region , key , keyid , profile ) if not lb : msg = 'Could not find lb {0}' . format ( name ) log . error ( msg ) ret . update ( { 'comment' : msg , 'result' : False } ) return ret he...
def check_libcloud_version ( reqver = LIBCLOUD_MINIMAL_VERSION , why = None ) : '''Compare different libcloud versions'''
if not HAS_LIBCLOUD : return False if not isinstance ( reqver , ( list , tuple ) ) : raise RuntimeError ( '\'reqver\' needs to passed as a tuple or list, i.e., (0, 14, 0)' ) try : import libcloud # pylint : disable = redefined - outer - name except ImportError : raise ImportError ( 'salt-cloud requi...
def CheckForQuestionPending ( task ) : """Check to see if VM needs to ask a question , throw exception"""
vm = task . info . entity if vm is not None and isinstance ( vm , vim . VirtualMachine ) : qst = vm . runtime . question if qst is not None : raise TaskBlocked ( "Task blocked, User Intervention required" )
def delete_one ( self , filter , collation = None ) : """Delete a single document matching the filter . > > > db . test . count ( { ' x ' : 1 } ) > > > result = db . test . delete _ one ( { ' x ' : 1 } ) > > > result . deleted _ count > > > db . test . count ( { ' x ' : 1 } ) : Parameters : - ` filter `...
with self . _socket_for_writes ( ) as sock_info : return DeleteResult ( self . _delete ( sock_info , filter , False , collation = collation ) , self . write_concern . acknowledged )
def _to_dict ( self ) : """Return a json dictionary representing this model ."""
_dict = { } if hasattr ( self , 'tones' ) and self . tones is not None : _dict [ 'tones' ] = [ x . _to_dict ( ) for x in self . tones ] if hasattr ( self , 'category_id' ) and self . category_id is not None : _dict [ 'category_id' ] = self . category_id if hasattr ( self , 'category_name' ) and self . category_...
def latex_run ( self ) : '''Start latex run .'''
self . log . info ( 'Running %s...' % self . latex_cmd ) cmd = [ self . latex_cmd ] cmd . extend ( LATEX_FLAGS ) cmd . append ( '%s.tex' % self . project_name ) try : with open ( os . devnull , 'w' ) as null : Popen ( cmd , stdout = null , stderr = null ) . wait ( ) except OSError : self . log . error (...
def upload_slow ( self , localfile : str , remotefile : str , overwrite : bool = True , permission : str = '' , ** kwargs ) : """This method uploads a local file to the SAS servers file system . localfile - path to the local file to upload remotefile - path to remote file to create or overwrite overwrite - ov...
valid = self . _sb . file_info ( remotefile , quiet = True ) if valid is None : remf = remotefile else : if valid == { } : remf = remotefile + self . _sb . hostsep + localfile . rpartition ( os . sep ) [ 2 ] else : remf = remotefile if overwrite == False : return { 'Succe...
def _buffer ( editor , variables , force = False ) : """Go to one of the open buffers ."""
eb = editor . window_arrangement . active_editor_buffer force = bool ( variables [ 'force' ] ) buffer_name = variables . get ( 'buffer_name' ) if buffer_name : if not force and eb . has_unsaved_changes : editor . show_message ( _NO_WRITE_SINCE_LAST_CHANGE_TEXT ) else : editor . window_arrangemen...
def call ( self , to , ** options ) : """Places a call or sends an an IM , Twitter , or SMS message . To start a call , use the Session API to tell Tropo to launch your code . Arguments : to is a String . Argument : * * options is a set of optional keyword arguments . See https : / / www . tropo . com / docs ...
self . _steps . append ( Call ( to , ** options ) . obj )
def history_view ( self , request , object_id , extra_context = None ) : "The ' history ' admin view for this model ."
from django . contrib . admin . models import LogEntry # First check if the user can see this history . model = self . model obj = get_object_or_404 ( self . get_queryset ( request ) , pk = unquote ( object_id ) ) if not self . has_change_permission ( request , obj ) : raise PermissionDenied # Then get the history ...
def set_timestamp ( self , timestamp = None ) : """Set the timestamp of the linguistic processor , set to None for the current time @ type timestamp : string @ param timestamp : version of the linguistic processor"""
if timestamp is None : import time timestamp = time . strftime ( '%Y-%m-%dT%H:%M:%S%Z' ) self . node . set ( 'timestamp' , timestamp )
def stop_regularly_cleanup ( self , only_read = False ) : """> > > cache = Cache ( log _ level = logging . WARNING ) > > > cache . stop _ regularly _ cleanup ( ) True > > > cache . stop _ regularly _ cleanup ( ) False"""
if hasattr ( self , 'cleanup_supervisor' ) and self . cleanup_supervisor is not None : self . cleanup_supervisor . stop ( ) self . logger . debug ( 'Regularly cleanup thread %s is closed' % self . cleanup_supervisor . name ) self . cleanup_supervisor = None return True else : self . logger . warning...
def qos_red_profile_min_threshold ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) qos = ET . SubElement ( config , "qos" , xmlns = "urn:brocade.com:mgmt:brocade-qos" ) red_profile = ET . SubElement ( qos , "red-profile" ) profile_id_key = ET . SubElement ( red_profile , "profile-id" ) profile_id_key . text = kwargs . pop ( 'profile_id' ) min_threshold = ET . SubEle...
def dashboard ( request ) : """Dashboard page"""
user = None if request . user . is_authenticated ( ) : user = User . objects . get ( username = request . user ) latest_results , count_types = get_collaboration_data ( user ) latest_results . sort ( key = lambda elem : elem . modified , reverse = True ) context = { 'type_count' : count_types , 'latest_results' : l...
def fracsimplify ( numerator , denominator ) : """Simplify a fraction . : type numerator : integer : param numerator : The numerator of the fraction to simplify : type denominator : integer : param denominator : The denominator of the fraction to simplify : return : The simplified fraction : rtype : lis...
# If the numerator is the same as the denominator if numerator == denominator : # Return the most simplified fraction return '1/1' # If the numerator is larger than the denominator elif int ( numerator ) > int ( denominator ) : # Set the limit to half of the numerator limit = int ( numerator / 2 ) elif int ( nu...
def data ( tableid , variables = dict ( ) , stream = False , descending = False , lang = DEFAULT_LANGUAGE ) : """Pulls data from a table and generates rows . Variables is a dictionary mapping variable codes to values . Streaming : Values must be chosen for all variables when streaming"""
# bulk is also in csv format , but the response is streamed format = 'BULK' if stream else 'CSV' request = Request ( 'data' , tableid , format , timeOrder = 'Descending' if descending else None , valuePresentation = 'CodeAndValue' , lang = lang , ** variables ) return ( Data ( datum , lang = lang ) for datum in request...
def multi_perspective_match_pairwise ( vector1 : torch . Tensor , vector2 : torch . Tensor , weight : torch . Tensor , eps : float = 1e-8 ) -> torch . Tensor : """Calculate multi - perspective cosine matching between each time step of one vector and each time step of another vector . Parameters vector1 : ` ` ...
num_perspectives = weight . size ( 0 ) # (1 , num _ perspectives , 1 , hidden _ size ) weight = weight . unsqueeze ( 0 ) . unsqueeze ( 2 ) # ( batch , num _ perspectives , seq _ len * , hidden _ size ) vector1 = weight * vector1 . unsqueeze ( 1 ) . expand ( - 1 , num_perspectives , - 1 , - 1 ) vector2 = weight * vector...
def put_path ( self , url , path ) : """Puts a resource already on disk into the disk cache . Args : url : The original url of the resource path : The resource already available on disk Raises : CacheError : If the file cannot be put in cache"""
cache_path = self . _url_to_path ( url ) # Ensure that cache directories exist try : dir = os . path . dirname ( cache_path ) os . makedirs ( dir ) except OSError as e : if e . errno != errno . EEXIST : raise Error ( 'Failed to create cache directories for ' % cache_path ) # Remove the resource alre...
def is_senior_subclass ( obj , cls , testcls ) : """Determines whether the cls is the senior subclass of basecls for obj . The most senior subclass is the first class in the mro which is a subclass of testcls . Use for inheritance schemes where a method should only be called once by the most senior subclass...
for base in obj . __class__ . mro ( ) : if base is cls : return True else : if issubclass ( base , testcls ) : return False
def default_vsan_policy_configured ( name , policy ) : '''Configures the default VSAN policy on a vCenter . The state assumes there is only one default VSAN policy on a vCenter . policy Dict representation of a policy'''
# TODO Refactor when recurse _ differ supports list _ differ # It ' s going to make the whole thing much easier policy_copy = copy . deepcopy ( policy ) proxy_type = __salt__ [ 'vsphere.get_proxy_type' ] ( ) log . trace ( 'proxy_type = %s' , proxy_type ) # All allowed proxies have a shim execution module with the same ...
def get ( self , sid ) : """Constructs a RoomRecordingContext : param sid : The sid : returns : twilio . rest . video . v1 . room . recording . RoomRecordingContext : rtype : twilio . rest . video . v1 . room . recording . RoomRecordingContext"""
return RoomRecordingContext ( self . _version , room_sid = self . _solution [ 'room_sid' ] , sid = sid , )
def _convert_xml_to_retention_policy ( xml , retention_policy ) : '''< Enabled > true | false < / Enabled > < Days > number - of - days < / Days >'''
# Enabled retention_policy . enabled = _bool ( xml . find ( 'Enabled' ) . text ) # Days days_element = xml . find ( 'Days' ) if days_element is not None : retention_policy . days = int ( days_element . text )
def lookup ( self , inc_raw = False , retry_count = 3 , asn_data = None , depth = 0 , excluded_entities = None , response = None , bootstrap = False , rate_limit_timeout = 120 ) : """The function for retrieving and parsing information for an IP address via RDAP ( HTTP ) . Args : inc _ raw ( : obj : ` bool ` ,...
if not excluded_entities : excluded_entities = [ ] # Create the return dictionary . results = { 'query' : self . _net . address_str , 'network' : None , 'entities' : None , 'objects' : None , 'raw' : None } if bootstrap : ip_url = '{0}/ip/{1}' . format ( BOOTSTRAP_URL , self . _net . address_str ) else : ip...
def _update_mask ( self ) : """Pre - compute masks for speed ."""
self . _threshold_mask = self . _data > self . _theta self . _threshold_mask_v = self . _data > self . _theta / np . abs ( self . _v )
def fix_2to3 ( source , aggressive = True , select = None , ignore = None , filename = '' , where = 'global' , verbose = False ) : """Fix various deprecated code ( via lib2to3 ) ."""
if not aggressive : return source select = select or [ ] ignore = ignore or [ ] return refactor ( source , code_to_2to3 ( select = select , ignore = ignore , where = where , verbose = verbose ) , filename = filename )
def aorb ( a , b ) : """Return a matrix of logic comparison of A or B"""
return matrix ( np . logical_or ( a , b ) . astype ( 'float' ) , a . size )
def verify_space_available ( self , search_pattern = r"(\d+) \w+ free" ) : """Verify sufficient space is available on destination file system ( return boolean ) ."""
if self . direction == "put" : space_avail = self . remote_space_available ( search_pattern = search_pattern ) elif self . direction == "get" : space_avail = self . local_space_available ( ) if space_avail > self . file_size : return True return False
def get_provider_fn_decorations ( provider_fn , default_arg_names ) : """Retrieves the provider method - relevant info set by decorators . If any info wasn ' t set by decorators , then defaults are returned . Args : provider _ fn : a ( possibly decorated ) provider function default _ arg _ names : the ( pos...
if hasattr ( provider_fn , _IS_WRAPPER_ATTR ) : provider_decorations = getattr ( provider_fn , _PROVIDER_DECORATIONS_ATTR ) if provider_decorations : expanded_provider_decorations = [ ] for provider_decoration in provider_decorations : # TODO ( kurts ) : seems like default scope should be done a...
def contiguous ( self , other : "Interval" ) -> bool : """Does this interval overlap or touch the other ?"""
return not ( self . end < other . start or self . start > other . end )