signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def problem_glob ( extension = '.py' ) : """Returns ProblemFile objects for all valid problem files"""
filenames = glob . glob ( '*[0-9][0-9][0-9]*{}' . format ( extension ) ) return [ ProblemFile ( file ) for file in filenames ]
def _update_lock_icon ( self ) : """Update locked state icon"""
icon = ima . icon ( 'lock' ) if self . locked else ima . icon ( 'lock_open' ) self . locked_button . setIcon ( icon ) tip = _ ( "Unlock" ) if self . locked else _ ( "Lock" ) self . locked_button . setToolTip ( tip )
def get_buffer_status ( self , device_from = None ) : """Main method to read from buffer . Optionally pass in device to only get response from that device"""
device_from = device_from or '' # only used if device _ from passed in return_record = OrderedDict ( ) return_record [ 'success' ] = False return_record [ 'error' ] = True command_url = self . hub_url + '/buffstatus.xml' self . logger . info ( "get_buffer_status: %s" , command_url ) response = self . get_direct_command...
def flatten_dict ( i ) : """Any list item is converted to @ number = value Any dict item is converted to # key = value # is always added at the beginning Input : { dict - python dictionary ( prefix ) - prefix ( for recursion ) ( prune _ keys ) - list of keys to prune ( can have wildcards ) Output : { ...
prefix = '#' if i . get ( 'prefix' , '' ) != '' : prefix = str ( i [ 'prefix' ] ) a = i [ 'dict' ] aa = { } pk = i . get ( 'prune_keys' , '' ) if pk == '' : pk = [ ] flatten_dict_internal ( a , aa , prefix , pk ) return { 'return' : 0 , 'dict' : aa }
def package ( input_dir , output_dir , meta_path = None , create_meta = False , force = False ) : """Generate Python package for model data , including meta and required installation files . A new directory will be created in the specified output directory , and model data will be copied over . If - - create - ...
msg = Printer ( ) input_path = util . ensure_path ( input_dir ) output_path = util . ensure_path ( output_dir ) meta_path = util . ensure_path ( meta_path ) if not input_path or not input_path . exists ( ) : msg . fail ( "Can't locate model data" , input_path , exits = 1 ) if not output_path or not output_path . ex...
def _to_pb ( self ) : """Create cluster proto buff message for API calls"""
client = self . _instance . _client location = client . instance_admin_client . location_path ( client . project , self . location_id ) cluster_pb = instance_pb2 . Cluster ( location = location , serve_nodes = self . serve_nodes , default_storage_type = self . default_storage_type , ) return cluster_pb
def parse_dynare_text ( txt , add_model = True , full_output = False , debug = False ) : '''Imports the content of a modfile into the current interpreter scope'''
# here we call " instruction group " , a string finishing by a semicolon # an " instruction group " can have several lines # a line can be # - a comment / / . . . # - an old - style tag / / $ . . . # - a new - style tag [ key1 = ' value1 ' , . . ] # - macro - instruction @ # . . . # A Modfile contains several blocks ( ...
def primary_key ( self ) : """Returns either the primary key value , or a tuple containing the primary key values in the case of a composite primary key ."""
pkname = self . primary_key_name if pkname is None : return None elif isinstance ( pkname , str ) : return getattr ( self , pkname ) else : return tuple ( ( getattr ( self , pkn ) for pkn in pkname ) )
def read_checksum_digest ( path , checksum_cls = hashlib . sha256 ) : """Given a hash constructor , returns checksum digest and size of file ."""
checksum = checksum_cls ( ) size = 0 with tf . io . gfile . GFile ( path , "rb" ) as f : while True : block = f . read ( io . DEFAULT_BUFFER_SIZE ) size += len ( block ) if not block : break checksum . update ( block ) return checksum . hexdigest ( ) , size
def _Rzderiv ( self , R , z , phi = 0. , t = 0. ) : """NAME : _ Rzderiv PURPOSE : evaluate the mixed R , z derivative for this potential INPUT : R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT : d2phi / dR / dz HISTORY : 2015-02-13 - Written - Trick ( ...
l , n = bovy_coords . Rz_to_lambdanu ( R , z , ac = self . _ac , Delta = self . _Delta ) jac = bovy_coords . Rz_to_lambdanu_jac ( R , z , Delta = self . _Delta ) hess = bovy_coords . Rz_to_lambdanu_hess ( R , z , Delta = self . _Delta ) dldR = jac [ 0 , 0 ] dndR = jac [ 1 , 0 ] dldz = jac [ 0 , 1 ] dndz = jac [ 1 , 1 ]...
def _get_hanging_wall_coeffs_rrup ( self , dists ) : """Returns the hanging wall rrup term defined in equation 13"""
fhngrrup = np . ones ( len ( dists . rrup ) ) idx = dists . rrup > 0.0 fhngrrup [ idx ] = ( dists . rrup [ idx ] - dists . rjb [ idx ] ) / dists . rrup [ idx ] return fhngrrup
def holidays ( self , year = None ) : """Computes holidays ( non - working days ) for a given year . Return a 2 - item tuple , composed of the date and a label ."""
if not year : year = date . today ( ) . year if year in self . _holidays : return self . _holidays [ year ] # Here we process the holiday specific calendar temp_calendar = tuple ( self . get_calendar_holidays ( year ) ) # it is sorted self . _holidays [ year ] = sorted ( temp_calendar ) return self . _holidays ...
def ok ( self ) : """Returns True if OK to use , else False"""
try : v = int ( self . _value ) if v < self . imin or v > self . imax : return False else : return True except : return False
def write_module_docs ( pkgname , modpath , tmpltpath , outpath ) : """Write the autosummary style docs for the specified package . Parameters pkgname : string Name of package to document modpath : string Path to package source root directory tmpltpath : string Directory path for autosummary template ...
dw = DocWriter ( outpath , tmpltpath ) modlst = get_module_names ( modpath , pkgname ) print ( 'Making api docs:' , end = '' ) for modname in modlst : # Don ' t generate docs for cupy or cuda subpackages if 'cupy' in modname or 'cuda' in modname : continue try : mod = importlib . import_module (...
def _index_chains ( chains ) : '''Given a list of LiftOverChain objects , creates a dict : source _ name - - > IntervalTree : < source _ from , source _ to > - - > ( target _ from , target _ to , chain ) Returns the resulting dict . Throws an exception on any errors or inconsistencies among chains ( e . g...
chain_index = { } source_size = { } target_size = { } for c in chains : # Verify that sizes of chromosomes are consistent over all chains source_size . setdefault ( c . source_name , c . source_size ) if source_size [ c . source_name ] != c . source_size : raise Exception ( "Chains have inconsistent spe...
def _get_hook ( self , shader , name ) : """Return a FunctionChain that Filters may use to modify the program . * shader * should be " frag " or " vert " * name * should be " pre " or " post " """
assert name in ( 'pre' , 'post' ) key = ( shader , name ) if key in self . _hooks : return self . _hooks [ key ] hook = StatementList ( ) if shader == 'vert' : self . view_program . vert [ name ] = hook elif shader == 'frag' : self . view_program . frag [ name ] = hook self . _hooks [ key ] = hook return ho...
def header_body_from_content ( content ) : """Tries to extract the header and the message from the cable content . The header is something like UNCLASSIFIED . . . SUBJECT . . . REF . . . while the message begins usually with a summary 1 . SUMMARY . . . 10 . . . . Returns ( header , msg ) or ( None ,...
m = _CLASSIFIED_BY_PATTERN . search ( content ) idx = m and m . end ( ) or 0 m = _SUMMARY_PATTERN . search ( content ) summary_idx = m and m . start ( ) or None m = _FIRST_PARAGRAPH_PATTERN . search ( content ) para_idx = m and m . start ( ) or None if summary_idx and para_idx : idx = max ( idx , min ( summary_idx ...
def parse ( data ) : """Parses a raw datagram and return the right type of message"""
# convert to string data = data . decode ( "ascii" ) if len ( data ) == 2 and data == "A5" : return AckMessage ( ) # split into bytes raw = [ data [ i : i + 2 ] for i in range ( len ( data ) ) if i % 2 == 0 ] if len ( raw ) != 7 : return UnknownMessage ( raw ) if raw [ 1 ] == "B8" : return StateMessage ( ra...
def change_retry_host_check_interval ( self , host , check_interval ) : """Modify host retry interval Format of the line that triggers function call : : CHANGE _ RETRY _ HOST _ CHECK _ INTERVAL ; < host _ name > ; < check _ interval > : param host : host to edit : type host : alignak . objects . host . Host...
host . modified_attributes |= DICT_MODATTR [ "MODATTR_RETRY_CHECK_INTERVAL" ] . value host . retry_interval = check_interval self . send_an_element ( host . get_update_status_brok ( ) )
def _list_sessions ( self ) : """Return list of sessions in : py : obj : ` dict ` form . Retrieved from ` ` $ tmux ( 1 ) list - sessions ` ` stdout . The : py : obj : ` list ` is derived from ` ` stdout ` ` in : class : ` common . tmux _ cmd ` which wraps : py : class : ` subprocess . Popen ` . Returns li...
sformats = formats . SESSION_FORMATS tmux_formats = [ '#{%s}' % f for f in sformats ] tmux_args = ( '-F%s' % '\t' . join ( tmux_formats ) , ) # output proc = self . cmd ( 'list-sessions' , * tmux_args ) if proc . stderr : raise exc . LibTmuxException ( proc . stderr ) sformats = formats . SESSION_FORMATS tmux_forma...
def shorten_author_string ( authors_string , maxlength ) : """Parse a list of authors concatenated as a text string ( comma separated ) and smartly adjust them to maxlength . 1 ) If the complete list of sender names does not fit in maxlength , it tries to shorten names by using only the first part of each . ...
# I will create a list of authors by parsing author _ string . I use # deque to do popleft without performance penalties authors = deque ( ) # If author list is too long , it uses only the first part of each # name ( gmail style ) short_names = len ( authors_string ) > maxlength for au in authors_string . split ( ", " ...
def content_property ( name , doc = None ) : """Delegates a property to the first sibling in a RiakObject , raising an error when the object is in conflict ."""
def _setter ( self , value ) : if len ( self . siblings ) == 0 : # In this case , assume that what the user wants is to # create a new sibling inside an empty object . self . siblings = [ RiakContent ( self ) ] if len ( self . siblings ) != 1 : raise ConflictError ( ) setattr ( self . si...
def find_root_and_sink_variables ( self ) : '''Find root variables of the whole graph'''
# First we assume all variables are roots is_root = { name : True for scope in self . scopes for name in scope . variables . keys ( ) } # Then , we remove those variables which are outputs of some operators for operator in self . unordered_operator_iterator ( ) : for variable in operator . outputs : is_root...
def ulocalized_gmt0_time ( self , time , context , request ) : """Returns the localized time in string format , but in GMT + 0"""
value = get_date ( context , time ) if not value : return "" # DateTime is stored with TimeZone , but DateTimeWidget omits TZ value = value . toZone ( "GMT+0" ) return self . ulocalized_time ( value , context , request )
def rwishart_cov ( n , C ) : """Return a Wishart random matrix . : Parameters : n : int Degrees of freedom , > 0. C : matrix Symmetric and positive definite"""
# return rwishart ( n , np . linalg . inv ( C ) ) p = np . shape ( C ) [ 0 ] # Need cholesky decomposition of precision matrix C ^ - 1? sig = np . linalg . cholesky ( C ) if n <= ( p - 1 ) : raise ValueError ( 'Wishart parameter n must be greater ' 'than size of matrix.' ) norms = np . random . normal ( size = ( p ...
def setup_rabbitmq ( self ) : """Setup RabbitMQ connection . Call this method after spider has set its crawler object . : return : None"""
if not self . rabbitmq_key : self . rabbitmq_key = '{}:start_urls' . format ( self . name ) self . server = connection . from_settings ( self . crawler . settings ) self . crawler . signals . connect ( self . spider_idle , signal = signals . spider_idle ) self . crawler . signals . connect ( self . item_scraped , s...
def set_common_attributes ( span ) : """Set the common attributes ."""
common = { attributes_helper . COMMON_ATTRIBUTES . get ( 'AGENT' ) : AGENT , } common_attrs = Attributes ( common ) . format_attributes_json ( ) . get ( 'attributeMap' ) _update_attr_map ( span , common_attrs )
def reply_sticker ( self , sticker : str , quote : bool = None , disable_notification : bool = None , reply_to_message_id : int = None , reply_markup : Union [ "pyrogram.InlineKeyboardMarkup" , "pyrogram.ReplyKeyboardMarkup" , "pyrogram.ReplyKeyboardRemove" , "pyrogram.ForceReply" ] = None , progress : callable = None ...
if quote is None : quote = self . chat . type != "private" if reply_to_message_id is None and quote : reply_to_message_id = self . message_id return self . _client . send_sticker ( chat_id = self . chat . id , sticker = sticker , disable_notification = disable_notification , reply_to_message_id = reply_to_messa...
def getRequest ( self ) : """Return the primary AR this attachment is linked"""
ars = self . getLinkedRequests ( ) if len ( ars ) > 1 : # Attachment is assigned to more than one Analysis Request . # This might happen when the AR was invalidated ar_ids = ", " . join ( map ( api . get_id , ars ) ) logger . info ( "Attachment assigned to more than one AR: [{}]. " "The first AR will be returne...
def get_node_parent ( self , name ) : r"""Get the parent structure of a node . See : py : meth : ` ptrie . Trie . get _ node ` for details about the structure : param name : Child node name : type name : : ref : ` NodeName ` : rtype : dictionary : raises : * RuntimeError ( Argument \ ` name \ ` is not v...
if self . _validate_node_name ( name ) : raise RuntimeError ( "Argument `name` is not valid" ) self . _node_in_tree ( name ) return self . _db [ self . _db [ name ] [ "parent" ] ] if not self . is_root ( name ) else { }
def fill_contactfields ( self , row , obj ) : """Fills the contact fields for the specified object if allowed : EmailAddress , Phone , Fax , BusinessPhone , BusinessFax , HomePhone , MobilePhone"""
fieldnames = [ 'EmailAddress' , 'Phone' , 'Fax' , 'BusinessPhone' , 'BusinessFax' , 'HomePhone' , 'MobilePhone' , ] schema = obj . Schema ( ) fields = dict ( [ ( field . getName ( ) , field ) for field in schema . fields ( ) ] ) for fieldname in fieldnames : try : field = fields [ fieldname ] except : ...
def _paths_equal ( lhs , rhs ) : """If one object path doesn ' t inlcude a host , don ' t include the hosts in the comparison"""
if lhs is rhs : return True if lhs . host is not None and rhs . host is not None and lhs . host != rhs . host : return False # need to make sure this stays in sync with CIMInstanceName . _ _ cmp _ _ ( ) return not ( pywbem . cmpname ( rhs . classname , lhs . classname ) or cmp ( rhs . keybindings , lhs . keybin...
def run ( self ) : """Start the recurring task ."""
if self . init_sec : sleep ( self . init_sec ) self . _functime = time ( ) while self . _running : start = time ( ) self . _func ( ) self . _functime += self . interval_sec if self . _functime - start > 0 : sleep ( self . _functime - start )
def GetBatchJobHelper ( self , version = sorted ( _SERVICE_MAP . keys ( ) ) [ - 1 ] , server = None ) : """Returns a BatchJobHelper to work with the BatchJobService . This is a convenience method . It is functionally identical to calling BatchJobHelper ( adwords _ client , version ) . Args : [ optional ] ...
if not server : server = _DEFAULT_ENDPOINT request_builder = BatchJobHelper . GetRequestBuilder ( self , version = version , server = server ) response_parser = BatchJobHelper . GetResponseParser ( ) return BatchJobHelper ( request_builder , response_parser )
def download_fonts ( gh_url , dst ) : """Download fonts from a github dir"""
font_paths = [ ] r = requests . get ( gh_url ) for item in r . json ( ) : if item [ 'name' ] . endswith ( ".ttf" ) : f = item [ 'download_url' ] dl_path = os . path . join ( dst , os . path . basename ( f ) ) download_file ( f , dl_path ) font_paths . append ( dl_path ) return font_p...
def speziale_debyetemp ( v , v0 , gamma0 , q0 , q1 , theta0 ) : """calculate Debye temperature for the Speziale equation : param v : unit - cell volume in A ^ 3 : param v0 : unit - cell volume in A ^ 3 at 1 bar : param gamma0 : Gruneisen parameter at 1 bar : param q0 : logarithmic derivative of Gruneisen pa...
if isuncertainties ( [ v , v0 , gamma0 , q0 , q1 , theta0 ] ) : f_vu = np . vectorize ( uct . wrap ( integrate_gamma ) , excluded = [ 1 , 2 , 3 , 4 , 5 , 6 ] ) integ = f_vu ( v , v0 , gamma0 , q0 , q1 , theta0 ) theta = unp . exp ( unp . log ( theta0 ) - integ ) else : f_v = np . vectorize ( integrate_g...
def h2i ( self , pkt , x ) : """The field accepts string values like v12.1 , v1.1 or integer values . String values have to start with a " v " folled by a floating point number . Valid numbers are between 0 and 255."""
if isinstance ( x , str ) and x . startswith ( "v" ) and len ( x ) <= 8 : major = int ( x . split ( "." ) [ 0 ] [ 1 : ] ) minor = int ( x . split ( "." ) [ 1 ] ) return ( major << 8 ) | minor elif isinstance ( x , int ) and 0 <= x <= 65535 : return x else : if not hasattr ( self , "default" ) : ...
def change ( name , context = None , changes = None , lens = None , load_path = None , ** kwargs ) : '''. . versionadded : : 2014.7.0 This state replaces : py : func : ` ~ salt . states . augeas . setvalue ` . Issue changes to Augeas , optionally for a specific context , with a specific lens . name State ...
ret = { 'name' : name , 'result' : False , 'comment' : '' , 'changes' : { } } if not changes or not isinstance ( changes , list ) : ret [ 'comment' ] = '\'changes\' must be specified as a list' return ret if load_path is not None : if not isinstance ( load_path , list ) : ret [ 'comment' ] = '\'load...
def configure_environment ( self , last_trade , benchmark , timezone ) : '''Prepare benchmark loader and trading context'''
if last_trade . tzinfo is None : last_trade = pytz . utc . localize ( last_trade ) # Setup the trading calendar from market informations self . benchmark = benchmark self . context = TradingEnvironment ( bm_symbol = benchmark , exchange_tz = timezone , load = self . _get_benchmark_handler ( last_trade ) )
def read ( self ) : # type : ( ) - > Optional [ str ] """Read the project version from . py file . This will regex search in the file for a ` ` _ _ version _ _ = VERSION _ STRING ` ` and read the version string ."""
with open ( self . version_file ) as fp : version = fp . read ( ) . strip ( ) if is_valid ( version ) : return version return None
def move_consonant_right ( letters : List [ str ] , positions : List [ int ] ) -> List [ str ] : """Given a list of letters , and a list of consonant positions , move the consonant positions to the right , merging strings as necessary . : param letters : : param positions : : return : > > > move _ consona...
for pos in positions : letters [ pos + 1 ] = letters [ pos ] + letters [ pos + 1 ] letters [ pos ] = "" return letters
def make_population ( population_size , solution_generator , * args , ** kwargs ) : """Make a population with the supplied generator ."""
return [ solution_generator ( * args , ** kwargs ) for _ in range ( population_size ) ]
def _reinit_daq_daemons ( sender , instance , ** kwargs ) : """update the daq daemon configuration when changes be applied in the models"""
if type ( instance ) is VISADevice : post_save . send_robust ( sender = Device , instance = instance . visa_device ) elif type ( instance ) is VISAVariable : post_save . send_robust ( sender = Variable , instance = instance . visa_variable ) elif type ( instance ) is VISADeviceHandler : # todo pass elif typ...
def completion ( X , factored_updates = True ) : """Supernodal multifrontal maximum determinant positive definite matrix completion . The routine computes the Cholesky factor : math : ` L ` of the inverse of the maximum determinant positive definite matrix completion of : math : ` X ` : , i . e . , . . math...
assert isinstance ( X , cspmatrix ) and X . is_factor is False , "X must be a cspmatrix" n = X . symb . n snpost = X . symb . snpost snptr = X . symb . snptr chptr = X . symb . chptr chidx = X . symb . chidx relptr = X . symb . relptr relidx = X . symb . relidx blkptr = X . symb . blkptr blkval = X . blkval stack = [ ]...
def temperature ( self ) : """Returns the current CPU temperature in degrees celsius ."""
with io . open ( self . sensor_file , 'r' ) as f : return float ( f . readline ( ) . strip ( ) ) / 1000
def login ( request , signature ) : """Automatically logs in a user based on a signed PK of a user object . The signature should be generated with the ` login ` management command . The signature will only work for 60 seconds ."""
signer = TimestampSigner ( ) try : pk = signer . unsign ( signature , max_age = MAX_AGE_OF_SIGNATURE_IN_SECONDS ) except ( BadSignature , SignatureExpired ) as e : return HttpResponseForbidden ( "Can't log you in" ) user = get_object_or_404 ( get_user_model ( ) , pk = pk ) # we * have * to set the backend for t...
def spatial_clip ( catalog , corners , mindepth = None , maxdepth = None ) : """Clip the catalog to a spatial box , can be irregular . Can only be irregular in 2D , depth must be between bounds . : type catalog : : class : ` obspy . core . catalog . Catalog ` : param catalog : Catalog to clip . : type corne...
cat_out = catalog . copy ( ) if mindepth is not None : for event in cat_out : try : origin = _get_origin ( event ) except IOError : continue if origin . depth < mindepth * 1000 : cat_out . events . remove ( event ) if maxdepth is not None : for event i...
def _prepare_basicauth ( self , username , password ) : """Handles BasicAuth preparation and error handling . Either both ` ` username ` ` and ` ` password ` ` must be defined , or neither . Defining one but not the other will result in an : class : ` AssertionError ` . ` ` username ` ` ` ` password ` ` R...
if username and password : enc_str = base64 . b64encode ( ":" . join ( ( username , password ) ) ) return ( "Authorization" , "Basic %s" % enc_str ) elif username or password : raise Exception ( "Username and password must both be specified." ) else : return None
def rastrigin ( self , x ) : """Rastrigin test objective function"""
if not isscalar ( x [ 0 ] ) : N = len ( x [ 0 ] ) return [ 10 * N + sum ( xi ** 2 - 10 * np . cos ( 2 * np . pi * xi ) ) for xi in x ] # return 10 * N + sum ( x * * 2 - 10 * np . cos ( 2 * np . pi * x ) , axis = 1) N = len ( x ) return 10 * N + sum ( x ** 2 - 10 * np . cos ( 2 * np . pi * x ) )
def write_config ( self , filename = None , header = "# Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib)\n" , save_old = True , verbose = True ) : r"""Writes out symbol values in the . config format . The format matches the C implementation , including ordering . Symbols appear in the same orde...
if filename is None : filename = standard_config_filename ( ) else : verbose = False if save_old : _save_old ( filename ) with self . _open ( filename , "w" ) as f : f . write ( header ) for node in self . node_iter ( unique_syms = True ) : item = node . item if item . __class__ is S...
def eval ( self , expression ) : """Evaluate ` expression ` in MATLAB engine . Parameters expression : str Expression is passed to MATLAB engine and evaluated ."""
expression_wrapped = wrap_script . format ( expression ) # # # Evaluate the expression self . _libeng . engEvalString ( self . _ep , expression_wrapped ) # # # Check for exceptions in MATLAB mxresult = self . _libeng . engGetVariable ( self . _ep , 'ERRSTR__' ) error_string = self . _libmx . mxArrayToString ( mxresult ...
def cmd_screen ( action , action_space , ability_id , queued , screen ) : """Do a command that needs a point on the screen ."""
action_cmd = spatial ( action , action_space ) . unit_command action_cmd . ability_id = ability_id action_cmd . queue_command = queued screen . assign_to ( action_cmd . target_screen_coord )
def run ( url , output , config ) : """Extracts database dump from given database URL and outputs sanitized copy of it into given stream . : param url : URL to the database which is to be sanitized . : type url : str : param output : Stream where sanitized copy of the database dump will be written into . ...
parsed_url = urlparse . urlparse ( url ) db_module_path = SUPPORTED_DATABASE_MODULES . get ( parsed_url . scheme ) if not db_module_path : raise ValueError ( "Unsupported database scheme: '%s'" % ( parsed_url . scheme , ) ) db_module = importlib . import_module ( db_module_path ) session . reset ( ) for line in db_...
def sky_fraction ( self ) : """Sky fraction covered by the MOC"""
pix_id = self . _best_res_pixels ( ) nb_pix_filled = pix_id . size return nb_pix_filled / float ( 3 << ( 2 * ( self . max_order + 1 ) ) )
def get_virtual_fd_set_params_cmd ( remote_image_server , remote_image_user_domain , remote_image_share_type , remote_image_share_name , remote_image_floppy_fat , remote_image_username , remote_image_user_password ) : """get Virtual FD Media Set Parameters Command This function returns Virtual FD Media Set Parame...
cmd = _VIRTUAL_MEDIA_FD_SETTINGS % ( remote_image_server , remote_image_user_domain , remote_image_share_type , remote_image_share_name , remote_image_floppy_fat , remote_image_username , remote_image_user_password ) return cmd
def formatargspec ( args , varargs = None , varkw = None , defaults = None , formatarg = str , formatvarargs = lambda name : '*' + name , formatvarkw = lambda name : '**' + name , formatvalue = lambda value : '=' + repr ( value ) , join = joinseq ) : """Format an argument spec from the 4 values returned by getargsp...
specs = [ ] if defaults : firstdefault = len ( args ) - len ( defaults ) for i in range ( len ( args ) ) : spec = strseq ( args [ i ] , formatarg , join ) if defaults and i >= firstdefault : spec = spec + formatvalue ( defaults [ i - firstdefault ] ) specs . append ( spec ) if varargs : spec...
def chat_unfurl ( self , * , channel : str , ts : str , unfurls : dict , ** kwargs ) -> SlackResponse : """Provide custom unfurl behavior for user - posted URLs . Args : channel ( str ) : The Channel ID of the message . e . g . ' C1234567890' ts ( str ) : Timestamp of the message to add unfurl behavior to . e...
self . _validate_xoxp_token ( ) kwargs . update ( { "channel" : channel , "ts" : ts , "unfurls" : unfurls } ) return self . api_call ( "chat.unfurl" , json = kwargs )
def decrement ( self , key , value = 1 ) : """Decrement the value of an item in the cache . : param key : The cache key : type key : str : param value : The decrement value : type value : int : rtype : int or bool"""
self . _store . decrement ( self . tagged_item_key ( key ) , value )
def _draw_button ( self , overlay , text , location ) : """Draws a button on the won and lost overlays , and return its hitbox ."""
label = self . button_font . render ( text , True , ( 119 , 110 , 101 ) ) w , h = label . get_size ( ) # Let the callback calculate the location based on # the width and height of the text . x , y = location ( w , h ) # Draw a box with some border space . pygame . draw . rect ( overlay , ( 238 , 228 , 218 ) , ( x - 5 ,...
def p_factor_id ( self , p ) : """factor : ID"""
def resolve_id ( key , context ) : try : return context [ key ] except KeyError : raise NameError ( "name '{}' is not defined" . format ( key ) ) p [ 0 ] = Instruction ( 'resolve_id(key, context)' , context = { 'resolve_id' : resolve_id , 'key' : p [ 1 ] , 'context' : self . context } )
def cut_levels ( nodes , start_level ) : """cutting nodes away from menus"""
final = [ ] removed = [ ] for node in nodes : if not hasattr ( node , 'level' ) : # remove and ignore nodes that don ' t have level information remove ( node , removed ) continue if node . attr . get ( 'soft_root' , False ) : # remove and ignore nodes that are behind a node marked as ' soft _ ro...
def clean ( self ) : """Validates the form ."""
if not self . instance . pk : # Only set user on post creation if not self . user . is_anonymous : self . instance . poster = self . user else : self . instance . anonymous_key = get_anonymous_user_forum_key ( self . user ) return super ( ) . clean ( )
def parse_name ( self ) : """This function uses string patterns to match a title cased name . This is done in a loop until there are no more names to match so as to be able to include surnames etc . in the output ."""
name = [ ] while True : # Match the current char until it doesnt match the given pattern : # first char must be an uppercase alpha and the rest must be lower # cased alphas . part = self . match_string_pattern ( spat . alphau , spat . alphal ) if part == '' : break # There is no more matchable s...
def promotePrefixes ( self ) : """Push prefix declarations up the tree as far as possible . Prefix mapping are pushed to its parent unless the parent has the prefix mapped to another URI or the parent has the prefix . This is propagated up the tree until the top is reached . @ return : self @ rtype : L { ...
for c in self . children : c . promotePrefixes ( ) if self . parent is None : return _pref = [ ] for p , u in self . nsprefixes . items ( ) : if p in self . parent . nsprefixes : pu = self . parent . nsprefixes [ p ] if pu == u : _pref . append ( p ) continue if p != ...
def _search ( self , addr ) : """Checks which segment that the address ` addr ` should belong to , and , returns the offset of that segment . Note that the address may not actually belong to the block . : param addr : The address to search : return : The offset of the segment ."""
start = 0 end = len ( self . _list ) while start != end : mid = ( start + end ) // 2 segment = self . _list [ mid ] if addr < segment . start : end = mid elif addr >= segment . end : start = mid + 1 else : # Overlapped : ( start = mid break return start
def _normalize_name ( name ) : """Returns a normalized element tag or attribute name . A tag name or attribute name can be given either as a string , or as a 2 - tuple . If a 2 - tuple , it is interpreted as ( namespace , name ) and is returned joined by a colon " : " : name : a string or a 2 - tuple of strin...
if isinstance ( name , tuple ) : ns , nm = name return "{}:{}" . format ( ns , nm ) else : return name
def Then5 ( self , f , arg1 , arg2 , arg3 , arg4 , * args , ** kwargs ) : """` Then5 ( f , . . . ) ` is equivalent to ` ThenAt ( 5 , f , . . . ) ` . Checkout ` phi . builder . Builder . ThenAt ` for more information ."""
args = ( arg1 , arg2 , arg3 , arg4 ) + args return self . ThenAt ( 5 , f , * args , ** kwargs )
def visit_Cond ( self , node ) : '''generic expression splitting algorithm . Should work for ifexp and if using W ( rap ) and U ( n ) W ( rap ) to manage difference between expr and stmt The idea is to split a BinOp in three expressions : 1 . a ( possibly empty ) non - static expr 2 . an expr containing a s...
NodeTy = type ( node ) if NodeTy is ast . IfExp : def W ( x ) : return x def UW ( x ) : return x else : def W ( x ) : return [ x ] def UW ( x ) : return x [ 0 ] has_static_expr = self . gather ( HasStaticExpression , node . test ) if not has_static_expr : return node ...
def search_unique_identities_slice ( db , term , offset , limit ) : """Look for unique identities using slicing . This function returns those unique identities which match with the given ` term ` . The term will be compared with name , email , username and source values of each identity . When an empty term i...
uidentities = [ ] pattern = '%' + term + '%' if term else None if offset < 0 : raise InvalidValueError ( 'offset must be greater than 0 - %s given' % str ( offset ) ) if limit < 0 : raise InvalidValueError ( 'limit must be greater than 0 - %s given' % str ( limit ) ) with db . connect ( ) as session : query...
def from_words ( cls , words , prefix = 0 , flatten = False ) : """Given an iterable of words , return the corresponding table . The table is built by accumulating , for each word , for each sub - word , the number of occurrences of the corresponding next character . : param words : an iterable of strings mad...
table = defaultdict ( lambda : defaultdict ( int ) ) for word in words : word = ">" + word + "<" for start in range ( len ( word ) - 1 ) : max_end = ( ( len ( word ) - 1 ) if prefix <= 0 else ( min ( start + prefix + 1 , len ( word ) - 1 ) ) ) for end in range ( start + 1 , max_end + 1 ) : ...
def get_status ( self , status_value , message = None ) : """Build a Status XML block for a SAML 1.1 Response ."""
status = etree . Element ( 'Status' ) status_code = etree . SubElement ( status , 'StatusCode' ) status_code . set ( 'Value' , 'samlp:' + status_value ) if message : status_message = etree . SubElement ( status , 'StatusMessage' ) status_message . text = message return status
def get_asset_ids_map ( self ) : """stub"""
asset_ids_map = { } for label , asset_obj in self . my_osid_object . _my_map [ 'fileIds' ] . items ( ) : asset_ids_map [ label ] = asset_obj return asset_ids_map
def create_tasks ( self , wfk_file , scr_input ) : """Create the SCR tasks and register them in self . Args : wfk _ file : Path to the ABINIT WFK file to use for the computation of the screening . scr _ input : Input for the screening calculation ."""
assert len ( self ) == 0 wfk_file = self . wfk_file = os . path . abspath ( wfk_file ) # Build a temporary work in the tmpdir that will use a shell manager # to run ABINIT in order to get the list of q - points for the screening . shell_manager = self . manager . to_shell_manager ( mpi_procs = 1 ) w = Work ( workdir = ...
def build_from_job_list ( scheme_files , templates , base_output_dir ) : """Use $ scheme _ files as a job lists and build base16 templates using $ templates ( a list of TemplateGroup objects ) ."""
queue = Queue ( ) for scheme in scheme_files : queue . put ( scheme ) if len ( scheme_files ) < 40 : thread_num = len ( scheme_files ) else : thread_num = 40 threads = [ ] for _ in range ( thread_num ) : thread = Thread ( target = build_single_worker , args = ( queue , templates , base_output_dir ) ) ...
def increment ( self , key , value = 1 ) : """Increment the value of an item in the cache . : param key : The cache key : type key : str : param value : The increment value : type value : int : rtype : int or bool"""
return self . _redis . incrby ( self . _prefix + key , value )
def set_property ( obj , name , value ) : """Sets value of object property specified by its name . If the property does not exist or introspection fails this method doesn ' t do anything and doesn ' t any throw errors . : param obj : an object to write property to . : param name : a name of the property to ...
if obj == None : raise Exception ( "Object cannot be null" ) if name == None : raise Exception ( "Property name cannot be null" ) name = name . lower ( ) try : for property_name in dir ( obj ) : if property_name . lower ( ) != name : continue property = getattr ( obj , property_n...
def show_image ( self , name ) : """Show image ( item is a PIL image )"""
command = "%s.show()" % name sw = self . shellwidget if sw . _reading : sw . kernel_client . input ( command ) else : sw . execute ( command )
def Fourier_heat ( t , L , rho = None , Cp = None , k = None , alpha = None ) : r'''Calculates heat transfer Fourier number or ` Fo ` for a specified time ` t ` , characteristic length ` L ` , and specified properties for the given fluid . . . math : : Fo = \ frac { k t } { C _ p \ rho L ^ 2 } = \ frac { \ ...
if rho and Cp and k : alpha = k / ( rho * Cp ) elif not alpha : raise Exception ( 'Either heat capacity and thermal conductivity and \ density, or thermal diffusivity is needed' ) return t * alpha / L ** 2
def envRegisterFilter ( self , name , attr_regex = '^\w+$' , default = True ) : """Register filter for including , excluding attributes in graphs through the use of include _ < name > and exclude _ < name > environment variables . The value of the variables must be a comma separated list of items . @ param na...
attrs = { } for prefix in ( 'include' , 'exclude' ) : key = "%s_%s" % ( prefix , name ) val = self . _env . get ( key ) if val : attrs [ prefix ] = [ attr . strip ( ) for attr in val . split ( ',' ) ] else : attrs [ prefix ] = [ ] self . _filters [ name ] = MuninAttrFilter ( attrs [ 'inc...
def refresh ( self , fetch_data ) : """Redraw the display"""
self . win . erase ( ) height , width = getmaxyx ( ) if curses . is_term_resized ( height , width ) : self . win . clear ( ) curses . resizeterm ( height , width ) y = 1 # Starts at 1 because of date string x = 0 columns = [ ] column = [ ] for table in self . _tables : desc = self . engine . describe ( tabl...
def block ( self , * args , ** kwargs ) : """Add a block index . Shortcut of : class : ` recordlinkage . index . Block ` : : from recordlinkage . index import Block indexer = recordlinkage . Index ( ) indexer . add ( Block ( ) )"""
indexer = Block ( * args , ** kwargs ) self . add ( indexer ) return self
def execute ( self , conn , dataset = "" , block_name = "" , data_tier_name = "" , origin_site_name = "" , logical_file_name = "" , run_num = - 1 , min_cdate = 0 , max_cdate = 0 , min_ldate = 0 , max_ldate = 0 , cdate = 0 , ldate = 0 , open_for_writing = - 1 , transaction = False ) : """dataset : / a / b / c bloc...
binds = { } basesql = self . sql joinsql = "" wheresql = "" generatedsql = "" if logical_file_name and logical_file_name != "%" : joinsql += " JOIN %sFILES FL ON FL.BLOCK_ID = B.BLOCK_ID " % ( self . owner ) op = ( "=" , "like" ) [ "%" in logical_file_name ] wheresql += " WHERE LOGICAL_FILE_NAME %s :logical...
def parse_all ( self , models , path , package_name , root_dir ) : """Parse all the model dictionaries in models . : param List [ dict ] models : The ` models ` section of the schema . yml , as a list of dicts . : param str path : The path to the schema . yml file : param str package _ name : The name of th...
filtered = _filter_validate ( path , 'models' , models , UnparsedNodeUpdate ) nodes = itertools . chain . from_iterable ( self . parse_models_entry ( model , path , package_name , root_dir ) for model in filtered ) for node_type , node in nodes : yield node_type , node
def get_instance ( self , payload ) : """Build an instance of FieldInstance : param dict payload : Payload response from the API : returns : twilio . rest . autopilot . v1 . assistant . task . field . FieldInstance : rtype : twilio . rest . autopilot . v1 . assistant . task . field . FieldInstance"""
return FieldInstance ( self . _version , payload , assistant_sid = self . _solution [ 'assistant_sid' ] , task_sid = self . _solution [ 'task_sid' ] , )
def io_add_watch ( * args , ** kwargs ) : """io _ add _ watch ( channel , priority , condition , func , * user _ data ) - > event _ source _ id"""
channel , priority , condition , func , user_data = _io_add_watch_get_args ( * args , ** kwargs ) return GLib . io_add_watch ( channel , priority , condition , func , * user_data )
def _check_len ( self , pkt ) : """Check for odd packet length and pad according to Cisco spec . This padding is only used for checksum computation . The original packet should not be altered ."""
if len ( pkt ) % 2 : last_chr = pkt [ - 1 ] if last_chr <= b'\x80' : return pkt [ : - 1 ] + b'\x00' + last_chr else : return pkt [ : - 1 ] + b'\xff' + chb ( orb ( last_chr ) - 1 ) else : return pkt
def set_target_temperature_by_id ( self , zone_id , target_temperature ) : """Set the target temperature for a zone by id"""
if not self . _do_auth ( ) : raise RuntimeError ( "Unable to login" ) data = { "ZoneId" : zone_id , "TargetTemperature" : target_temperature } headers = { "Accept" : "application/json" , "Content-Type" : "application/json" , 'Authorization' : 'Bearer ' + self . login_data [ 'token' ] [ 'accessToken' ] } url = self ...
def find_instance ( self , name , module = None ) : """Find the Instance by its name ."""
module = module if module is not None else ffi . NULL definstance = lib . EnvFindInstance ( self . _env , module , name . encode ( ) , 1 ) if definstance == ffi . NULL : raise LookupError ( "Instance '%s' not found" % name ) return Instance ( self . _env , definstance )
def has_firewall ( vlan ) : """Helper to determine whether or not a VLAN has a firewall . : param dict vlan : A dictionary representing a VLAN : returns : True if the VLAN has a firewall , false if it doesn ' t ."""
return bool ( vlan . get ( 'dedicatedFirewallFlag' , None ) or vlan . get ( 'highAvailabilityFirewallFlag' , None ) or vlan . get ( 'firewallInterfaces' , None ) or vlan . get ( 'firewallNetworkComponents' , None ) or vlan . get ( 'firewallGuestNetworkComponents' , None ) )
def tranz_context ( parser , token ) : """Templatetagish wrapper for Translator . transchoice ( )"""
tokens = token . split_contents ( ) parameters = { } for idx , token in enumerate ( tokens [ 1 : ] , start = 1 ) : if "=" in token : if token [ 0 : token . index ( '=' ) ] not in ( "domain" , "prefix" , "locale" ) : raise TemplateSyntaxError ( "Unexpected token {0} in tag {{tag_name}}" . format ...
def group_norm ( x , filters = None , num_groups = 8 , epsilon = 1e-5 ) : """Group normalization as in https : / / arxiv . org / abs / 1803.08494."""
x_shape = shape_list ( x ) if filters is None : filters = x_shape [ - 1 ] assert len ( x_shape ) == 4 assert filters % num_groups == 0 # Prepare variables . scale = tf . get_variable ( "group_norm_scale" , [ filters ] , initializer = tf . ones_initializer ( ) ) bias = tf . get_variable ( "group_norm_bias" , [ filte...
def add_watch_callback ( self , * args , ** kwargs ) : """Watch a key or range of keys and call a callback on every event . If timeout was declared during the client initialization and the watch cannot be created during that time the method raises a ` ` WatchTimedOut ` ` exception . : param key : key to wat...
try : return self . watcher . add_callback ( * args , ** kwargs ) except queue . Empty : raise exceptions . WatchTimedOut ( )
def run_estimators ( ns_run , estimator_list , simulate = False ) : """Calculates values of list of quantities ( such as the Bayesian evidence or mean of parameters ) for a single nested sampling run . Parameters ns _ run : dict Nested sampling run dict ( see data _ processing module docstring for more de...
logw = get_logw ( ns_run , simulate = simulate ) output = np . zeros ( len ( estimator_list ) ) for i , est in enumerate ( estimator_list ) : output [ i ] = est ( ns_run , logw = logw ) return output
def set_token ( self , token ) : """Set the token for the v20 context Args : token : The token used to access the v20 REST api"""
self . token = token self . set_header ( 'Authorization' , "Bearer {}" . format ( token ) )
def delete ( self , port , qos_policy = None ) : """Remove QoS rules from port . : param port : port object . : param qos _ policy : the QoS policy to be removed from port ."""
LOG . info ( "Deleting QoS policy %(qos_policy)s on port %(port)s" , dict ( qos_policy = qos_policy , port = port ) ) self . _utils . remove_port_qos_rule ( port [ "port_id" ] )
def add ( self , dn : str , mod_list : dict ) -> None : """Add a DN to the LDAP database ; See ldap module . Doesn ' t return a result if transactions enabled ."""
return self . _do_with_retry ( lambda obj : obj . add_s ( dn , mod_list ) )
def delete_by_field ( self , table : str , field : str , value : Any ) -> int : """Deletes all records where " field " is " value " ."""
sql = ( "DELETE FROM " + self . delimit ( table ) + " WHERE " + self . delimit ( field ) + "=?" ) return self . db_exec ( sql , value )
def bowtie ( self , name , fd = None , loge = None ) : """Generate a spectral uncertainty band ( bowtie ) for the given source . This will create an uncertainty band on the differential flux as a function of energy by propagating the errors on the global fit parameters . Note that this band only reflects th...
if loge is None : logemin = self . log_energies [ 0 ] logemax = self . log_energies [ - 1 ] loge = np . linspace ( logemin , logemax , 50 ) o = { 'energies' : 10 ** loge , 'log_energies' : loge , 'dnde' : np . zeros ( len ( loge ) ) * np . nan , 'dnde_lo' : np . zeros ( len ( loge ) ) * np . nan , 'dnde_hi'...
def create_lbaas_l7rule ( self , l7policy , body = None ) : """Creates rule for a certain L7 policy ."""
return self . post ( self . lbaas_l7rules_path % l7policy , body = body )
def log_predictive_density_sampling ( self , y_test , mu_star , var_star , Y_metadata = None , num_samples = 1000 ) : """Calculation of the log predictive density via sampling . . math : log p ( y _ { * } | D ) = log 1 / num _ samples prod ^ { S } _ { s = 1 } p ( y _ { * } | f _ { * s } ) f _ { * s } ~ p ( f ...
assert y_test . shape == mu_star . shape assert y_test . shape == var_star . shape assert y_test . shape [ 1 ] == 1 # Take samples of p ( f * | y ) # fi _ samples = np . random . randn ( num _ samples ) * np . sqrt ( var _ star ) + mu _ star fi_samples = np . random . normal ( mu_star , np . sqrt ( var_star ) , size = ...