signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def retrieve_remote_profile ( id : str ) -> Optional [ Profile ] : """High level retrieve profile method . Retrieve the profile from a remote location , using protocol based on the given ID ."""
protocol = identify_protocol_by_id ( id ) utils = importlib . import_module ( f"federation.utils.{protocol.PROTOCOL_NAME}" ) return utils . retrieve_and_parse_profile ( id )
def run ( self ) : """Starts a development server for the zengine application"""
from zengine . wf_daemon import run_workers , Worker worker_count = int ( self . manager . args . workers or 1 ) if not self . manager . args . daemonize : print ( "Starting worker(s)" ) if worker_count > 1 or self . manager . args . autoreload : run_workers ( worker_count , self . manager . args . paths . spli...
def parse_cov ( cov_table , scaffold2genome ) : """calculate genome coverage from scaffold coverage table"""
size = { } # size [ genome ] = genome size mapped = { } # mapped [ genome ] [ sample ] = mapped bases # parse coverage files for line in open ( cov_table ) : line = line . strip ( ) . split ( '\t' ) if line [ 0 ] . startswith ( '#' ) : samples = line [ 1 : ] samples = [ i . rsplit ( '/' , 1 ) [ ...
def cells_dn_meta ( workbook , sheet , row , col , final_dict ) : """Traverse all cells in a column moving downward . Primarily created for the metadata sheet , but may use elsewhere . Check the cell title , and switch it to . : param obj workbook : : param str sheet : : param int row : : param int col : ...
logger_excel . info ( "enter cells_dn_meta" ) row_loop = 0 pub_cases = [ 'id' , 'year' , 'author' , 'journal' , 'issue' , 'volume' , 'title' , 'pages' , 'reportNumber' , 'abstract' , 'alternateCitation' ] geo_cases = [ 'latMin' , 'lonMin' , 'lonMax' , 'latMax' , 'elevation' , 'siteName' , 'location' ] funding_cases = [...
def libvlc_media_player_get_state ( p_mi ) : '''Get current movie state . @ param p _ mi : the Media Player . @ return : the current state of the media player ( playing , paused , . . . ) See libvlc _ state _ t .'''
f = _Cfunctions . get ( 'libvlc_media_player_get_state' , None ) or _Cfunction ( 'libvlc_media_player_get_state' , ( ( 1 , ) , ) , None , State , MediaPlayer ) return f ( p_mi )
def set_json_item ( key , value ) : """manipulate json data on the fly"""
data = get_json ( ) data [ key ] = value request = get_request ( ) request [ "BODY" ] = json . dumps ( data )
def obfuscatable_class ( tokens , index , ** kwargs ) : """Given a list of * tokens * and an * index * ( representing the current position ) , returns the token string if it is a class name that can be safely obfuscated ."""
tok = tokens [ index ] token_type = tok [ 0 ] token_string = tok [ 1 ] if index > 0 : prev_tok = tokens [ index - 1 ] else : # Pretend it ' s a newline ( for simplicity ) prev_tok = ( 54 , '\n' , ( 1 , 1 ) , ( 1 , 2 ) , '#\n' ) prev_tok_string = prev_tok [ 1 ] if token_type != tokenize . NAME : return None ...
def extract_views_from_urlpatterns ( self , urlpatterns , base = '' , namespace = None ) : """Return a list of views from a list of urlpatterns . Each object in the returned list is a three - tuple : ( view _ func , regex , name )"""
views = [ ] for p in urlpatterns : if isinstance ( p , ( URLPattern , RegexURLPattern ) ) : try : if not p . name : name = p . name elif namespace : name = '{0}:{1}' . format ( namespace , p . name ) else : name = p . name ...
def check_redis ( ) : """Redis checks the connection It displays on the screen whether or not you have a connection ."""
from pyoko . db . connection import cache from redis . exceptions import ConnectionError try : cache . ping ( ) print ( CheckList . OKGREEN + "{0}Redis is working{1}" + CheckList . ENDC ) except ConnectionError as e : print ( __ ( u"{0}Redis is not working{1} " ) . format ( CheckList . FAIL , CheckList . EN...
def _prep_noise_interpolants ( self ) : """Construct interpolated sensitivity curves This will construct the interpolated sensitivity curves using scipy . interpolate . interp1d . It will add wd noise if that is requested . Raises : ValueError : ` ` len ( noise _ type _ in ) ! = len ( sensitivity _ curves...
noise_lists = { } self . noise_interpolants = { } if isinstance ( self . sensitivity_curves , str ) : self . sensitivity_curves = [ self . sensitivity_curves ] if isinstance ( self . noise_type_in , list ) : if len ( self . noise_type_in ) != len ( self . sensitivity_curves ) : raise ValueError ( 'noise...
def windowed_tajima_d ( pos , ac , size = None , start = None , stop = None , step = None , windows = None , min_sites = 3 ) : """Calculate the value of Tajima ' s D in windows over a single chromosome / contig . Parameters pos : array _ like , int , shape ( n _ items , ) Variant positions , using 1 - based...
# check inputs if not isinstance ( pos , SortedIndex ) : pos = SortedIndex ( pos , copy = False ) if not hasattr ( ac , 'count_segregating' ) : ac = AlleleCountsArray ( ac , copy = False ) # assume number of chromosomes sampled is constant for all variants n = ac . sum ( axis = 1 ) . max ( ) # calculate constan...
def goto_line ( self ) : """Shows the * go to line dialog * and go to the selected line ."""
helper = TextHelper ( self ) line , result = DlgGotoLine . get_line ( self , helper . current_line_nbr ( ) , helper . line_count ( ) ) if not result : return return helper . goto_line ( line , move = True )
def run ( users , hosts , func , ** kwargs ) : """Convenience function that creates an Exscript . Queue instance , adds the given accounts , and calls Queue . run ( ) with the given hosts and function as an argument . If you also want to pass arguments to the given function , you may use util . decorator . ...
attempts = kwargs . get ( "attempts" , 1 ) if "attempts" in kwargs : del kwargs [ "attempts" ] queue = Queue ( ** kwargs ) queue . add_account ( users ) queue . run ( hosts , func , attempts ) queue . destroy ( )
def get_bewit ( resource ) : """Returns a bewit identifier for the resource as a string . : param resource : Resource to generate a bewit for : type resource : ` mohawk . base . Resource `"""
if resource . method != 'GET' : raise ValueError ( 'bewits can only be generated for GET requests' ) if resource . nonce != '' : raise ValueError ( 'bewits must use an empty nonce' ) mac = calculate_mac ( 'bewit' , resource , None , ) if isinstance ( mac , six . binary_type ) : mac = mac . decode ( 'ascii' ...
def is_subdomains_enabled ( blockstack_opts ) : """Can we do subdomain operations ?"""
if not is_atlas_enabled ( blockstack_opts ) : log . debug ( "Subdomains are disabled" ) return False if 'subdomaindb_path' not in blockstack_opts : log . debug ( "Subdomains are disabled: no 'subdomaindb_path' path set" ) return False return True
def register_postloop_hook ( self , func : Callable [ [ None ] , None ] ) -> None : """Register a function to be called at the end of the command loop ."""
self . _validate_prepostloop_callable ( func ) self . _postloop_hooks . append ( func )
def render_html_attributes ( ** kwargs ) : """Returns a string representation of attributes for html entities : param kwargs : attributes and values : return : a well - formed string representation of attributes"""
attr = list ( ) if kwargs : attr = [ '{}="{}"' . format ( key , val ) for key , val in kwargs . items ( ) ] return " " . join ( attr ) . replace ( "css_class" , "class" )
def reward_bonus ( self , assignment_id , amount , reason ) : """Print out bonus info for the assignment"""
logger . info ( 'Award ${} for assignment {}, with reason "{}"' . format ( amount , assignment_id , reason ) )
def get_command ( self ) : """Get a line of text that was received from the DE . The class ' s cmd _ ready attribute will be true if lines are available ."""
cmd = None count = len ( self . command_list ) if count > 0 : cmd = self . command_list . pop ( 0 ) # # If that was the last line , turn off lines _ pending if count == 1 : self . cmd_ready = False return cmd
async def execute ( self , run_id : str = None , code : str = None , mode : str = 'query' , opts : dict = None ) : '''Executes a code snippet directly in the compute session or sends a set of build / clean / execute commands to the compute session . For more details about using this API , please refer : doc : `...
opts = opts if opts is not None else { } params = { } if self . owner_access_key : params [ 'owner_access_key' ] = self . owner_access_key if mode in { 'query' , 'continue' , 'input' } : assert code is not None , 'The code argument must be a valid string even when empty.' rqst = Request ( self . session , '...
def createCitation ( self , multiCite = False ) : """Overwriting the general [ citation creator ] ( . / ExtendedRecord . html # metaknowledge . ExtendedRecord . createCitation ) to deal with scopus weirdness . Creates a citation string , using the same format as other WOS citations , for the [ Record ] ( . / Reco...
# Need to put the import here to avoid circular import issues from . . citation import Citation valsStr = '' if multiCite : auths = [ ] for auth in self . get ( "authorsShort" , [ ] ) : auths . append ( auth . replace ( ',' , '' ) ) else : if self . get ( "authorsShort" , False ) : valsStr +...
def numpy ( ) : '''Lazily import the numpy module'''
if LazyImport . numpy_module is None : try : LazyImport . numpy_module = __import__ ( 'numpypy' ) except ImportError : try : LazyImport . numpy_module = __import__ ( 'numpy' ) except ImportError : raise ImportError ( 'The numpy module is required' ) return LazyImp...
def join_gates ( * gates : Gate ) -> Gate : """Direct product of two gates . Qubit count is the sum of each gate ' s bit count ."""
vectors = [ gate . vec for gate in gates ] vec = reduce ( outer_product , vectors ) return Gate ( vec . tensor , vec . qubits )
def remove_parameter ( self , twig = None , ** kwargs ) : """Remove a : class : ` Parameter ` from the ParameterSet Note : removing Parameters from a ParameterSet will not remove them from any parent ParameterSets ( including the : class : ` phoebe . frontend . bundle . Bundle ` ) : parameter str twig : the...
param = self . get ( twig = twig , ** kwargs ) self . _remove_parameter ( param )
def compose ( self ) : """get CGR of reaction reagents will be presented as unchanged molecules : return : CGRContainer"""
rr = self . __reagents + self . __reactants if rr : if not all ( isinstance ( x , ( MoleculeContainer , CGRContainer ) ) for x in rr ) : raise TypeError ( 'Queries not composable' ) r = reduce ( or_ , rr ) else : r = MoleculeContainer ( ) if self . __products : if not all ( isinstance ( x , ( Mo...
def handle_get_passphrase ( self , conn , _ ) : """Allow simple GPG symmetric encryption ( using a passphrase ) ."""
p1 = self . client . device . ui . get_passphrase ( 'Symmetric encryption:' ) p2 = self . client . device . ui . get_passphrase ( 'Re-enter encryption:' ) if p1 == p2 : result = b'D ' + util . assuan_serialize ( p1 . encode ( 'ascii' ) ) keyring . sendline ( conn , result , confidential = True ) else : log ...
def create_and_setup_cors ( self , restapi , resource , uri , depth , config ) : """Set up the methods , integration responses and method responses for a given API Gateway resource ."""
if config is True : config = { } method_name = "OPTIONS" method = troposphere . apigateway . Method ( method_name + str ( depth ) ) method . RestApiId = troposphere . Ref ( restapi ) if type ( resource ) is troposphere . apigateway . Resource : method . ResourceId = troposphere . Ref ( resource ) else : met...
def getPayloadStruct ( self , attributes , objType ) : """Function getPayloadStruct Get the payload structure to do a creation or a modification @ param attribute : The data @ param objType : SubItem type ( e . g : hostgroup for hostgroup _ class ) @ return RETURN : the payload"""
payload = { self . payloadObj : attributes , objType + "_class" : { self . payloadObj : attributes } } return payload
def plot_bargraph ( self , rank = "auto" , normalize = "auto" , top_n = "auto" , threshold = "auto" , title = None , xlabel = None , ylabel = None , tooltip = None , return_chart = False , haxis = None , legend = "auto" , label = None , ) : """Plot a bargraph of relative abundance of taxa for multiple samples . P...
if rank is None : raise OneCodexException ( "Please specify a rank or 'auto' to choose automatically" ) if not ( threshold or top_n ) : raise OneCodexException ( "Please specify at least one of: threshold, top_n" ) if top_n == "auto" and threshold == "auto" : top_n = 10 threshold = None elif top_n == "a...
def inferheader ( lines , comments = None , metadata = None , verbosity = DEFAULT_VERBOSITY ) : """Infers header from a CSV or other tab - delimited file . This is essentially small extension of the csv . Sniffer . has _ header algorithm . provided in the Python csv module . First , it checks to see whether a ...
if ( ( comments is None ) and metadata and ( 'comments' in metadata . keys ( ) ) ) : comments = metadata [ 'comments' ] if ( comments is None ) : comments = '#' if ( 'metametadata' in metadata . keys ( ) ) : mmd = metadata [ 'metametadata' ] cc = 1 + max ( [ v if isinstance ( v , int ) else max ( v ) fo...
def send ( self , data ) : """Send data over scgi to URL and get response ."""
start = time . time ( ) try : scgi_resp = '' . join ( self . transport . send ( _encode_payload ( data ) ) ) finally : self . latency = time . time ( ) - start resp , self . resp_headers = _parse_response ( scgi_resp ) return resp
def do_format ( value , * args , ** kwargs ) : """Apply python string formatting on an object : . . sourcecode : : jinja { { " % s - % s " | format ( " Hello ? " , " Foo ! " ) } } - > Hello ? - Foo !"""
if args and kwargs : raise FilterArgumentError ( 'can\'t handle positional and keyword ' 'arguments at the same time' ) return soft_unicode ( value ) % ( kwargs or args )
def get_activities_for_objectives ( self , objective_ids = None ) : """Gets the activities for the given objectives . In plenary mode , the returned list contains all of the activities specified in the objective Id list , in the order of the list , including duplicates , or an error results if a course offe...
if objective_ids is None : raise NullArgument ( ) # Should also check if objective _ id exists ? activities = [ ] for i in objective_ids : acts = None url_path = construct_url ( 'activities' , bank_id = self . _catalog_idstr , obj_id = i ) try : acts = json . loads ( self . _get_request ( url_pa...
def hardware_custom_profile_kap_custom_profile_name ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) hardware = ET . SubElement ( config , "hardware" , xmlns = "urn:brocade.com:mgmt:brocade-hardware" ) custom_profile = ET . SubElement ( hardware , "custom-profile" ) kap_custom_profile = ET . SubElement ( custom_profile , "kap-custom-profile" ) name = ET . SubElement ( kap_custom_prof...
def effect_emd ( d1 , d2 ) : """Compute the EMD between two effect repertoires . Because the nodes are independent , the EMD between effect repertoires is equal to the sum of the EMDs between the marginal distributions of each node , and the EMD between marginal distribution for a node is the absolute diffe...
return sum ( abs ( marginal_zero ( d1 , i ) - marginal_zero ( d2 , i ) ) for i in range ( d1 . ndim ) )
def config_managed_object ( p_dn , p_class_id , class_id , mo_config , mo_dn , handle = None , delete = True ) : """Configure the specified MO in UCS Manager . : param uuid : MO config : param p _ dn : parent MO DN : param p _ class _ id : parent MO class ID : param class _ id : MO class ID : param MO con...
if handle is None : handle = self . handle try : result = handle . AddManagedObject ( None , classId = class_id , params = mo_config , modifyPresent = True , dumpXml = YesOrNo . FALSE ) return result except UcsException as ex : print ( _ ( "Cisco client exception: %(msg)s" ) , { 'msg' : ex } ) raise...
def make_initial_state ( project , stack_length ) : """: return : an initial state with a symbolic stack and good options for rop"""
initial_state = project . factory . blank_state ( add_options = { options . AVOID_MULTIVALUED_READS , options . AVOID_MULTIVALUED_WRITES , options . NO_SYMBOLIC_JUMP_RESOLUTION , options . CGC_NO_SYMBOLIC_RECEIVE_LENGTH , options . NO_SYMBOLIC_SYSCALL_RESOLUTION , options . TRACK_ACTION_HISTORY } , remove_options = opt...
def p_else_single ( p ) : '''else _ single : empty | ELSE statement'''
if len ( p ) == 3 : p [ 0 ] = ast . Else ( p [ 2 ] , lineno = p . lineno ( 1 ) )
def register_callback ( self , callback , remove = False ) : """( Un ) Register a callback Parameters callback : method handle Method to be registered or unregistered . remove = False : bool Whether to unregister the callback ."""
# ( Un ) Register the callback . if remove and callback in self . callbacks : self . callbacks . remove ( callback ) elif not remove and callback not in self . callbacks : self . callbacks . append ( callback )
def multi_bulk ( self , args ) : '''Multi bulk encoding for list / tuple ` ` args ` `'''
return null_array if args is None else b'' . join ( self . _pack ( args ) )
def update ( self , items ) : """Updates the dependencies with the given items . Note that this does not reset all previously - evaluated and cached nodes . : param items : Iterable or dictionary in the format ` ( dependent _ item , dependencies ) ` . : type items : collections . Iterable"""
for item , parents in _iterate_dependencies ( items ) : dep = self . _deps [ item ] merge_list ( dep . parent , parents )
def _parse_container ( tokens , index , for_or_if = None ) : """Parse a high - level container , such as a list , tuple , etc ."""
# Store the opening bracket . items = [ Atom ( Token ( * tokens [ index ] ) ) ] index += 1 num_tokens = len ( tokens ) while index < num_tokens : tok = Token ( * tokens [ index ] ) if tok . token_string in ',)]}' : # First check if we ' re at the end of a list comprehension or # if - expression . Don ' t ad...
def _set_fcoe_fip_keep_alive ( self , v , load = False ) : """Setter method for fcoe _ fip _ keep _ alive , mapped from YANG variable / fcoe / fcoe _ fabric _ map / fcoe _ fip _ keep _ alive ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ fcoe _ fip _ keep...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = fcoe_fip_keep_alive . fcoe_fip_keep_alive , is_container = 'container' , presence = False , yang_name = "fcoe-fip-keep-alive" , rest_name = "keep-alive" , parent = self , path_helper = self . _path_helper , extmethods = self ...
def locate_key ( self , k1 , k2 = None ) : """Get index location for the requested key . Parameters k1 : object Level 1 key . k2 : object , optional Level 2 key . Returns loc : int or slice Location of requested key ( will be slice if there are duplicate entries ) . Examples > > > import allel...
loc1 = self . l1 . locate_key ( k1 ) if k2 is None : return loc1 if isinstance ( loc1 , slice ) : offset = loc1 . start try : loc2 = SortedIndex ( self . l2 [ loc1 ] , copy = False ) . locate_key ( k2 ) except KeyError : # reraise with more information raise KeyError ( k1 , k2 ) else...
def scale ( text = "" , value = 0 , min = 0 , max = 100 , step = 1 , draw_value = True , title = "" , width = DEFAULT_WIDTH , height = DEFAULT_HEIGHT , timeout = None ) : """Select a number with a range widget : param text : text inside window : type text : str : param value : current value : type value : i...
dialog = ZScale ( text , value , min , max , step , draw_value , title , width , height , timeout ) dialog . run ( ) return dialog . response
def fit ( self , X , y , sample_weight = None , eval_set = None , eval_metric = None , early_stopping_rounds = None , verbose = True ) : # pylint : disable = attribute - defined - outside - init , arguments - differ """Fit gradient boosting classifier Parameters X : array _ like Feature matrix y : array _ l...
evals_result = { } self . classes_ = list ( np . unique ( y ) ) self . n_classes_ = len ( self . classes_ ) if self . n_classes_ > 2 : # Switch to using a multiclass objective in the underlying XGB instance self . objective = "multi:softprob" xgb_options = self . get_xgb_params ( ) xgb_options [ 'num_class'...
def hacking_assert_is_none ( logical_line , noqa ) : """Use assertIs ( Not ) None to check for None in assertions . Okay : self . assertEqual ( ' foo ' , ' bar ' ) Okay : self . assertNotEqual ( ' foo ' , { } . get ( ' bar ' , None ) ) Okay : self . assertIs ( ' foo ' , ' bar ' ) Okay : self . assertIsNot (...
if noqa : return for func_name in ( 'assertEqual' , 'assertIs' , 'assertNotEqual' , 'assertIsNot' ) : try : start = logical_line . index ( '.%s(' % func_name ) + 1 except ValueError : continue checker = NoneArgChecker ( func_name ) checker . visit ( ast . parse ( logical_line ) ) ...
def check_member_pool ( self , member , pool_name ) : '''Check a pool member exists in a specific pool'''
members = self . bigIP . LocalLB . Pool . get_member ( pool_names = [ pool_name ] ) [ 0 ] for mem in members : if member == mem . address : return True return False
def fetch ( cls , id , service = None , endpoint = None , * args , ** kwargs ) : """Customize fetch because it lives on a special endpoint ."""
if service is None and endpoint is None : raise InvalidArguments ( service , endpoint ) if endpoint is None : sid = service [ 'id' ] if isinstance ( service , Entity ) else service endpoint = 'services/{0}/integrations' . format ( sid ) return getattr ( Entity , 'fetch' ) . __func__ ( cls , id , endpoint = ...
def add_providers ( self , * providers : Type [ BaseProvider ] ) -> None : """Add a lot of custom providers to Generic ( ) object . : param providers : Custom providers . : return : None"""
for provider in providers : self . add_provider ( provider )
def floating_ip_pool_list ( self ) : '''List all floating IP pools . . versionadded : : 2016.3.0'''
nt_ks = self . compute_conn pools = nt_ks . floating_ip_pools . list ( ) response = { } for pool in pools : response [ pool . name ] = { 'name' : pool . name , } return response
def note_create_update ( self , post_id = None , coor_x = None , coor_y = None , width = None , height = None , is_active = None , body = None , note_id = None ) : """Function to create or update note ( Requires login ) ( UNTESTED ) . Parameters : post _ id ( int ) : The post id number this note belongs to . ...
params = { 'id' : note_id , 'note[post]' : post_id , 'note[x]' : coor_x , 'note[y]' : coor_y , 'note[width]' : width , 'note[height]' : height , 'note[body]' : body , 'note[is_active]' : is_active } return self . _get ( 'note/update' , params , method = 'POST' )
def _init_map ( self ) : """stub"""
super ( EdXDragAndDropQuestionFormRecord , self ) . _init_map ( ) QuestionTextFormRecord . _init_map ( self ) QuestionFilesFormRecord . _init_map ( self ) self . my_osid_object_form . _my_map [ 'text' ] [ 'text' ] = ''
def on_connection_open_error ( self , connection , error ) : """Invoked if the connection to RabbitMQ can not be made . : type connection : pika . TornadoConnection : param Exception error : The exception indicating failure"""
LOGGER . critical ( 'Could not connect to RabbitMQ (%s): %r' , connection , error ) self . state = self . STATE_CLOSED self . _reconnect ( )
def append ( self , item , parent = None , select = False ) : """Add an item to the end of the list . : param item : The item to be added : param parent : The parent item to add this as a child of , or None for a top - level node : param select : Whether the item should be selected after adding"""
if item in self : raise ValueError ( "item %s already in list" % item ) if parent is not None : giter = self . _iter_for ( parent ) else : giter = None modeliter = self . model . append ( giter , ( item , ) ) self . _id_to_iter [ id ( item ) ] = modeliter if select : self . selected_item = item
def parse ( self , items ) : """Parse ` 主题 ` , ` 时间 ` , ` 场馆 ` , 票价 ` in every item ."""
rows = [ ] for i , item in enumerate ( items ) : theme = colored . green ( item . find ( class_ = 'ico' ) . a . text . strip ( ) ) text = item . find ( class_ = 'mt10' ) . text . strip ( ) mix = re . sub ( '\s+' , ' ' , text ) . split ( ':' ) time = mix [ 1 ] [ : - 3 ] place = mix [ 2 ] [ : - 7 ] ...
def start ( self ) : """Starts the background thread . Additionally , this registers a handler for process exit to attempt to send any pending log entries before shutdown ."""
with self . _operational_lock : if self . is_alive : return self . _thread = threading . Thread ( target = self . _thread_main , name = _WORKER_THREAD_NAME ) self . _thread . daemon = True self . _thread . start ( ) atexit . register ( self . _main_thread_terminated )
def stdio ( filters = None , search_dirs = None , data_dir = True , sys_path = True , panfl_ = False , input_stream = None , output_stream = None ) : """Reads JSON from stdin and second CLI argument : ` ` sys . argv [ 1 ] ` ` . Dumps JSON doc to the stdout . : param filters : Union [ List [ str ] , None ] if ...
doc = load ( input_stream ) # meta = doc . metadata # Local variable ' meta ' value is not used verbose = doc . get_metadata ( 'panflute-verbose' , False ) if search_dirs is None : # metadata ' panflute - path ' can be a list , a string , or missing # ` search _ dirs ` should be a list of str search_dirs = doc . ge...
async def put ( self , path = '' ) : """Publish a notebook on a given path . The payload directly matches the contents API for PUT ."""
self . log . info ( "Attempt publishing to %s" , path ) if path == '' or path == '/' : raise web . HTTPError ( 400 , "Must provide a path for publishing" ) model = self . get_json_body ( ) if model : await self . _publish ( model , path . lstrip ( '/' ) ) else : raise web . HTTPError ( 400 , "Cannot publish...
def credentials_delegated ( self ) : """Checks if credentials are delegated ( server mode ) . : return : ` ` True ` ` if credentials are delegated , otherwise ` ` False ` `"""
return self . _gss_flags & sspicon . ISC_REQ_DELEGATE and ( self . _gss_srv_ctxt_status or self . _gss_flags )
def _set_cluster ( self , v , load = False ) : """Setter method for cluster , mapped from YANG variable / mgmt _ cluster / cluster ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ cluster is considered as a private method . Backends looking to populate th...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = cluster . cluster , is_container = 'container' , presence = False , yang_name = "cluster" , rest_name = "cluster" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True ,...
def list_str_summarized ( list_ , list_name , maxlen = 5 ) : """prints the list members when the list is small and the length when it is large"""
if len ( list_ ) > maxlen : return 'len(%s)=%d' % ( list_name , len ( list_ ) ) else : return '%s=%r' % ( list_name , list_ )
def help_center_user_segment_create ( self , data , ** kwargs ) : "https : / / developer . zendesk . com / rest _ api / docs / help _ center / user _ segments # create - user - segment"
api_path = "/api/v2/help_center/user_segments.json" return self . call ( api_path , method = "POST" , data = data , ** kwargs )
def crypto_box_keypair ( ) : """Returns a randomly generated public and secret key . : rtype : ( bytes ( public _ key ) , bytes ( secret _ key ) )"""
pk = ffi . new ( "unsigned char[]" , crypto_box_PUBLICKEYBYTES ) sk = ffi . new ( "unsigned char[]" , crypto_box_SECRETKEYBYTES ) rc = lib . crypto_box_keypair ( pk , sk ) ensure ( rc == 0 , 'Unexpected library error' , raising = exc . RuntimeError ) return ( ffi . buffer ( pk , crypto_box_PUBLICKEYBYTES ) [ : ] , ffi ...
def _is_valid_netmask ( self , netmask ) : """Verify that the netmask is valid . Args : netmask : A string , either a prefix or dotted decimal netmask . Returns : A boolean , True if the prefix represents a valid IPv4 netmask ."""
mask = netmask . split ( '.' ) if len ( mask ) == 4 : try : for x in mask : if int ( x ) not in self . _valid_mask_octets : return False except ValueError : # Found something that isn ' t an integer or isn ' t valid return False for idx , y in enumerate ( mask ) :...
def _true_anomaly ( M , ecc , itermax = 8 ) : r"""Calculation of true and eccentric anomaly in Kepler orbits . ` ` M ` ` is the phase of the star , ` ` ecc ` ` is the eccentricity See p . 39 of Hilditch , ' An Introduction To Close Binary Stars ' : Kepler ' s equation : . . math : : E - e \ sin E = \ frac...
# Initial value Fn = M + ecc * sin ( M ) + ecc ** 2 / 2. * sin ( 2 * M ) # Iterative solving of the transcendent Kepler ' s equation for i in range ( itermax ) : F = Fn Mn = F - ecc * sin ( F ) Fn = F + ( M - Mn ) / ( 1. - ecc * cos ( F ) ) keep = F != 0 # take care of zerodivision if hasattr ( ...
def handle_emphasis ( self , start , tag_style , parent_style ) : """handles various text emphases"""
tag_emphasis = google_text_emphasis ( tag_style ) parent_emphasis = google_text_emphasis ( parent_style ) # handle Google ' s text emphasis strikethrough = 'line-through' in tag_emphasis and self . hide_strikethrough bold = 'bold' in tag_emphasis and not 'bold' in parent_emphasis italic = 'italic' in tag_emphasis and n...
def get_calc_id ( db , datadir , job_id = None ) : """Return the latest calc _ id by looking both at the datastore and the database . : param db : a : class : ` openquake . server . dbapi . Db ` instance : param datadir : the directory containing the datastores : param job _ id : a job ID ; if None , return...
calcs = datastore . get_calc_ids ( datadir ) calc_id = 0 if not calcs else calcs [ - 1 ] if job_id is None : try : job_id = db ( 'SELECT seq FROM sqlite_sequence WHERE name="job"' , scalar = True ) except NotFound : job_id = 0 return max ( calc_id , job_id )
def load_user ( self , uid ) : '''a method to retrieve the account details of a user in the bucket : param uid : string with id of user in bucket : return : dictionary with account fields for user'''
title = '%s.load_user' % self . __class__ . __name__ # validate inputs input_fields = { 'uid' : uid } for key , value in input_fields . items ( ) : if value : object_title = '%s(%s=%s)' % ( title , key , str ( value ) ) self . fields . validate ( value , '.%s' % key , object_title ) # construct url ...
def search ( self , category , term = '' , index = 0 , count = 100 ) : """Search for an item in a category . Args : category ( str ) : The search category to use . Standard Sonos search categories are ' artists ' , ' albums ' , ' tracks ' , ' playlists ' , ' genres ' , ' stations ' , ' tags ' . Not all are ...
search_category = self . _get_search_prefix_map ( ) . get ( category , None ) if search_category is None : raise MusicServiceException ( "%s does not support the '%s' search category" % ( self . service_name , category ) ) response = self . soap_client . call ( 'search' , [ ( 'id' , search_category ) , ( 'term' , t...
def build_dependencies ( self ) : """Build the dependencies for this module . Parse the code with ast , find all the import statements , convert them into Dependency objects ."""
highest = self . dsm or self . root if self is highest : highest = LeafNode ( ) for _import in self . parse_code ( ) : target = highest . get_target ( _import [ 'target' ] ) if target : what = _import [ 'target' ] . split ( '.' ) [ - 1 ] if what != target . name : _import [ 'what...
def _get_formatter ( fmt ) : """Args : fmt ( str | unicode ) : Format specification Returns : ( logging . Formatter ) : Associated logging formatter"""
fmt = _replace_and_pad ( fmt , "%(timezone)s" , LogManager . spec . timezone ) return logging . Formatter ( fmt )
def resource_etree_element ( self , resource , element_name = 'url' ) : """Return xml . etree . ElementTree . Element representing the resource . Returns and element for the specified resource , of the form < url > with enclosed properties that are based on the sitemap with extensions for ResourceSync ."""
e = Element ( element_name ) sub = Element ( 'loc' ) sub . text = resource . uri e . append ( sub ) if ( resource . timestamp is not None ) : # Create appriate element for timestamp sub = Element ( 'lastmod' ) sub . text = str ( resource . lastmod ) # W3C Datetime in UTC e . append ( sub ) md_atts = { }...
def increment_key ( key ) : """given a key increment the value"""
pipe = REDIS_SERVER . pipeline ( ) pipe . incr ( key , 1 ) if config . COOLOFF_TIME : pipe . expire ( key , config . COOLOFF_TIME ) new_value = pipe . execute ( ) [ 0 ] return new_value
def SETUP ( self ) : """Set up stream transport ."""
message = "SETUP " + self . session . control_url + " RTSP/1.0\r\n" message += self . sequence message += self . authentication message += self . user_agent message += self . transport message += '\r\n' return message
def _sensoryComputeInferenceMode ( self , anchorInput ) : """Infer the location from sensory input . Activate any cells with enough active synapses to this sensory input . Deactivate all other cells . @ param anchorInput ( numpy array ) A sensory input . This will often come from a feature - location pair lay...
if len ( anchorInput ) == 0 : return overlaps = self . connections . computeActivity ( anchorInput , self . connectedPermanence ) activeSegments = np . where ( overlaps >= self . activationThreshold ) [ 0 ] sensorySupportedCells = np . unique ( self . connections . mapSegmentsToCells ( activeSegments ) ) self . bum...
def as_categorical_frame ( self , index , columns , name = None ) : """Coerce self into a pandas DataFrame of Categoricals ."""
if len ( self . shape ) != 2 : raise ValueError ( "Can't convert a non-2D LabelArray into a DataFrame." ) expected_shape = ( len ( index ) , len ( columns ) ) if expected_shape != self . shape : raise ValueError ( "Can't construct a DataFrame with provided indices:\n\n" "LabelArray shape is {actual}, but index ...
def purge ( self ) : """Deletes all tasks in the queue ."""
try : return self . _api . purge ( ) except AttributeError : while True : lst = self . list ( ) if len ( lst ) == 0 : break for task in lst : self . delete ( task ) self . wait ( ) return self
def init_validator ( required , cls , * additional_validators ) : """Create an attrs validator based on the cls provided and required setting . : param bool required : whether the field is required in a given model . : param cls : the expected class type of object value . : return : attrs validator chained co...
validator = validators . instance_of ( cls ) if additional_validators : additional_validators = list ( additional_validators ) additional_validators . append ( validator ) validator = composite ( * additional_validators ) return validator if required else validators . optional ( validator )
def set_acceptance_filter_bypass ( self , bus , bypass ) : """Control the status of CAN acceptance filter for a bus . Returns True if the command was successful ."""
request = { "command" : "af_bypass" , "bus" : bus , "bypass" : bypass } return self . _check_command_response_status ( request )
def copy_dir ( self , path ) : """Recursively copy directory"""
for directory in path : if os . path . isdir ( path ) : full_path = os . path . join ( self . archive_dir , directory . lstrip ( '/' ) ) logger . debug ( "Copying %s to %s" , directory , full_path ) shutil . copytree ( directory , full_path ) else : logger . debug ( "Not a direct...
def get_field_value ( self , instance , field_name ) : """Given an instance , and the name of an attribute , returns the value of that attribute on the instance . Default behavior will map the ` ` percent ` ` attribute to ` ` id ` ` ."""
# XXX : can we come up w / a better API ? # Ensure we map ` ` percent ` ` to the ` ` id ` ` column if field_name == 'percent' : field_name = 'id' value = getattr ( instance , field_name ) if callable ( value ) : value = value ( ) return value
def setup_domain_socket ( location ) : '''Setup Domain Socket Setup a connection to a Unix Domain Socket @ param location : str The path to the Unix Domain Socket to connect to . @ return < class ' socket . _ socketobject ' >'''
clientsocket = socket . socket ( socket . AF_UNIX , socket . SOCK_STREAM ) clientsocket . settimeout ( timeout ) clientsocket . connect ( location ) return clientsocket
def get_all_roles ( path_prefix = None , region = None , key = None , keyid = None , profile = None ) : '''Get and return all IAM role details , starting at the optional path . . . versionadded : : 2016.3.0 CLI Example : salt - call boto _ iam . get _ all _ roles'''
conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile ) if not conn : return None _roles = conn . list_roles ( path_prefix = path_prefix ) roles = _roles . list_roles_response . list_roles_result . roles marker = getattr ( _roles . list_roles_response . list_roles_result , 'marker' , No...
def unpack_auth_b64 ( self , docker_registry ) : """Decode and unpack base64 ' auth ' credentials from config file . : param docker _ registry : str , registry reference in config file : return : namedtuple , UnpackedAuth ( or None if no ' auth ' is available )"""
UnpackedAuth = namedtuple ( 'UnpackedAuth' , [ 'raw_str' , 'username' , 'password' ] ) credentials = self . get_credentials ( docker_registry ) auth_b64 = credentials . get ( 'auth' ) if auth_b64 : raw_str = b64decode ( auth_b64 ) . decode ( 'utf-8' ) unpacked_credentials = raw_str . split ( ':' , 1 ) if le...
def __install_perforce ( self , config ) : """install perforce binary"""
if not system . is_64_bit ( ) : self . logger . warn ( "Perforce formula is only designed for 64 bit systems! Not install executables..." ) return False version = config . get ( 'version' , 'r13.2' ) key = 'osx' if system . is_osx ( ) else 'linux' perforce_packages = package_dict [ version ] [ key ] d = self . ...
def add_agent_cloud ( self , agent_cloud ) : """AddAgentCloud . [ Preview API ] : param : class : ` < TaskAgentCloud > < azure . devops . v5_0 . task _ agent . models . TaskAgentCloud > ` agent _ cloud : : rtype : : class : ` < TaskAgentCloud > < azure . devops . v5_0 . task _ agent . models . TaskAgentCloud ...
content = self . _serialize . body ( agent_cloud , 'TaskAgentCloud' ) response = self . _send ( http_method = 'POST' , location_id = 'bfa72b3d-0fc6-43fb-932b-a7f6559f93b9' , version = '5.0-preview.1' , content = content ) return self . _deserialize ( 'TaskAgentCloud' , response )
def cmd_condition ( args ) : '''control MAVExporer conditions'''
if len ( args ) == 0 : print ( "condition is: %s" % mestate . settings . condition ) return mestate . settings . condition = ' ' . join ( args ) if len ( mestate . settings . condition ) == 0 or mestate . settings . condition == 'clear' : mestate . settings . condition = None
def create_from_other ( Class , other , values = None ) : """Create a new Matrix with attributes taken from ` other ` but with the values taken from ` values ` if provided"""
m = Class ( ) m . alphabet = other . alphabet m . sorted_alphabet = other . sorted_alphabet m . char_to_index = other . char_to_index if values is not None : m . values = values else : m . values = other . values return m
def _time_stretcher ( self , stretch_factor ) : """Real time time - scale without pitch modification . : param int i : index of the beginning of the chunk to stretch : param float stretch _ factor : audio scale factor ( if > 1 speed up the sound else slow it down ) . . warning : : This method needs to store t...
start = self . _i2 end = min ( self . _i2 + self . _N , len ( self . _sy ) - ( self . _N + self . _H ) ) if start >= end : raise StopIteration # The not so clean code below basically implements a phase vocoder out = numpy . zeros ( self . _N , dtype = numpy . complex ) while self . _i2 < end : if self . _i1 + s...
def setFont ( self , font ) : """Assigns the font to this widget and all of its children . : param font | < QtGui . QFont >"""
super ( XTimeEdit , self ) . setFont ( font ) # update the fonts for the time combos self . _hourCombo . setFont ( font ) self . _minuteCombo . setFont ( font ) self . _secondCombo . setFont ( font ) self . _timeOfDayCombo . setFont ( font )
def create ( cls , datacenter , memory , cores , ip_version , bandwidth , login , password , hostname , image , run , background , sshkey , size , vlan , ip , script , script_args , ssh ) : """Create a new virtual machine ."""
from gandi . cli . modules . network import Ip , Iface if not background and not cls . intty ( ) : background = True datacenter_id_ = int ( Datacenter . usable_id ( datacenter ) ) if not hostname : hostname = randomstring ( 'vm' ) disk_name = 'sys_%s' % hostname [ 2 : ] else : disk_name = 'sys_%s' % hos...
def _wait_for_request ( self , uuid , connection_adapter = None ) : """Wait for RPC request to arrive . : param str uuid : Rpc Identifier . : param obj connection _ adapter : Provide custom connection adapter . : return :"""
start_time = time . time ( ) while not self . _response [ uuid ] : connection_adapter . check_for_errors ( ) if time . time ( ) - start_time > self . _timeout : self . _raise_rpc_timeout_error ( uuid ) time . sleep ( IDLE_WAIT )
def _block_shape ( values , ndim = 1 , shape = None ) : """guarantee the shape of the values to be at least 1 d"""
if values . ndim < ndim : if shape is None : shape = values . shape if not is_extension_array_dtype ( values ) : # TODO : https : / / github . com / pandas - dev / pandas / issues / 23023 # block . shape is incorrect for " 2D " ExtensionArrays # We can ' t , and don ' t need to , reshape . ...
def unpack ( self , token ) : """Unpack a received signed or signed and encrypted Json Web Token : param token : The Json Web Token : return : If decryption and signature verification work the payload will be returned as a Message instance if possible ."""
if not token : raise KeyError _jwe_header = _jws_header = None # Check if it ' s an encrypted JWT darg = { } if self . allowed_enc_encs : darg [ 'enc' ] = self . allowed_enc_encs if self . allowed_enc_algs : darg [ 'alg' ] = self . allowed_enc_algs try : _decryptor = jwe_factory ( token , ** darg ) exce...
def _op_method ( self , data , extra_factor = 1.0 ) : """Operator This method returns the input data after the singular values have been thresholded Parameters data : np . ndarray Input data array extra _ factor : float Additional multiplication factor Returns np . ndarray SVD thresholded data"""
# Update threshold with extra factor . threshold = self . thresh * extra_factor if self . lowr_type == 'standard' : data_matrix = svd_thresh ( cube2matrix ( data ) , threshold , thresh_type = self . thresh_type ) elif self . lowr_type == 'ngole' : data_matrix = svd_thresh_coef ( cube2matrix ( data ) , self . op...
def get_bundles ( self ) : # type : ( ) - > List [ Bundle ] """Returns the list of all installed bundles : return : the list of all installed bundles"""
with self . __bundles_lock : return [ self . __bundles [ bundle_id ] for bundle_id in sorted ( self . __bundles . keys ( ) ) ]
def get_build_info ( api_instance , build_id = None , keys = DEFAULT_BUILD_KEYS , wait = False ) : """print build info about a job"""
build = ( api_instance . get_build ( build_id ) if build_id else api_instance . get_last_build ( ) ) output = "" if wait : build . block_until_complete ( ) if 'timestamp' in keys : output += str ( build . get_timestamp ( ) ) + '\n' if 'console' in keys : output += build . get_console ( ) + '\n' if 'scm' in ...
def build_row_dict ( cls , row , dialect , deleted = False , user_id = None , use_dirty = True ) : """Builds a dictionary of archive data from row which is suitable for insert . NOTE : If ` deleted ` is False , version ID will be set to an AsIs SQL construct . : param row : instance of : class : ` ~ SavageModel...
data = { 'data' : row . to_archivable_dict ( dialect , use_dirty = use_dirty ) , 'deleted' : deleted , 'updated_at' : datetime . now ( ) , 'version_id' : current_version_sql ( as_is = True ) if deleted else row . version_id } for col_name in row . version_columns : data [ col_name ] = utils . get_column_attribute (...
def simulateCatalog ( config , roi = None , lon = None , lat = None ) : """Simulate a catalog object ."""
import ugali . simulation . simulator if roi is None : roi = createROI ( config , lon , lat ) sim = ugali . simulation . simulator . Simulator ( config , roi ) return sim . catalog ( )