signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_all_eip_addresses ( addresses = None , allocation_ids = None , region = None , key = None , keyid = None , profile = None ) : '''Get public addresses of some , or all EIPs associated with the current account . addresses ( list ) - Optional list of addresses . If provided , only the addresses associate...
return [ x . public_ip for x in _get_all_eip_addresses ( addresses , allocation_ids , region , key , keyid , profile ) ]
def update_value_from_mapping ( source_resource_attr_id , target_resource_attr_id , source_scenario_id , target_scenario_id , ** kwargs ) : """Using a resource attribute mapping , take the value from the source and apply it to the target . Both source and target scenarios must be specified ( and therefor must e...
user_id = int ( kwargs . get ( 'user_id' ) ) rm = aliased ( ResourceAttrMap , name = 'rm' ) # Check the mapping exists . mapping = db . DBSession . query ( rm ) . filter ( or_ ( and_ ( rm . resource_attr_id_a == source_resource_attr_id , rm . resource_attr_id_b == target_resource_attr_id ) , and_ ( rm . resource_attr_i...
def _initial_key ( self ) : """Construct an initial key for based on the lower range bounds or values on the key dimensions ."""
key = [ ] undefined = [ ] stream_params = set ( util . stream_parameters ( self . streams ) ) for kdim in self . kdims : if str ( kdim ) in stream_params : key . append ( None ) elif kdim . default : key . append ( kdim . default ) elif kdim . values : if all ( util . isnumeric ( v )...
def iterate ( matrix , expansion , inflation ) : """Run a single iteration ( expansion + inflation ) of the mcl algorithm : param matrix : The matrix to perform the iteration on : param expansion : Cluster expansion factor : param inflation : Cluster inflation factor"""
# Expansion matrix = expand ( matrix , expansion ) # Inflation matrix = inflate ( matrix , inflation ) return matrix
def rpc_get_account_balance ( self , address , token_type , ** con_info ) : """Get the balance of an address for a particular token type Returns the value on success Returns 0 if the balance is 0 , or if there is no address"""
if not check_account_address ( address ) : return { 'error' : 'Invalid address' , 'http_status' : 400 } if not check_token_type ( token_type ) : return { 'error' : 'Invalid token type' , 'http_status' : 400 } # must be b58 if is_c32_address ( address ) : address = c32ToB58 ( address ) db = get_db_state ( se...
def cull_edges ( self , stat , threshold = 0.5 , comparator = ge ) : """Delete edges whose stat > = ` ` threshold ` ` ( default 0.5 ) . Optional argument ` ` comparator ` ` will replace > = as the test for whether to cull . You can use the name of a stored function ."""
return self . cull_portals ( stat , threshold , comparator )
def read_dftbp ( filename ) : """Reads DFTB + structure files in gen format . Args : filename : name of the gen - file to be read Returns : atoms : an object of the phonopy . Atoms class , representing the structure found in filename"""
infile = open ( filename , 'r' ) lines = infile . readlines ( ) # remove any comments for ss in lines : if ss . strip ( ) . startswith ( '#' ) : lines . remove ( ss ) natoms = int ( lines [ 0 ] . split ( ) [ 0 ] ) symbols = lines [ 1 ] . split ( ) if ( lines [ 0 ] . split ( ) [ 1 ] . lower ( ) == 'f' ) : ...
def calculate_twi ( self , esfile , save_path , use_cache = True , do_edges = False , skip_uca_twi = False ) : """Calculates twi for supplied elevation file Parameters esfile : str Path to elevation file to be processed save _ path : str Root path to location where TWI will be saved . TWI will be saved in...
if os . path . exists ( os . path . join ( save_path , 'tile_edge.pkl' ) ) and self . tile_edge is None : with open ( os . path . join ( save_path , 'tile_edge.pkl' ) , 'r' ) as fid : self . tile_edge = cPickle . load ( fid ) elif self . tile_edge is None : self . tile_edge = TileEdgeFile ( self . elev_...
def hide_routemap_holder_route_map_content_set_weight_weight_value ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) hide_routemap_holder = ET . SubElement ( config , "hide-routemap-holder" , xmlns = "urn:brocade.com:mgmt:brocade-ip-policy" ) route_map = ET . SubElement ( hide_routemap_holder , "route-map" ) name_key = ET . SubElement ( route_map , "name" ) name_key . text = kwargs . pop ( 'name' ) ...
def current_livechat ( request ) : """Checks if a live chat is currently on the go , and add it to the request context . This is to allow the AskMAMA URL in the top - navigation to be redirected to the live chat object view consistently , and to make it available to the views and tags that depends on it .""...
result = { } livechat = LiveChat . chat_finder . get_current_live_chat ( ) if livechat : result [ 'live_chat' ] = { } result [ 'live_chat' ] [ 'current_live_chat' ] = livechat can_comment , reason_code = livechat . can_comment ( request ) result [ 'live_chat' ] [ 'can_render_comment_form' ] = can_commen...
def get_version ( package , url_pattern = URL_PATTERN ) : """Return version of package on pypi . python . org using json . Adapted from https : / / stackoverflow . com / a / 34366589"""
req = requests . get ( url_pattern . format ( package = package ) ) version = parse ( '0' ) if req . status_code == requests . codes . ok : # j = json . loads ( req . text . encode ( req . encoding ) ) j = req . json ( ) releases = j . get ( 'releases' , [ ] ) for release in releases : ver = parse (...
def _unzip ( self , src , dst , scene , force_unzip = False ) : """Unzip tar files"""
self . output ( "Unzipping %s - It might take some time" % scene , normal = True , arrow = True ) try : # check if file is already unzipped , skip if isdir ( dst ) and not force_unzip : self . output ( '%s is already unzipped.' % scene , normal = True , color = 'green' , indent = 1 ) return else...
def read_checking_config ( self ) : """Read configuration options in section " checking " ."""
section = "checking" self . read_int_option ( section , "threads" , min = - 1 ) self . config [ 'threads' ] = max ( 0 , self . config [ 'threads' ] ) self . read_int_option ( section , "timeout" , min = 1 ) self . read_int_option ( section , "aborttimeout" , min = 1 ) self . read_int_option ( section , "recursionlevel"...
def create ( ** kwargs ) : """Create and a return a specialized contract based on the given secType , or a general Contract if secType is not given ."""
secType = kwargs . get ( 'secType' , '' ) cls = { '' : Contract , 'STK' : Stock , 'OPT' : Option , 'FUT' : Future , 'CONTFUT' : ContFuture , 'CASH' : Forex , 'IND' : Index , 'CFD' : CFD , 'BOND' : Bond , 'CMDTY' : Commodity , 'FOP' : FuturesOption , 'FUND' : MutualFund , 'WAR' : Warrant , 'IOPT' : Warrant , 'BAG' : Bag...
def data_period_end_day ( self , value = None ) : """Corresponds to IDD Field ` data _ period _ end _ day ` Args : value ( str ) : value for IDD Field ` data _ period _ end _ day ` if ` value ` is None it will not be checked against the specification and is assumed to be a missing value Raises : ValueEr...
if value is not None : try : value = str ( value ) except ValueError : raise ValueError ( 'value {} need to be of type str ' 'for field `data_period_end_day`' . format ( value ) ) if ',' in value : raise ValueError ( 'value should not contain a comma ' 'for field `data_period_end_day...
def _init_coord_properties ( self ) : """Generates combinations of named coordinate values , mapping them to the internal array . For Example : x , xy , xyz , y , yy , zyx , etc"""
def gen_getter_setter_funs ( * args ) : indices = [ self . coords [ coord ] for coord in args ] def getter ( self ) : return tuple ( self . _array [ indices ] ) if len ( args ) > 1 else self . _array [ indices [ 0 ] ] def setter ( self , value ) : setitem ( self . _array , indices , value ) ...
def long_to_bytes ( n , blocksize = 0 ) : """Convert an integer to a byte string . In Python 3.2 + , use the native method instead : : > > > n . to _ bytes ( blocksize , ' big ' ) For instance : : > > > n = 80 > > > n . to _ bytes ( 2 , ' big ' ) b ' \x00 P ' If the optional : data : ` blocksize ` is ...
# after much testing , this algorithm was deemed to be the fastest s = b'' n = int ( n ) pack = struct . pack while n > 0 : s = pack ( '>I' , n & 0xffffffff ) + s n = n >> 32 # strip off leading zeros for i in range ( len ( s ) ) : if s [ i ] != b'\000' [ 0 ] : break else : # only happens when n = =...
def get_posts ( self , num = None , tag = None , private = False ) : """Get all the posts added to the blog . Args : num ( int ) : Optional . If provided , only return N posts ( sorted by date , most recent first ) . tag ( Tag ) : Optional . If provided , only return posts that have a specific tag . pri...
posts = self . posts if not private : posts = [ post for post in posts if post . public ] if tag : posts = [ post for post in posts if tag in post . tags ] if num : return posts [ : num ] return posts
def get_query_params ( self ) : """Get combined query parameters ( GET and POST ) ."""
params = self . request . query_params . copy ( ) params . update ( self . request . data ) return params
def get_projects ( format ) : """Gets projects data from fablabs . io ."""
projects_json = data_from_fablabs_io ( fablabs_io_projects_api_url_v0 ) projects = { } project_url = "https://www.fablabs.io/projects/" fablabs = get_labs ( format = "object" ) # Load all the FabLabs for i in projects_json [ "projects" ] : i = i [ "projects" ] current_project = Project ( ) current_project ....
def delete_public_ip ( access_token , subscription_id , resource_group , public_ip_name ) : '''Delete a public ip addresses associated with a resource group . Args : access _ token ( str ) : A valid Azure authentication token . subscription _ id ( str ) : Azure subscription id . resource _ group ( str ) : A...
endpoint = '' . join ( [ get_rm_endpoint ( ) , '/subscriptions/' , subscription_id , '/resourceGroups/' , resource_group , '/providers/Microsoft.Network/publicIPAddresses/' , public_ip_name , '?api-version=' , NETWORK_API ] ) return do_delete ( endpoint , access_token )
def normalize_slice ( length , index ) : "Fill in the Nones in a slice ."
is_int = False if isinstance ( index , int ) : is_int = True index = slice ( index , index + 1 ) if index . start is None : index = slice ( 0 , index . stop , index . step ) if index . stop is None : index = slice ( index . start , length , index . step ) if index . start < - 1 : # XXX why must this be ...
def changed ( self , node = None , allowcache = False ) : """Returns if the node is up - to - date with respect to the BuildInfo stored last time it was built . The default behavior is to compare it against our own previously stored BuildInfo , but the stored BuildInfo from another Node ( typically one in a R...
t = 0 if t : Trace ( 'changed(%s [%s], %s)' % ( self , classname ( self ) , node ) ) if node is None : node = self result = False bi = node . get_stored_info ( ) . binfo then = bi . bsourcesigs + bi . bdependsigs + bi . bimplicitsigs children = self . children ( ) diff = len ( children ) - len ( then ) if diff ...
def flat_git_tree_to_nested ( flat_tree , prefix = '' ) : '''Given an array in format : [ " 100644 " , " blob " , " ab3ce . . . " , " 748 " , " . gitignore " ] , [ " 100644 " , " blob " , " ab3ce . . . " , " 748 " , " path / to / thing " ] , Outputs in a nested format : " path " : " / " , " type " : " dir...
root = _make_empty_dir_dict ( prefix if prefix else '/' ) # Filter all descendents of this prefix descendent_files = [ info for info in flat_tree if os . path . dirname ( info [ PATH ] ) . startswith ( prefix ) ] # Figure out strictly leaf nodes of this tree ( can be immediately added as # children ) children_files = [...
def from_attribute ( attr ) : """Converts an attribute into a shadow attribute . : param attr : : class : ` MispAttribute ` instance to be converted : returns : Converted : class : ` MispShadowAttribute ` : example : > > > server = MispServer ( ) > > > event = server . events . get ( 12) > > > attr = ev...
assert attr is not MispAttribute prop = MispShadowAttribute ( ) prop . distribution = attr . distribution prop . type = attr . type prop . comment = attr . comment prop . value = attr . value prop . category = attr . category prop . to_ids = attr . to_ids return prop
def wrap ( cls , e , stack_depth = 0 ) : """ENSURE THE STACKTRACE AND CAUSAL CHAIN IS CAPTURED , PLUS ADD FEATURES OF Except : param e : AN EXCEPTION OF ANY TYPE : param stack _ depth : HOW MANY CALLS TO TAKE OFF THE TOP OF THE STACK TRACE : return : A Except OBJECT OF THE SAME"""
if e == None : return Null elif isinstance ( e , ( list , Except ) ) : return e elif is_data ( e ) : e . cause = unwraplist ( [ Except . wrap ( c ) for c in listwrap ( e . cause ) ] ) return Except ( ** e ) else : tb = getattr ( e , '__traceback__' , None ) if tb is not None : trace = _p...
def urlize_twitter ( text ) : """Replace # hashtag and @ username references in a tweet with HTML text ."""
html = TwitterText ( text ) . autolink . auto_link ( ) return mark_safe ( html . replace ( 'twitter.com/search?q=' , 'twitter.com/search/realtime/' ) )
def _saveGuiSettings ( self ) : """The base class doesn ' t implement this , so we will - save settings ( only GUI stuff , not task related ) to a file ."""
# Put the settings into a ConfigObj dict ( don ' t use a config - spec ) rcFile = self . _rcDir + os . sep + APP_NAME . lower ( ) + '.cfg' if os . path . exists ( rcFile ) : os . remove ( rcFile ) co = configobj . ConfigObj ( rcFile ) # can skip try - block , won ' t read file co [ 'showHelpInBrowser' ] = self . _s...
def get ( self , connect_app_sid ) : """Constructs a AuthorizedConnectAppContext : param connect _ app _ sid : The SID of the Connect App to fetch : returns : twilio . rest . api . v2010 . account . authorized _ connect _ app . AuthorizedConnectAppContext : rtype : twilio . rest . api . v2010 . account . auth...
return AuthorizedConnectAppContext ( self . _version , account_sid = self . _solution [ 'account_sid' ] , connect_app_sid = connect_app_sid , )
def flipGenotype ( genotype ) : """Flips a genotype . : param genotype : the genotype to flip . : type genotype : set : returns : the new flipped genotype ( as a : py : class : ` set ` ) . . testsetup : : from pyGenClean . DupSNPs . duplicated _ snps import flipGenotype . . doctest : : > > > flipGenot...
newGenotype = set ( ) for allele in genotype : if allele == "A" : newGenotype . add ( "T" ) elif allele == "C" : newGenotype . add ( "G" ) elif allele == "T" : newGenotype . add ( "A" ) elif allele == "G" : newGenotype . add ( "C" ) else : msg = "%(allele)s: u...
def shift_epoch ( delorean , direction , unit , count ) : """Gets the resulting epoch after a time shift of a Delorean Args : delorean : Delorean datetime instance to shift from . direction : String to shift time forwards or backwards . Valid values : ' last ' , ' next ' . unit : String of time period uni...
return int ( delorean . _shift_date ( direction , unit , count ) . epoch )
def key_file ( self , value ) : """gets / sets the certificate file"""
import os if os . path . isfile ( value ) : self . _keyfile = value
def build ( self ) : '''Builds Depoyed Classifier'''
if self . _clf is None : raise NeedToTrainExceptionBeforeDeployingException ( ) return DeployedClassifier ( self . _category , self . _term_doc_matrix . _category_idx_store , self . _term_doc_matrix . _term_idx_store , self . _term_doc_matrix_factory )
def sample_mgrid ( self , mgrid : np . array ) -> np . array : """Sample a mesh - grid array and return the result . The : any : ` sample _ ogrid ` method performs better as there is a lot of overhead when working with large mesh - grids . Args : mgrid ( numpy . ndarray ) : A mesh - grid array of points to ...
mgrid = np . ascontiguousarray ( mgrid , np . float32 ) if mgrid . shape [ 0 ] != self . dimensions : raise ValueError ( "mgrid.shape[0] must equal self.dimensions, " "%r[0] != %r" % ( mgrid . shape , self . dimensions ) ) out = np . ndarray ( mgrid . shape [ 1 : ] , np . float32 ) if mgrid . shape [ 1 : ] != out ....
def __replaceSpecialValues ( self , decisions ) : """Will replace special values in decisions array . Args : decisions ( array of array of str ) : Standard decision array format . Raises : ValueError : Row element don ' t have parent value . Returns : New decision array with updated values ."""
error = [ ] for row , line in enumerate ( decisions ) : if '.' in line : for i , element in enumerate ( line ) : if row == 0 : error . append ( "Row: {}colume: {}==> don't have parent value" . format ( str ( row ) . ljust ( 4 ) , str ( i ) . ljust ( 4 ) ) ) if element...
def find_by_project ( self , project , params = { } , ** options ) : """Returns the compact project membership records for the project . Parameters project : { Id } The project for which to fetch memberships . [ params ] : { Object } Parameters for the request - [ user ] : { String } If present , the user t...
path = "/projects/%s/project_memberships" % ( project ) return self . client . get_collection ( path , params , ** options )
def remove_token ( self , * , payer_id , credit_card_token_id ) : """This feature allows you to delete a tokenized credit card register . Args : payer _ id : credit _ card _ token _ id : Returns :"""
payload = { "language" : self . client . language . value , "command" : PaymentCommand . REMOVE_TOKEN . value , "merchant" : { "apiLogin" : self . client . api_login , "apiKey" : self . client . api_key } , "removeCreditCardToken" : { "payerId" : payer_id , "creditCardTokenId" : credit_card_token_id } , "test" : self ....
def load_anki_df ( language = 'deu' ) : """Load into a DataFrame statements in one language along with their translation into English > > > get _ data ( ' zsm ' ) . head ( 1) eng zsm 0 Are you new ? Awak baru ?"""
if os . path . isfile ( language ) : filepath = language lang = re . search ( '[a-z]{3}-eng/' , filepath ) . group ( ) [ : 3 ] . lower ( ) else : lang = ( language or 'deu' ) . lower ( ) [ : 3 ] filepath = os . path . join ( BIGDATA_PATH , '{}-eng' . format ( lang ) , '{}.txt' . format ( lang ) ) df = p...
def summary ( self , stream ) : """Produce coverage reports ."""
# Output coverage section header . if len ( self . node_descs ) == 1 : self . sep ( stream , '-' , 'coverage: %s' % '' . join ( self . node_descs ) ) else : self . sep ( stream , '-' , 'coverage' ) for node_desc in sorted ( self . node_descs ) : self . sep ( stream , ' ' , '%s' % node_desc ) # Produ...
def system ( self , command , dir = '' , stdin = '' , env = None , queue = None , max_time = None , stream = False , tags = None , id = None ) : """Execute a command : param command : command to execute ( with its arguments ) ex : ` ls - l / root ` : param dir : CWD of command : param stdin : Stdin data to fe...
parts = shlex . split ( command ) if len ( parts ) == 0 : raise ValueError ( 'invalid command' ) args = { 'name' : parts [ 0 ] , 'args' : parts [ 1 : ] , 'dir' : dir , 'stdin' : stdin , 'env' : env , } self . _system_chk . check ( args ) response = self . raw ( command = 'core.system' , arguments = args , queue = q...
def update_headers ( src_tree ) : """Main ."""
print ( "src tree" , src_tree ) for root , dirs , files in os . walk ( src_tree ) : py_files = fnmatch . filter ( files , "*.py" ) for f in py_files : print ( "checking" , f ) p = os . path . join ( root , f ) with open ( p ) as fh : contents = fh . read ( ) if suffix...
async def set_mode ( self , mode , timeout = OTGW_DEFAULT_TIMEOUT ) : """Set the operating mode to either " Gateway " mode ( : mode : = OTGW _ MODE _ GATEWAY or 1 ) or " Monitor " mode ( : mode : = OTGW _ MODE _ MONITOR or 0 ) , or use this method to reset the device ( : mode : = OTGW _ MODE _ RESET ) . Ret...
cmd = OTGW_CMD_MODE status = { } ret = await self . _wait_for_cmd ( cmd , mode , timeout ) if ret is None : return if mode is OTGW_MODE_RESET : self . _protocol . status = { } await self . get_reports ( ) await self . get_status ( ) return dict ( self . _protocol . status ) status [ OTGW_MODE ] = re...
def lat ( self ) : """Latitude of grid centers ( degrees North ) : getter : Returns the points of axis ` ` ' lat ' ` ` if availible in the process ' s domains . : type : array : raises : : exc : ` ValueError ` if no ` ` ' lat ' ` ` axis can be found ."""
try : for domname , dom in self . domains . items ( ) : try : thislat = dom . axes [ 'lat' ] . points except : pass return thislat except : raise ValueError ( 'Can\'t resolve a lat axis.' )
def _unpack_zip ( self , file_obj , path ) : """Unpack . zip archive in ` file _ obj ` to given ` path ` . Make sure , that it fits into limits ( see : attr : ` . _ max _ zipfiles ` for details ) . Args : file _ obj ( file ) : Opened file - like object . path ( str ) : Path into which the . zip will be unpa...
old_cwd = os . getcwd ( ) os . chdir ( path ) zip_obj = zipfile . ZipFile ( file_obj ) for cnt , zip_info in enumerate ( zip_obj . infolist ( ) ) : zip_obj . extract ( zip_info ) if cnt + 1 > self . max_zipfiles : os . chdir ( old_cwd ) msg = "Too many files in .zip " msg += "(self.max_z...
def plot_manifold_embedding ( self , algorithm = "lle" , path = "images" ) : """Draw the manifold embedding for the specified algorithm"""
_ , ax = plt . subplots ( figsize = ( 9 , 6 ) ) path = self . _make_path ( path , "s_curve_{}_manifold.png" . format ( algorithm ) ) oz = Manifold ( ax = ax , manifold = algorithm , target = 'continuous' , colors = 'nipy_spectral' ) oz . fit ( self . X , self . y ) oz . poof ( outpath = path )
def un ( source , wrapper = list , error_bad_lines = True ) : """Parse a text stream to TSV If the source is a string , it is converted to a line - iterable stream . If it is a file handle or other object , we assume that we can iterate over the lines in it . The result is a generator , and what it contains...
if isinstance ( source , six . string_types ) : source = six . StringIO ( source ) # Prepare source lines for reading rows = parse_lines ( source ) # Get columns if is_namedtuple ( wrapper ) : columns = wrapper . _fields wrapper = wrapper . _make else : columns = next ( rows , None ) if columns is n...
def _apply_section ( self , section , hosts ) : """Recursively find all the hosts that belong in or under a section and add the section ' s group name and variables to every host ."""
# Add the current group name to each host that this section covers . if section [ 'name' ] is not None : for hostname in self . _group_get_hostnames ( section [ 'name' ] ) : hosts [ hostname ] [ 'groups' ] . add ( section [ 'name' ] ) # Apply variables func_map = { "hosts" : self . _apply_section_hosts , "c...
def get_product ( config ) : """Get the / product / < product > resource from LTD Keeper ."""
product_url = config [ 'keeper_url' ] + '/products/{p}' . format ( p = config [ 'ltd_product' ] ) r = requests . get ( product_url ) if r . status_code != 200 : raise RuntimeError ( r . json ( ) ) product_info = r . json ( ) return product_info
def partial_transform ( self , traj ) : """Featurize an MD trajectory into a vector space via pairwise atom - atom distances Parameters traj : mdtraj . Trajectory A molecular dynamics trajectory to featurize . Returns features : np . ndarray , dtype = float , shape = ( n _ samples , n _ features ) A f...
d = md . geometry . compute_distances ( traj , self . pair_indices , periodic = self . periodic ) return d ** self . exponent
def check_alerts ( self ) : """Periodical check to issue due alerts"""
alerted = [ ] for alert_time , task in self . alerts . items ( ) : task_time = dateutil . parser . parse ( alert_time ) if task_time < get_time ( ) : self . log ( 'Alerting about task now:' , task ) address = objectmodels [ 'user' ] . find_one ( { 'uuid' : task . owner } ) . mail subject...
def _print_results ( file , status ) : """Print the download results . Args : file ( str ) : The filename . status ( str ) : The file download status ."""
file_color = c . Fore . GREEN status_color = c . Fore . RED if status == 'Success' : status_color = c . Fore . GREEN elif status == 'Skipped' : status_color = c . Fore . YELLOW print ( '{}{!s:<13}{}{!s:<35}{}{!s:<8}{}{}' . format ( c . Fore . CYAN , 'Downloading:' , file_color , file , c . Fore . CYAN , 'Status...
def thread_view ( request , pk ) : '''View an individual thread .'''
if request . is_ajax ( ) : if not request . user . is_authenticated ( ) : return HttpResponse ( json . dumps ( dict ( ) ) , content_type = "application/json" ) try : user_profile = UserProfile . objects . get ( user = request . user ) except UserProfile . DoesNotExist : return HttpRe...
def prepare_obsseries ( self , ramflag : bool = True ) -> None : """Call method | Node . prepare _ obsseries | of all handled | Node | objects ."""
for node in printtools . progressbar ( self ) : node . prepare_obsseries ( ramflag )
def configure_extensions ( app ) : """Configure application extensions"""
db . init_app ( app ) app . wsgi_app = ProxyFix ( app . wsgi_app ) assets . init_app ( app ) for asset in bundles : for ( name , bundle ) in asset . iteritems ( ) : assets . register ( name , bundle ) login_manager . login_view = 'frontend.login' login_manager . login_message_category = 'info' @ login_manag...
def hover ( self , locator , params = None , use_js = False , alt_loc = None , alt_params = None ) : """Context manager for hovering . Opens and closes the hover . Usage : with self . hover ( locator , params ) : / / do something with the hover : param locator : locator tuple or WebElement instance : pa...
# Open hover element = self . open_hover ( locator , params , use_js ) try : yield finally : # Close hover if alt_loc : element = alt_loc if not isinstance ( element , WebElement ) : element = self . get_visible_element ( alt_loc , alt_params ) self . close_hover ( element , use_...
def get_least_orbits ( atom_index , cell , site_symmetry , symprec = 1e-5 ) : """Find least orbits for a centering atom"""
orbits = _get_orbits ( atom_index , cell , site_symmetry , symprec ) mapping = np . arange ( cell . get_number_of_atoms ( ) ) for i , orb in enumerate ( orbits ) : for num in np . unique ( orb ) : if mapping [ num ] > mapping [ i ] : mapping [ num ] = mapping [ i ] return np . unique ( mapping )
def initialize ( self , io_loop ) : '''Start a Bokeh Server Tornado Application on a given Tornado IOLoop .'''
self . _loop = io_loop for app_context in self . _applications . values ( ) : app_context . _loop = self . _loop self . _clients = set ( ) self . _stats_job = PeriodicCallback ( self . _log_stats , self . _stats_log_frequency_milliseconds ) if self . _mem_log_frequency_milliseconds > 0 : self . _mem_job = Perio...
def incrbyfloat ( self , name , amount = 1.0 ) : """increment the value for key by value : float : param name : str the name of the redis key : param amount : int : return : Future ( )"""
with self . pipe as pipe : return pipe . incrbyfloat ( self . redis_key ( name ) , amount = amount )
def get_location ( self , location ) : """For an index location return a dict of the index and value . This is optimized for speed because it does not need to lookup the index location with a search . Also can accept relative indexing from the end of the SEries in standard python notation [ - 3 , - 2 , - 1] :...
return { self . index_name : self . _index [ location ] , self . data_name : self . _data [ location ] }
def rhochange ( self ) : """Updated cached c array when rho changes ."""
if self . opt [ 'HighMemSolve' ] and self . cri . Cd == 1 : self . c = sl . solvedbd_sm_c ( self . Df , np . conj ( self . Df ) , ( self . mu / self . rho ) * self . GHGf + 1.0 , self . cri . axisM )
def _on_timeout ( self , info : str = None ) -> None : """Timeout callback of _ HTTPConnection instance . Raise a ` HTTPTimeoutError ` when a timeout occurs . : info string key : More detailed timeout information ."""
self . _timeout = None error_message = "Timeout {0}" . format ( info ) if info else "Timeout" if self . final_callback is not None : self . _handle_exception ( HTTPTimeoutError , HTTPTimeoutError ( error_message ) , None )
def sdb_get_or_set_hash ( uri , opts , length = 8 , chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)' , utils = None ) : '''Check if value exists in sdb . If it does , return , otherwise generate a random string and store it . This can be used for storing secrets in a centralized place .'''
if not isinstance ( uri , string_types ) or not uri . startswith ( 'sdb://' ) : return False if utils is None : utils = salt . loader . utils ( opts ) ret = sdb_get ( uri , opts , utils = utils ) if ret is None : val = '' . join ( [ random . SystemRandom ( ) . choice ( chars ) for _ in range ( length ) ] ) ...
def start_continuous ( self , aichans , update_hz = 10 ) : """Begins a continuous analog generation , calling a provided function at a rate of 10Hz : param aichans : name of channel ( s ) to record ( analog input ) from : type aichans : list < str > : param update _ hz : Rate ( Hz ) at which to read data fr...
self . daq_lock . acquire ( ) self . ngenerated = 0 # number of stimuli presented during chart run npts = int ( self . aifs / update_hz ) # update display at 10Hz rate nchans = len ( aichans ) self . aitask = AITask ( aichans , self . aifs , npts * 5 * nchans ) self . aitask . register_callback ( self . _read_continuou...
def writefasta ( self , fname ) : """Write sequences to FASTA formatted file"""
f = open ( fname , "w" ) fa_str = "\n" . join ( [ ">%s\n%s" % ( id , self . _format_seq ( seq ) ) for id , seq in self . items ( ) ] ) f . write ( fa_str ) f . close ( )
def plot_state_map ( xall , yall , states , ax = None , ncontours = 100 , cmap = None , cbar = True , cax = None , cbar_label = 'state' , cbar_orientation = 'vertical' , nbins = 100 , mask = True , ** kwargs ) : """Plot a two - dimensional contour map of states by interpolating labels of scattered data on a grid ...
from matplotlib . cm import get_cmap nstates = int ( _np . max ( states ) + 1 ) cmap_ = get_cmap ( cmap , nstates ) fig , ax , misc = plot_contour ( xall , yall , states , ax = ax , cmap = cmap_ , ncontours = ncontours , vmin = None , vmax = None , levels = None , cbar = cbar , cax = cax , cbar_label = cbar_label , cba...
def next_paragraph_style ( self ) : """| _ ParagraphStyle | object representing the style to be applied automatically to a new paragraph inserted after a paragraph of this style . Returns self if no next paragraph style is defined . Assigning | None | or * self * removes the setting such that new paragraphs a...
next_style_elm = self . _element . next_style if next_style_elm is None : return self if next_style_elm . type != WD_STYLE_TYPE . PARAGRAPH : return self return StyleFactory ( next_style_elm )
def meminfo ( ) : '''Return the information in / proc / meminfo as a dictionary'''
meminfo = OrderedDict ( ) with open ( '/proc/meminfo' ) as f : for line in f : meminfo [ line . split ( ':' ) [ 0 ] ] = line . split ( ':' ) [ 1 ] . strip ( ) return meminfo
def raise_for_error ( self ) : """raise ` ShCmdError ` if the proc ' s return _ code is not 0 otherwise return self . . Usage : : > > > proc = shcmd . run ( " ls " ) . raise _ for _ error ( ) > > > proc . return _ code = = 0 True"""
if self . ok : return self tip = "running {0} @<{1}> error, return code {2}" . format ( " " . join ( self . cmd ) , self . cwd , self . return_code ) logger . error ( "{0}\nstdout:{1}\nstderr:{2}\n" . format ( tip , self . _stdout . decode ( "utf8" ) , self . _stderr . decode ( "utf8" ) ) ) raise ShCmdError ( self ...
def _footer_start_thread ( self , text , time ) : """Display given text in the footer . Clears after < time > seconds"""
footerwid = urwid . AttrMap ( urwid . Text ( text ) , 'footer' ) self . top . footer = footerwid load_thread = Thread ( target = self . _loading_thread , args = ( time , ) ) load_thread . daemon = True load_thread . start ( )
def add_annotation ( self , description , ** attrs ) : """Add an annotation to span . : type description : str : param description : A user - supplied message describing the event . The maximum length for the description is 256 bytes . : type attrs : kwargs : param attrs : keyworded arguments e . g . fail...
at = attributes . Attributes ( attrs ) self . add_time_event ( time_event_module . TimeEvent ( datetime . utcnow ( ) , time_event_module . Annotation ( description , at ) ) )
def _DeleteClientStats ( self , limit , retention_time , cursor = None ) : """Deletes up to ` limit ` ClientStats older than ` retention _ time ` ."""
cursor . execute ( "DELETE FROM client_stats WHERE timestamp < FROM_UNIXTIME(%s) LIMIT %s" , [ mysql_utils . RDFDatetimeToTimestamp ( retention_time ) , limit ] ) return cursor . rowcount
def __get_response_element_data ( self , key1 , key2 ) : """For each origin an elements object is created in the ouput . For each destination , an object is created inside elements object . For example , if there are 2 origins and 1 destination , 2 element objects with 1 object each are created . If there are ...
if not self . dict_response [ key1 ] [ key2 ] : l = self . response for i , orig in enumerate ( self . origins ) : self . dict_response [ key1 ] [ key2 ] [ orig ] = { } for j , dest in enumerate ( self . destinations ) : if l [ i ] [ 'elements' ] [ j ] [ 'status' ] == 'OK' : ...
def _set_openflow_state ( self , v , load = False ) : """Setter method for openflow _ state , mapped from YANG variable / openflow _ state ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ openflow _ state is considered as a private method . Backends looki...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = openflow_state . openflow_state , is_container = 'container' , presence = False , yang_name = "openflow-state" , rest_name = "openflow-state" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmetho...
def set_ds9 ( self , level = "PREF" ) : """Set the default values on the ds9 display ."""
self . set_zoom ( ) ds9_settings = config . read ( "DS9." + level ) for key in ds9_settings . keys ( ) : value = ds9_settings [ key ] cmd = key . replace ( "_" , " " ) self . ds9 . set ( "{} {}" . format ( cmd , value ) )
def dataset_from_rdf ( graph , dataset = None , node = None ) : '''Create or update a dataset from a RDF / DCAT graph'''
dataset = dataset or Dataset ( ) if node is None : # Assume first match is the only match node = graph . value ( predicate = RDF . type , object = DCAT . Dataset ) d = graph . resource ( node ) dataset . title = rdf_value ( d , DCT . title ) dataset . description = sanitize_html ( d . value ( DCT . description ) ) ...
def domain_get ( auth = None , ** kwargs ) : '''Get a single domain CLI Example : . . code - block : : bash salt ' * ' keystoneng . domain _ get name = domain1 salt ' * ' keystoneng . domain _ get name = b62e76fbeeff4e8fb77073f591cf211e'''
cloud = get_operator_cloud ( auth ) kwargs = _clean_kwargs ( ** kwargs ) return cloud . get_domain ( ** kwargs )
def export ( zone , path = None ) : '''Export the configuration from memory to stable storage . zone : string name of zone path : string path of file to export to CLI Example : . . code - block : : bash salt ' * ' zonecfg . export epyon salt ' * ' zonecfg . export epyon / zones / epyon . cfg'''
ret = { 'status' : True } # export zone res = __salt__ [ 'cmd.run_all' ] ( 'zonecfg -z {zone} export{path}' . format ( zone = zone , path = ' -f {0}' . format ( path ) if path else '' , ) ) ret [ 'status' ] = res [ 'retcode' ] == 0 ret [ 'message' ] = res [ 'stdout' ] if ret [ 'status' ] else res [ 'stderr' ] if ret [ ...
def read_backup ( self , p_todolist = None , p_timestamp = None ) : """Retrieves a backup for p _ timestamp or p _ todolist ( if p _ timestamp is not specified ) from backup file and sets timestamp , todolist , archive and label attributes to appropriate data from it ."""
if not p_timestamp : change_hash = hash_todolist ( p_todolist ) index = self . _get_index ( ) self . timestamp = index [ [ change [ 1 ] for change in index ] . index ( change_hash ) ] [ 0 ] else : self . timestamp = p_timestamp d = self . backup_dict [ self . timestamp ] self . todolist = TodoList ( d [...
def g_ ( self , X ) : """computes h ( ) : param X : : return :"""
if self . _interpol : if not hasattr ( self , '_g_interp' ) : if self . _lookup : x = self . _x_lookup g_x = self . _g_lookup else : x = np . linspace ( 0 , self . _max_interp_X , self . _num_interp_X ) g_x = self . _g ( x ) self . _g_interp = ...
def mean ( data ) : """Return the sample arithmetic mean of data ."""
# : http : / / stackoverflow . com / a / 27758326 n = len ( data ) if n < 1 : raise ValueError ( 'mean requires at least one data point' ) return sum ( data ) / n
def auth_view ( name , ** kwargs ) : """Shows an authorization group ' s content ."""
ctx = Context ( ** kwargs ) ctx . execute_action ( 'auth:group:view' , ** { 'storage' : ctx . repo . create_secure_service ( 'storage' ) , 'name' : name , } )
def _parse_libsvm_line ( line ) : """Parses a line in LIBSVM format into ( label , indices , values ) ."""
items = line . split ( None ) label = float ( items [ 0 ] ) nnz = len ( items ) - 1 indices = np . zeros ( nnz , dtype = np . int32 ) values = np . zeros ( nnz ) for i in xrange ( nnz ) : index , value = items [ 1 + i ] . split ( ":" ) indices [ i ] = int ( index ) - 1 values [ i ] = float ( value ) return ...
def from_py_func ( cls , func ) : """Create a ` ` CustomJS ` ` instance from a Python function . The function is translated to JavaScript using PScript ."""
from bokeh . util . deprecation import deprecated deprecated ( "'from_py_func' is deprecated and will be removed in an eventual 2.0 release. " "Use CustomJS directly instead." ) if not isinstance ( func , FunctionType ) : raise ValueError ( 'CustomJS.from_py_func needs function object.' ) pscript = import_required ...
def rsem_stats_table ( self ) : """Take the parsed stats from the rsem report and add them to the basic stats table at the top of the report"""
headers = OrderedDict ( ) headers [ 'alignable_percent' ] = { 'title' : '% Alignable' . format ( config . read_count_prefix ) , 'description' : '% Alignable reads' . format ( config . read_count_desc ) , 'max' : 100 , 'min' : 0 , 'suffix' : '%' , 'scale' : 'YlGn' } self . general_stats_addcols ( self . rsem_mapped_data...
def transition_complete ( self , pipeline_key ) : """Marks the given pipeline as complete . Does nothing if the pipeline is no longer in a state that can be completed . Args : pipeline _ key : db . Key of the _ PipelineRecord that has completed ."""
def txn ( ) : pipeline_record = db . get ( pipeline_key ) if pipeline_record is None : logging . warning ( 'Tried to mark pipeline ID "%s" as complete but it does not exist.' , pipeline_key . name ( ) ) raise db . Rollback ( ) if pipeline_record . status not in ( _PipelineRecord . WAITING , ...
def output ( output_id , name , value_class = NumberValue ) : """Add output to controller"""
def _init ( ) : return value_class ( name , input_id = output_id , is_input = False , index = - 1 ) def _decorator ( cls ) : setattr ( cls , output_id , _init ( ) ) return cls return _decorator
def _get_case_file_paths ( tmp_dir , case , training_fraction = 0.95 ) : """Obtain a list of image paths corresponding to training or eval case . Args : tmp _ dir : str , the root path to which raw images were written , at the top level having meta / and raw / subdirs . case : bool , whether obtaining file ...
paths = tf . gfile . Glob ( "%s/*.jpg" % tmp_dir ) if not paths : raise ValueError ( "Search of tmp_dir (%s) " % tmp_dir , "for subimage paths yielded an empty list, " , "can't proceed with returning training/eval split." ) split_index = int ( math . floor ( len ( paths ) * training_fraction ) ) if split_index >= l...
def sparse_grid ( func , order , dim = None , skew = None ) : """Smolyak sparse grid constructor . Args : func ( : py : data : typing . Callable ) : Function that takes a single argument ` ` order ` ` of type ` ` numpy . ndarray ` ` and with ` ` order . shape = ( dim , ) ` ` order ( int , numpy . ndarray ...
if not isinstance ( order , int ) : orders = numpy . array ( order ) . flatten ( ) dim = orders . size m_order = int ( numpy . min ( orders ) ) skew = [ order - m_order for order in orders ] return sparse_grid ( func , m_order , dim , skew ) abscissas , weights = [ ] , [ ] bindex = chaospy . bertran...
def parse_csv_headers ( dataset_id ) : """Return the first row of a CSV as a list of headers ."""
data = Dataset . objects . get ( pk = dataset_id ) with open ( data . dataset_file . path , 'r' ) as datasetFile : csvReader = reader ( datasetFile , delimiter = ',' , quotechar = '"' ) headers = next ( csvReader ) # print headers return headers
def x_parse_error ( err , content , source ) : """Explains the specified ParseError instance to show the user where the error happened in their XML ."""
lineno , column = err . position if "<doc>" in content : # Adjust the position since we are taking the < doc > part out of the tags # since we may have put that in ourselves . column -= 5 start = lineno - ( 1 if lineno == 1 else 2 ) lines = [ ] tcontent = content . replace ( "<doc>" , "" ) . replace ( "</doc>" , ""...
def update_tags ( self , image_id , new_tags ) : """Update an Image tags . : param new _ tags : list of tags that will replace currently assigned tags"""
# Do not add : param list in the docstring above until this is solved : # https : / / github . com / sphinx - doc / sphinx / issues / 2549 old_image = self . get ( image_id ) old_tags = frozenset ( old_image . tags ) new_tags = frozenset ( new_tags ) to_add = list ( new_tags - old_tags ) to_remove = list ( old_tags - n...
def rate_timestamp ( self , rate_timestamp ) : """Force the rate _ timestamp to be a datetime : param rate _ timestamp : : return :"""
if rate_timestamp is not None : if isinstance ( rate_timestamp , ( str , type_check ) ) : rate_timestamp = parse ( rate_timestamp ) . replace ( tzinfo = pytz . utc ) if type ( rate_timestamp ) == date : rate_timestamp = datetime . combine ( rate_timestamp , datetime . min . time ( ) ) . replace ...
def _fake_enumerateinstancenames ( self , namespace , ** params ) : """Implements a server responder for : meth : ` ~ pywbem . WBEMConnection . EnumerateInstanceNames ` Get instance names for instances that match the path define by ` ClassName ` and returns a list of the names ."""
cname = params [ 'ClassName' ] assert isinstance ( cname , CIMClassName ) cname = cname . classname # Validate namespace instance_repo = self . _get_instance_repo ( namespace ) clns = self . _get_subclass_list_for_enums ( cname , namespace ) inst_paths = [ inst . path for inst in instance_repo if inst . path . classnam...
def raise_412 ( instance , msg = None ) : """Abort the current request with a 412 ( Precondition Failed ) response code . If the message is given it ' s output as an error message in the response body ( correctly converted to the requested MIME type ) . : param instance : Resource instance ( used to access th...
instance . response . status = 412 if msg : instance . response . body_raw = { 'error' : msg } raise ResponseException ( instance . response )
def _GetValueAsObject ( self , property_value ) : """Retrieves the property value as a Python object . Args : property _ value ( pyolecf . property _ value ) : OLECF property value . Returns : object : property value as a Python object ."""
if property_value . type == pyolecf . value_types . BOOLEAN : return property_value . data_as_boolean if property_value . type in self . _INTEGER_TYPES : return property_value . data_as_integer if property_value . type in self . _STRING_TYPES : return property_value . data_as_string try : data = propert...
def ensure ( data_type , check_value , default_value = None ) : """function to ensure the given check value is in the given data type , if yes , return the check value directly , otherwise return the default value : param data _ type : different data type : can be int , str , list , tuple etc , must be python...
if default_value is not None and not isinstance ( default_value , data_type ) : raise ValueError ( "default_value must be the value in the given data " "type." ) elif isinstance ( check_value , data_type ) : return check_value try : new_value = data_type ( check_value ) except : return default_value ret...
def logical_raid_levels ( self ) : """Gets the raid level for each logical volume : returns the set of list of raid levels configured"""
lg_raid_lvls = set ( ) for member in self . get_members ( ) : lg_raid_lvls . update ( member . logical_drives . logical_raid_levels ) return lg_raid_lvls
def _clean_data ( self , str_value , file_data , obj_value ) : """This overwrite is neccesary for work with multivalues"""
str_value = str_value or None obj_value = obj_value or None return ( str_value , None , obj_value )
def write_block ( self , block , data , erase = True ) : """Write an 8 - byte data block at address ( block * 8 ) . The target bytes are zero ' d first if * erase * is True ."""
if block < 0 or block > 255 : raise ValueError ( "invalid block number" ) log . debug ( "write block {0}" . format ( block ) ) cmd = "\x54" if erase is True else "\x1B" cmd = cmd + chr ( block ) + data + self . uid rsp = self . transceive ( cmd ) if len ( rsp ) < 9 : raise Type1TagCommandError ( RESPONSE_ERROR ...
def get_dag_params ( self ) -> Dict [ str , Any ] : """Merges default config with dag config , sets dag _ id , and extropolates dag _ start _ date : returns : dict of dag parameters"""
try : dag_params : Dict [ str , Any ] = utils . merge_configs ( self . dag_config , self . default_config ) except Exception as e : raise Exception ( f"Failed to merge config with default config, err: {e}" ) dag_params [ "dag_id" ] : str = self . dag_name try : # ensure that default _ args dictionary contains k...