signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def ProcessMessage ( self , message ) : """Run the foreman on the client ."""
# Only accept authenticated messages if ( message . auth_state != rdf_flows . GrrMessage . AuthorizationState . AUTHENTICATED ) : return now = time . time ( ) # Maintain a cache of the foreman with self . lock : if ( self . foreman_cache is None or now > self . foreman_cache . age + self . cache_refresh_time ) ...
def _generate_barcode_ids ( info_iter ) : """Create unique barcode IDs assigned to sequences"""
bc_type = "SampleSheet" barcodes = list ( set ( [ x [ - 1 ] for x in info_iter ] ) ) barcodes . sort ( ) barcode_ids = { } for i , bc in enumerate ( barcodes ) : barcode_ids [ bc ] = ( bc_type , i + 1 ) return barcode_ids
def _store ( self , uid , content , data = None ) : """Store the given dict of content at uid . Nothing returned ."""
doc = dict ( uid = uid ) if data : gfs = gridfs . GridFS ( self . db ) id = gfs . put ( data , encoding = 'utf-8' ) doc . update ( data_id = id ) doc . update ( content ) self . db . pastes . insert_one ( doc )
def all_segs_matching_fts ( self , fts ) : """Return segments matching a feature mask , both as ( value , feature ) tuples ( sorted in reverse order by length ) . Args : fts ( list ) : feature mask as ( value , feature ) tuples . Returns : list : segments matching ` fts ` , sorted in reverse order by leng...
matching_segs = [ ] for seg , pairs in self . segments : if set ( fts ) <= set ( pairs ) : matching_segs . append ( seg ) return sorted ( matching_segs , key = lambda x : len ( x ) , reverse = True )
def isdir ( path , ** kwargs ) : """Check if * path * is a directory"""
import os . path return os . path . isdir ( path , ** kwargs )
def parse_result_to_dsl ( tokens ) : """Convert a ParseResult to a PyBEL DSL object . : type tokens : dict or pyparsing . ParseResults : rtype : BaseEntity"""
if MODIFIER in tokens : return parse_result_to_dsl ( tokens [ TARGET ] ) elif REACTION == tokens [ FUNCTION ] : return _reaction_po_to_dict ( tokens ) elif VARIANTS in tokens : return _variant_po_to_dict ( tokens ) elif MEMBERS in tokens : return _list_po_to_dict ( tokens ) elif FUSION in tokens : r...
def spharm ( lmax , theta , phi , normalization = '4pi' , kind = 'real' , csphase = 1 , packed = False , degrees = True ) : """Compute all the spherical harmonic functions up to a maximum degree . Usage ylm = spharm ( lmax , theta , phi , [ normalization , kind , csphase , packed , degrees ] ) Returns ylm...
if lmax < 0 : raise ValueError ( "lmax must be greater or equal to 0. Input value was {:s}." . format ( repr ( lmax ) ) ) if normalization . lower ( ) not in ( '4pi' , 'ortho' , 'schmidt' , 'unnorm' ) : raise ValueError ( "The normalization must be '4pi', 'ortho', 'schmidt', " + "or 'unnorm'. Input value was {:...
def clean_surface ( surface , span ) : """Remove spurious characters from a quantity ' s surface ."""
surface = surface . replace ( '-' , ' ' ) no_start = [ 'and' , ' ' ] no_end = [ ' and' , ' ' ] found = True while found : found = False for word in no_start : if surface . lower ( ) . startswith ( word ) : surface = surface [ len ( word ) : ] span = ( span [ 0 ] + len ( word ) , ...
def parse_job_files ( self ) : """Check for job definitions in known zuul files ."""
repo_jobs = [ ] for rel_job_file_path , job_info in self . job_files . items ( ) : LOGGER . debug ( "Checking for job definitions in %s" , rel_job_file_path ) jobs = self . parse_job_definitions ( rel_job_file_path , job_info ) LOGGER . debug ( "Found %d job definitions in %s" , len ( jobs ) , rel_job_file_...
def fit_curvefit ( p0 , datax , datay , function , ** kwargs ) : """Fits the data to a function using scipy . optimise . curve _ fit Parameters p0 : array _ like initial parameters to use for fitting datax : array _ like x data to use for fitting datay : array _ like y data to use for fitting functi...
pfit , pcov = _curve_fit ( function , datax , datay , p0 = p0 , epsfcn = 0.0001 , ** kwargs ) error = [ ] for i in range ( len ( pfit ) ) : try : error . append ( _np . absolute ( pcov [ i ] [ i ] ) ** 0.5 ) except : error . append ( _np . NaN ) pfit_curvefit = pfit perr_curvefit = _np . array (...
def to_array ( self ) : """Serializes this InputTextMessageContent to a dictionary . : return : dictionary representation of this object . : rtype : dict"""
array = super ( InputTextMessageContent , self ) . to_array ( ) array [ 'message_text' ] = u ( self . message_text ) # py2 : type unicode , py3 : type str if self . parse_mode is not None : array [ 'parse_mode' ] = u ( self . parse_mode ) # py2 : type unicode , py3 : type str if self . disable_web_page_preview ...
def get_port_profile_status_input_request_type_getnext_request_last_received_port_profile_info_profile_mac ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) get_port_profile_status = ET . Element ( "get_port_profile_status" ) config = get_port_profile_status input = ET . SubElement ( get_port_profile_status , "input" ) request_type = ET . SubElement ( input , "request-type" ) getnext_request = ET . SubElement ( request_type , "getnext-req...
def manager_view ( request , managerTitle ) : '''View the details of a manager position . Parameters : request is an HTTP request managerTitle is the URL title of the manager .'''
targetManager = get_object_or_404 ( Manager , url_title = managerTitle ) if not targetManager . active : messages . add_message ( request , messages . ERROR , MESSAGES [ 'INACTIVE_MANAGER' ] . format ( managerTitle = targetManager . title ) ) return HttpResponseRedirect ( reverse ( 'managers:list_managers' ) ) ...
def download ( self , uuid , output_format = 'gzip' ) : """Download pre - prepared data by UUID : type uuid : str : param uuid : Data UUID : type output _ format : str : param output _ format : Output format of the data , either " gzip " or " text " : rtype : str : return : The downloaded content"""
if output_format . lower ( ) not in ( 'gzip' , 'text' ) : raise Exception ( "output_format must be one of file, text" ) data = { 'format' : output_format , 'uuid' : uuid , } return self . get ( 'download' , get_params = data , is_json = False )
def load ( self ) : """Load each path in order . Remember paths already loaded and only load new ones ."""
data = self . dict_class ( ) for path in self . paths : if path in self . paths_loaded : continue try : with open ( path , 'r' ) as file : path_data = yaml . load ( file . read ( ) ) data = dict_merge ( data , path_data ) self . paths_loaded . add ( path ) exc...
def addBorder ( self , width , color = None ) : """Add a border to the current : py : class : ` Layer ` . : param width : The width of the border . : param color : The : py : class : ` Color ` of the border , current : py : class : ` Color ` is the default value . : rtype : Nothing ."""
width = int ( width / config . DOWNSAMPLING ) if color == None : color = self . color layer = self . image . getActiveLayer ( ) . data colorRGBA = color . get_0_255 ( ) print ( 'adding border' + str ( colorRGBA ) + str ( width ) + str ( layer . shape ) ) layer [ 0 : width , : , 0 ] = colorRGBA [ 0 ] layer [ 0 : wid...
def load ( self , filename = None ) : """Method was overriden to set spectrum . filename as well"""
DataFile . load ( self , filename ) self . spectrum . filename = filename
def _show_stat_wrapper_Progress ( count , last_count , start_time , max_count , speed_calc_cycles , width , q , last_speed , prepend , show_stat_function , add_args , i , lock ) : """calculate"""
count_value , max_count_value , speed , tet , ttg , = Progress . _calc ( count , last_count , start_time , max_count , speed_calc_cycles , q , last_speed , lock ) return show_stat_function ( count_value , max_count_value , prepend , speed , tet , ttg , width , i , ** add_args )
def wait_with_ioloop ( self , ioloop , timeout = None ) : """Do blocking wait until condition is event is set . Parameters ioloop : tornadio . ioloop . IOLoop instance MUST be the same ioloop that set ( ) / clear ( ) is called from timeout : float , int or None If not None , only wait up to ` timeout ` se...
f = Future ( ) def cb ( ) : return gen . chain_future ( self . until_set ( ) , f ) ioloop . add_callback ( cb ) try : f . result ( timeout ) return True except TimeoutError : return self . _flag
def instance_attr ( self , name , context = None ) : """Get the list of nodes associated to the given attribute name . Assignments are looked for in both this class and in parents . : returns : The list of assignments to the given name . : rtype : list ( NodeNG ) : raises AttributeInferenceError : If no att...
# Return a copy , so we don ' t modify self . instance _ attrs , # which could lead to infinite loop . values = list ( self . instance_attrs . get ( name , [ ] ) ) # get all values from parents for class_node in self . instance_attr_ancestors ( name , context ) : values += class_node . instance_attrs [ name ] value...
def response_hook ( self , response , ** kwargs ) -> HTMLResponse : """Change response enconding and replace it by a HTMLResponse ."""
if not response . encoding : response . encoding = DEFAULT_ENCODING return HTMLResponse . _from_response ( response , self )
def get_nested_relation_kwargs ( field_name , relation_info ) : """Creating a default instance of a nested serializer"""
kwargs = get_relation_kwargs ( field_name , relation_info ) kwargs . pop ( 'queryset' ) kwargs . pop ( 'required' ) kwargs [ 'read_only' ] = True return kwargs
def look_for_books ( citation_elements , kbs ) : """Look for books in our kb Create book tags by using the authors and the title to find books in our knowledge base"""
title = None for el in citation_elements : if el [ 'type' ] == 'QUOTED' : title = el break if title : normalized_title = title [ 'title' ] . upper ( ) if normalized_title in kbs [ 'books' ] : line = kbs [ 'books' ] [ normalized_title ] el = { 'type' : 'BOOK' , 'misc_txt' : ''...
def _set_process_list ( self , v , load = False ) : """Setter method for process _ list , mapped from YANG variable / cpu _ state / process _ list ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ process _ list is considered as a private method . Backends...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = process_list . process_list , is_container = 'container' , presence = False , yang_name = "process-list" , rest_name = "process-list" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , reg...
def unfreeze_extensions ( self ) : """Remove a previously frozen list of extensions ."""
output_path = os . path . join ( _registry_folder ( ) , 'frozen_extensions.json' ) if not os . path . isfile ( output_path ) : raise ExternalError ( "There is no frozen extension list" ) os . remove ( output_path ) ComponentRegistry . _frozen_extensions = None
def view_run ( ) : """Page for viewing before / after for a specific test run ."""
build = g . build if request . method == 'POST' : form = forms . RunForm ( request . form ) else : form = forms . RunForm ( request . args ) form . validate ( ) ops = operations . BuildOps ( build . id ) run , next_run , previous_run , approval_log = ops . get_run ( form . name . data , form . number . data , f...
def launch_coroutine ( self , cor , * args , ** kwargs ) : """Start a coroutine task and return a blockable / awaitable object . If this method is called from inside the event loop , it will return an awaitable object . If it is called from outside the event loop it will return an concurrent Future object tha...
if self . stopping : raise LoopStoppingError ( "Could not launch coroutine because loop is shutting down: %s" % cor ) # Ensure the loop exists and is started self . start ( ) cor = _instaniate_coroutine ( cor , args , kwargs ) if self . inside_loop ( ) : return asyncio . ensure_future ( cor , loop = self . loop...
def managed_process ( process ) : """Wrapper for subprocess . Popen to work across various Python versions , when using the with syntax ."""
try : yield process finally : for stream in [ process . stdout , process . stdin , process . stderr ] : if stream : stream . close ( ) process . wait ( )
def current_gvim_edit ( op = 'e' , fpath = '' ) : r"""CommandLine : python - m utool . util _ ubuntu XCtrl . current _ gvim _ edit sp ~ / . bashrc"""
import utool as ut fpath = ut . unexpanduser ( ut . truepath ( fpath ) ) # print ( ' fpath = % r ' % ( fpath , ) ) ut . copy_text_to_clipboard ( fpath ) # print ( ut . get _ clipboard ( ) ) doscript = [ ( 'focus' , 'gvim' ) , ( 'key' , 'Escape' ) , ( 'type2' , ';' + op + ' ' + fpath ) , # ( ' type2 ' , ' ; ' + op + ' '...
def console_init_root ( w : int , h : int , title : Optional [ str ] = None , fullscreen : bool = False , renderer : Optional [ int ] = None , order : str = "C" , ) -> tcod . console . Console : """Set up the primary display and return the root console . ` w ` and ` h ` are the columns and rows of the new window ...
if title is None : # Use the scripts filename as the title . title = os . path . basename ( sys . argv [ 0 ] ) if renderer is None : warnings . warn ( "A renderer should be given, see the online documentation." , DeprecationWarning , stacklevel = 2 , ) renderer = tcod . constants . RENDERER_SDL elif rendere...
def add_issue ( self , data ) : """This method include new issues to the ArticleMeta . data : legacy SciELO Documents JSON Type 3."""
issue = self . dispatcher ( 'add_issue' , data , self . _admintoken ) return json . loads ( issue )
def startLoop ( self , useDriverLoop ) : '''Called by the engine to start an event loop .'''
if useDriverLoop : self . _driver . startLoop ( ) else : self . _iterator = self . _driver . iterate ( )
def GroupsSensorsPost ( self , group_id , sensors ) : """Share a number of sensors within a group . @ param group _ id ( int ) - Id of the group to share sensors with @ param sensors ( dictionary ) - Dictionary containing the sensors to share within the groups @ return ( bool ) - Boolean indicating whether th...
if self . __SenseApiCall__ ( "/groups/{0}/sensors.json" . format ( group_id ) , "POST" , parameters = sensors ) : return True else : self . __error__ = "api call unsuccessful" return False
def get_form_kwargs ( self ) : """Return the form kwargs . This method injects the context variable , defined in : meth : ` get _ agnocomplete _ context ` . Override this method to adjust it to your needs ."""
data = super ( UserContextFormViewMixin , self ) . get_form_kwargs ( ) data . update ( { 'user' : self . get_agnocomplete_context ( ) , } ) return data
def RepackTemplates ( self , repack_configs , templates , output_dir , config = None , sign = False , signed_template = False ) : """Call repacker in a subprocess ."""
pool = multiprocessing . Pool ( processes = 10 ) results = [ ] bulk_sign_installers = False for repack_config in repack_configs : for template in templates : repack_args = [ "grr_client_build" ] if config : repack_args . extend ( [ "--config" , config ] ) repack_args . extend ( [...
def _parse_multifile ( self , desired_type : Type [ Union [ Dict , List , Set , Tuple ] ] , obj : PersistedObject , parsing_plan_for_children : Dict [ str , ParsingPlan ] , logger : Logger , options : Dict [ str , Dict [ str , Any ] ] ) -> Union [ Dict , List , Set , Tuple ] : """Options may contain a section with ...
# first get the options and check them lazy_parsing = False background_parsing = False opts = self . _get_applicable_options ( options ) for opt_key , opt_val in opts . items ( ) : if opt_key is 'lazy_parsing' : lazy_parsing = opt_val elif opt_key is 'background_parsing' : background_parsing = o...
def columnCount ( self , parent = QtCore . QModelIndex ( ) ) : """Determines the numbers of columns the view will draw Required by view , see : qtdoc : ` subclassing < qabstractitemmodel . subclassing > `"""
if parent . isValid ( ) : return self . _stim . columnCount ( parent . row ( ) ) else : return self . _stim . columnCount ( )
def filter_actions ( self , block_addr = None , block_stmt = None , insn_addr = None , read_from = None , write_to = None ) : """Filter self . actions based on some common parameters . : param block _ addr : Only return actions generated in blocks starting at this address . : param block _ stmt : Only return ac...
if read_from is not None : if write_to is not None : raise ValueError ( "Can't handle read_from and write_to at the same time!" ) if read_from in ( 'reg' , 'mem' ) : read_type = read_from read_offset = None elif isinstance ( read_from , str ) : read_type = 'reg' read_...
def has_option ( section , name ) : """Wrapper around ConfigParser ' s ` ` has _ option ` ` method ."""
cfg = ConfigParser . SafeConfigParser ( { "working_dir" : "/tmp" , "debug" : "0" } ) cfg . read ( CONFIG_LOCATIONS ) return cfg . has_option ( section , name )
def extra ( request , provider ) : """Handle registration of new user with extra data for profile"""
identity = request . session . get ( 'identity' , None ) if not identity : raise Http404 if request . method == "POST" : form = str_to_class ( settings . EXTRA_FORM ) ( request . POST ) if form . is_valid ( ) : user = form . save ( request , identity , provider ) del request . session [ 'ide...
def visitShapeDefinition ( self , ctx : ShExDocParser . ShapeDefinitionContext ) : """shapeDefinition : qualifier * ' { ' oneOfShape ? ' } ' annotation * semanticActions"""
if ctx . qualifier ( ) : for q in ctx . qualifier ( ) : self . visit ( q ) if ctx . oneOfShape ( ) : oneof_parser = ShexOneOfShapeParser ( self . context ) oneof_parser . visit ( ctx . oneOfShape ( ) ) self . shape . expression = oneof_parser . expression if ctx . annotation ( ) or ctx . semanti...
def _add_environment_lib ( ) : """Adds the chef _ solo _ envs cookbook , which provides a library that adds environment attribute compatibility for chef - solo v10 NOTE : Chef 10 only"""
# Create extra cookbook dir lib_path = os . path . join ( env . node_work_path , cookbook_paths [ 0 ] , 'chef_solo_envs' , 'libraries' ) with hide ( 'running' , 'stdout' ) : sudo ( 'mkdir -p {0}' . format ( lib_path ) ) # Add environment patch to the node ' s cookbooks put ( os . path . join ( basedir , 'environmen...
def _query ( self , action , qobj ) : """Form query to enumerate category"""
title = self . params . get ( 'title' ) pageid = self . params . get ( 'pageid' ) if action == 'random' : return qobj . random ( namespace = 14 ) elif action == 'category' : return qobj . category ( title , pageid , self . _continue_params ( ) )
def get_frame ( self ) : """Get a dataframe of metrics from this storage"""
metric_items = list ( self . db . metrics . find ( { 'run_name' : self . model_config . run_name } ) . sort ( 'epoch_idx' ) ) if len ( metric_items ) == 0 : return pd . DataFrame ( columns = [ 'run_name' ] ) else : return pd . DataFrame ( metric_items ) . drop ( [ '_id' , 'model_name' ] , axis = 1 ) . set_index...
def get_user_permission_from_email ( self , email ) : """Returns a user ' s permissions object when given the user email ."""
_id = self . get_user_id_from_email ( email ) return self . get_user_permission ( _id )
def _FormatSubjectOrProcessToken ( self , token_data ) : """Formats a subject or process token as a dictionary of values . Args : token _ data ( bsm _ token _ data _ subject32 | bsm _ token _ data _ subject64 ) : AUT _ SUBJECT32 , AUT _ PROCESS32 , AUT _ SUBJECT64 or AUT _ PROCESS64 token data . Returns :...
ip_address = self . _FormatPackedIPv4Address ( token_data . ip_address ) return { 'aid' : token_data . audit_user_identifier , 'euid' : token_data . effective_user_identifier , 'egid' : token_data . effective_group_identifier , 'uid' : token_data . real_user_identifier , 'gid' : token_data . real_group_identifier , 'pi...
def make_path ( * args ) : """> > > _ hack _ make _ path _ doctest _ output ( make _ path ( " / a " , " b " ) ) ' / a / b ' > > > _ hack _ make _ path _ doctest _ output ( make _ path ( [ " / a " , " b " ] ) ) ' / a / b ' > > > _ hack _ make _ path _ doctest _ output ( make _ path ( * [ " / a " , " b " ] ) ...
paths = unpack_args ( * args ) return os . path . abspath ( os . path . join ( * [ p for p in paths if p is not None ] ) )
def parseline ( line , format ) : """Given a line ( a string actually ) and a short string telling how to format it , return a list of python objects that result . The format string maps words ( as split by line . split ( ) ) into python code : x - > Nothing ; skip this word s - > Return this word as a st...
xlat = { 'x' : None , 's' : str , 'f' : float , 'd' : int , 'i' : int } result = [ ] words = line . split ( ) for i in range ( len ( format ) ) : f = format [ i ] trans = xlat . get ( f , None ) if trans : result . append ( trans ( words [ i ] ) ) if len ( result ) == 0 : return None if len ( re...
def _to_point ( dims ) : """Convert ( width , height ) or size - > point . Point ."""
assert dims if isinstance ( dims , ( tuple , list ) ) : if len ( dims ) != 2 : raise ValueError ( "A two element tuple or list is expected here, got {}." . format ( dims ) ) else : width = int ( dims [ 0 ] ) height = int ( dims [ 1 ] ) if width <= 0 or height <= 0 : r...
def extent ( self ) : """Return the source range ( the range of text ) occupied by the entity pointed at by the cursor ."""
if not hasattr ( self , '_extent' ) : self . _extent = conf . lib . clang_getCursorExtent ( self ) return self . _extent
def list_absent ( name , acl_type , acl_names = None , recurse = False ) : '''Ensure a Linux ACL list does not exist Takes a list of acl names and remove them from the given path name The acl path acl _ type The type of the acl is used for , it can be ' user ' or ' group ' acl _ names The list of user...
if acl_names is None : acl_names = [ ] ret = { 'name' : name , 'result' : True , 'changes' : { } , 'comment' : '' } if not os . path . exists ( name ) : ret [ 'comment' ] = '{0} does not exist' . format ( name ) ret [ 'result' ] = False return ret __current_perms = __salt__ [ 'acl.getfacl' ] ( name ) if...
def get_temp_url ( self , obj , seconds , method = "GET" , key = None , cached = True ) : """Given a storage object in this container , returns a URL that can be used to access that object . The URL will expire after ` seconds ` seconds . The only methods supported are GET and PUT . Anything else will raise a...
return self . manager . get_temp_url ( self , obj , seconds , method = method , key = key , cached = cached )
def forward ( self , Q_ , p_ , G_ , h_ , A_ , b_ ) : """Solve a batch of QPs . This function solves a batch of QPs , each optimizing over ` nz ` variables and having ` nineq ` inequality constraints and ` neq ` equality constraints . The optimization problem for each instance in the batch ( dropping index...
nBatch = extract_nBatch ( Q_ , p_ , G_ , h_ , A_ , b_ ) Q , _ = expandParam ( Q_ , nBatch , 3 ) p , _ = expandParam ( p_ , nBatch , 2 ) G , _ = expandParam ( G_ , nBatch , 3 ) h , _ = expandParam ( h_ , nBatch , 2 ) A , _ = expandParam ( A_ , nBatch , 3 ) b , _ = expandParam ( b_ , nBatch , 2 ) if self . check_Q_spd : ...
def get_item ( self , table , hash_key , range_key = None , attributes_to_get = None , consistent_read = False , item_class = Item ) : """Retrieve an existing item from the table . : type table : : class : ` boto . dynamodb . table . Table ` : param table : The Table object from which the item is retrieved . ...
key = self . build_key_from_values ( table . schema , hash_key , range_key ) response = self . layer1 . get_item ( table . name , key , attributes_to_get , consistent_read , object_hook = item_object_hook ) item = item_class ( table , hash_key , range_key , response [ 'Item' ] ) if 'ConsumedCapacityUnits' in response :...
def _find_file ( self , needle , candidates ) : """Find the first directory containing a given candidate file ."""
for candidate in candidates : fullpath = os . path . join ( candidate , needle ) if os . path . isfile ( fullpath ) : return fullpath raise PathError ( "Unable to locate file %s; tried %s" % ( needle , candidates ) )
def get_tower_results ( iterator , optimizer , dropout_rates ) : r'''With this preliminary step out of the way , we can for each GPU introduce a tower for which ' s batch we calculate and return the optimization gradients and the average loss across towers .'''
# To calculate the mean of the losses tower_avg_losses = [ ] # Tower gradients to return tower_gradients = [ ] with tf . variable_scope ( tf . get_variable_scope ( ) ) : # Loop over available _ devices for i in range ( len ( Config . available_devices ) ) : # Execute operations of tower i on device i device...
def forward ( self , is_train , req , in_data , out_data , aux ) : """Implements forward computation . is _ train : bool , whether forwarding for training or testing . req : list of { ' null ' , ' write ' , ' inplace ' , ' add ' } , how to assign to out _ data . ' null ' means skip assignment , etc . in _ dat...
data = in_data [ 0 ] label = in_data [ 1 ] pred = mx . nd . SoftmaxOutput ( data , label ) self . assign ( out_data [ 0 ] , req [ 0 ] , pred )
def _get_timeframe_bounds ( self , timeframe , bucket_width ) : """Get a ` bucket _ width ` aligned ` start _ time ` and ` end _ time ` from a ` timeframe ` dict"""
if bucket_width : bucket_width_seconds = bucket_width bucket_width = epoch_time_to_kronos_time ( bucket_width ) # TODO ( derek ) : Potential optimization by setting the end _ time equal to the # untrusted _ time if end _ time > untrusted _ time and the results are not being # output to the user ( only for cachi...
def controller ( self ) : """Show current linked controllers ."""
if hasattr ( self , 'controllers' ) : if len ( self . controllers ) > 1 : # in the future , we should support more controllers raise TypeError ( "Only one controller per account." ) return self . controllers [ 0 ] raise AttributeError ( "There is no controller assigned." )
def get_exchanges ( self , vhost = None ) : """: returns : A list of dicts : param string vhost : A vhost to query for exchanges , or None ( default ) , which triggers a query for all exchanges in all vhosts ."""
if vhost : vhost = quote ( vhost , '' ) path = Client . urls [ 'exchanges_by_vhost' ] % vhost else : path = Client . urls [ 'all_exchanges' ] exchanges = self . _call ( path , 'GET' ) return exchanges
def happy_edges ( row , prefix = None ) : """Convert a row in HAPPY file and yield edges ."""
trans = maketrans ( "[](){}" , " " ) row = row . strip ( ) . strip ( "+" ) row = row . translate ( trans ) scfs = [ x . strip ( "+" ) for x in row . split ( ":" ) ] for a , b in pairwise ( scfs ) : oa = '<' if a . strip ( ) [ 0 ] == '-' else '>' ob = '<' if b . strip ( ) [ 0 ] == '-' else '>' is_uncert...
def evaluate ( loop_hparams , planner_hparams , policy_dir , model_dir , eval_metrics_dir , agent_type , eval_mode , eval_with_learner , log_every_steps , debug_video_path , num_debug_videos = 1 , random_starts_step_limit = None , report_fn = None , report_metric = None ) : """Evaluate ."""
if eval_with_learner : assert agent_type == "policy" if report_fn : assert report_metric is not None eval_metrics_writer = tf . summary . FileWriter ( eval_metrics_dir ) video_writers = ( ) kwargs = { } if eval_mode in [ "agent_real" , "agent_simulated" ] : if not eval_with_learner : if debug_video_...
def reset ( cls ) : """Resets the static state . Should only be called by tests ."""
cls . stats = StatContainer ( ) cls . parentMap = { } cls . containerMap = { } cls . subId = 0 for stat in gc . get_objects ( ) : if isinstance ( stat , Stat ) : stat . _aggregators = { }
def hms ( self , msg , tic = None , prt = sys . stdout ) : """Print elapsed time and message ."""
if tic is None : tic = self . tic now = timeit . default_timer ( ) hms = str ( datetime . timedelta ( seconds = ( now - tic ) ) ) prt . write ( '{HMS}: {MSG}\n' . format ( HMS = hms , MSG = msg ) ) return now
def etree ( self ) : """Returns a lxml object of the response ' s content that can be selected by xpath"""
if not hasattr ( self , '_elements' ) : try : parser = lxml . html . HTMLParser ( encoding = self . encoding ) self . _elements = lxml . html . fromstring ( self . content , parser = parser ) except LookupError : # lxml would raise LookupError when encoding not supported # try fromstring wit...
def add_node ( self , node_id , name , labels ) : """Add a node to the graph with name and labels . Args : node _ id : the unique node _ id e . g . ' www . evil4u . com ' name : the display name of the node e . g . ' evil4u ' labels : a list of labels e . g . [ ' domain ' , ' evil ' ] Returns : Nothing"...
self . neo_db . add_node ( node_id , name , labels )
def write_concrete_dag ( self ) : """Write all the nodes in the DAG to the DAG file ."""
if not self . __dag_file_path : raise CondorDAGError , "No path for DAG file" try : dagfile = open ( self . __dag_file_path , 'w' ) except : raise CondorDAGError , "Cannot open file " + self . __dag_file_path for node in self . __nodes : node . write_job ( dagfile ) node . write_vars ( dagfile ) ...
def build_search ( self ) : """Construct the ` ` Search ` ` object ."""
s = self . search ( ) s = self . query ( s , self . _query ) s = self . filter ( s ) if self . fields : s = self . highlight ( s ) s = self . sort ( s ) self . aggregate ( s ) return s
def main_plates ( sdat ) : """Plot several plates information ."""
# calculating averaged horizontal surface velocity # needed for redimensionalisation ilast = sdat . rprof . index . levels [ 0 ] [ - 1 ] rlast = sdat . rprof . loc [ ilast ] nprof = 0 uprof_averaged = rlast . loc [ : , 'vhrms' ] * 0 for step in sdat . walk . filter ( rprof = True ) : uprof_averaged += step . rprof ...
def set_post_evaluation_transform ( self , value ) : r"""Set the post processing transform applied after the prediction value from the tree ensemble . Parameters value : str A value denoting the transform applied . Possible values are : - " NoTransform " ( default ) . Do not apply a transform . - " Clas...
self . tree_spec . postEvaluationTransform = _TreeEnsemble_pb2 . TreeEnsemblePostEvaluationTransform . Value ( value )
def reply_inform ( cls , req_msg , * args ) : """Helper method for creating inform messages in reply to a request . Copies the message name and message identifier from request message . Parameters req _ msg : katcp . core . Message instance The request message that this inform if in reply to args : list o...
return cls ( cls . INFORM , req_msg . name , args , req_msg . mid )
def publish ( self , exchange , routing_key , body , properties = None ) : """Publish a message to RabbitMQ . If the RabbitMQ connection is not established or is blocked , attempt to wait until sending is possible . : param str exchange : The exchange to publish the message to . : param str routing _ key : Th...
future = concurrent . Future ( ) properties = properties or { } properties . setdefault ( 'app_id' , self . default_app_id ) properties . setdefault ( 'message_id' , str ( uuid . uuid4 ( ) ) ) properties . setdefault ( 'timestamp' , int ( time . time ( ) ) ) if self . ready : if self . publisher_confirmations : ...
def _raise_error_if_column_exists ( dataset , column_name = 'dataset' , dataset_variable_name = 'dataset' , column_name_error_message_name = 'column_name' ) : """Check if a column exists in an SFrame with error message ."""
err_msg = 'The SFrame {0} must contain the column {1}.' . format ( dataset_variable_name , column_name_error_message_name ) if column_name not in dataset . column_names ( ) : raise ToolkitError ( str ( err_msg ) )
def emit_children ( self , node ) : """Emit all the children of a node ."""
return "" . join ( [ self . emit_node ( child ) for child in node . children ] )
def ms_rotate ( self , viewer , event , data_x , data_y , msg = True ) : """Rotate the image by dragging the cursor left or right ."""
if not self . canrotate : return True msg = self . settings . get ( 'msg_rotate' , msg ) x , y = self . get_win_xy ( viewer ) if event . state == 'move' : self . _rotate_xy ( viewer , x , y ) elif event . state == 'down' : if msg : viewer . onscreen_message ( "Rotate (drag around center)" , delay = ...
def dumpDictHdf5 ( RV , o ) : """Dump a dictionary where each page is a list or an array"""
for key in list ( RV . keys ( ) ) : o . create_dataset ( name = key , data = SP . array ( RV [ key ] ) , chunks = True , compression = 'gzip' )
def isCountRate ( self ) : """isCountRate : Method or IRInputObject used to indicate if the science data is in units of counts or count rate . This method assumes that the keyword ' BUNIT ' is in the header of the input FITS file ."""
has_bunit = False if 'BUNIT' in self . _image [ 'sci' , 1 ] . header : has_bunit = True countrate = False if ( self . _image [ 0 ] . header [ 'UNITCORR' ] . strip ( ) == 'PERFORM' ) or ( has_bunit and self . _image [ 'sci' , 1 ] . header [ 'bunit' ] . find ( '/' ) != - 1 ) : countrate = True return countrate
def apply_inheritance ( self ) : """Apply inheritance over templates Template can be used in the following objects : : * hosts * contacts * services * servicedependencies * hostdependencies * timeperiods * hostsextinfo * servicesextinfo * serviceescalations * hostescalations * escalations ...
# inheritance properties by template self . hosts . apply_inheritance ( ) self . contacts . apply_inheritance ( ) self . services . apply_inheritance ( ) self . servicedependencies . apply_inheritance ( ) self . hostdependencies . apply_inheritance ( ) # Also timeperiods self . timeperiods . apply_inheritance ( ) # Als...
def set_state ( profile , state , store = 'local' ) : '''Configure the firewall state . . . versionadded : : 2018.3.4 . . versionadded : : 2019.2.0 Args : profile ( str ) : The firewall profile to configure . Valid options are : - domain - public - private state ( str ) : The firewall state . Va...
return salt . utils . win_lgpo_netsh . set_state ( profile = profile , state = state , store = store )
def from_mediaid ( cls , context : InstaloaderContext , mediaid : int ) : """Create a post object from a given mediaid"""
return cls . from_shortcode ( context , Post . mediaid_to_shortcode ( mediaid ) )
def epoch_to_log_line_timestamp ( epoch_time , time_zone = None ) : """Converts an epoch timestamp in ms to log line timestamp format , which is readible for humans . Args : epoch _ time : integer , an epoch timestamp in ms . time _ zone : instance of tzinfo , time zone information . Using pytz rather tha...
s , ms = divmod ( epoch_time , 1000 ) d = datetime . datetime . fromtimestamp ( s , tz = time_zone ) return d . strftime ( '%m-%d %H:%M:%S.' ) + str ( ms )
def get_composition_query_session_for_repository ( self , repository_id ) : """Gets a composition query session for the given repository . arg : repository _ id ( osid . id . Id ) : the ` ` Id ` ` of the repository return : ( osid . repository . CompositionQuerySession ) - a ` ` CompositionQuerySession ` ` ...
if not self . supports_composition_query ( ) : raise errors . Unimplemented ( ) # Also include check to see if the catalog Id is found otherwise raise errors . NotFound # pylint : disable = no - member return sessions . CompositionQuerySession ( repository_id , runtime = self . _runtime )
def lin_sim_calc ( goid1 , goid2 , sim_r , termcnts ) : '''Computes Lin ' s similarity measure using pre - calculated Resnik ' s similarities .'''
if sim_r is not None : info = get_info_content ( goid1 , termcnts ) + get_info_content ( goid2 , termcnts ) if info != 0 : return ( 2 * sim_r ) / info
def p_enum_list ( self , p ) : '''enum _ list : enum _ list COMMA ENUM _ VAL | ENUM _ VAL | empty'''
if p [ 1 ] is None : p [ 0 ] = [ ] elif len ( p ) == 4 : p [ 1 ] . append ( p [ 3 ] ) p [ 0 ] = p [ 1 ] elif len ( p ) == 2 : p [ 0 ] = [ p [ 1 ] ]
def _json_default_encoder ( func ) : """Monkey - Patch the core json encoder library . This isn ' t as bad as it sounds . We override the default method so that if an object falls through and can ' t be encoded normally , we see if it is a Future object and return the result to be encoded . I set a specia...
@ wraps ( func ) def inner ( self , o ) : try : return o . _redpipe_future_result # noqa except AttributeError : pass return func ( self , o ) return inner
def to_metric ( self , desc , tag_values , agg_data ) : """to _ metric translate the data that OpenCensus create to Prometheus format , using Prometheus Metric object : type desc : dict : param desc : The map that describes view definition : type tag _ values : tuple of : class : ` ~ opencensus . tags . t...
metric_name = desc [ 'name' ] metric_description = desc [ 'documentation' ] label_keys = desc [ 'labels' ] assert ( len ( tag_values ) == len ( label_keys ) ) # Prometheus requires that all tag values be strings hence # the need to cast none to the empty string before exporting . See # https : / / github . com / census...
def sendJabber ( sender , password , receivers , body , senderDomain = NOTIFY_IM_DOMAIN_SENDER , receiverDomain = NOTIFY_IM_DOMAIN_RECEIVER ) : """Sends an instant message to the inputted receivers from the given user . The senderDomain is an override to be used when no domain is supplied , same for the receive...
import xmpp # make sure there is a proper domain as part of the sender if '@' not in sender : sender += '@' + senderDomain # create a jabber user connection user = xmpp . protocol . JID ( sender ) # create a connection to an xmpp client client = xmpp . Client ( user . getDomain ( ) , debug = [ ] ) connection = clie...
def extend ( self , patterns ) : """Extend a : class : ` PatternSet ` with addition * patterns * * patterns * can either be : * A single : class : ` Pattern ` * Another : class : ` PatternSet ` or * A list of : class : ` Pattern ` instances"""
assert patterns is not None if isinstance ( patterns , Pattern ) : self . append ( patterns ) return if isinstance ( patterns , PatternSet ) : patterns = patterns . patterns assert all ( isinstance ( pat , Pattern ) for pat in patterns ) self . patterns . extend ( patterns ) self . _all_files = None
def handle ( self , * args , ** options ) : """get all the triggers that need to be handled"""
from django . db import connection connection . close ( ) failed_tries = settings . DJANGO_TH . get ( 'failed_tries' , 10 ) trigger = TriggerService . objects . filter ( Q ( provider_failed__lte = failed_tries ) | Q ( consumer_failed__lte = failed_tries ) , status = True , user__is_active = True , provider__name__statu...
def get_work_items ( self , ids , project = None , fields = None , as_of = None , expand = None , error_policy = None ) : """GetWorkItems . [ Preview API ] Returns a list of work items ( Maximum 200) : param [ int ] ids : The comma - separated list of requested work item ids . ( Maximum 200 ids allowed ) . : ...
route_values = { } if project is not None : route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' ) query_parameters = { } if ids is not None : ids = "," . join ( map ( str , ids ) ) query_parameters [ 'ids' ] = self . _serialize . query ( 'ids' , ids , 'str' ) if fields is not ...
def boot_priority ( self , boot_priority ) : """Sets the boot priority for this QEMU VM . : param boot _ priority : QEMU boot priority"""
self . _boot_priority = boot_priority log . info ( 'QEMU VM "{name}" [{id}] has set the boot priority to {boot_priority}' . format ( name = self . _name , id = self . _id , boot_priority = self . _boot_priority ) )
def _build_http_client ( cls , session : AppSession ) : '''Create the HTTP client . Returns : Client : An instance of : class : ` . http . Client ` .'''
# TODO : # recorder = self . _ build _ recorder ( ) stream_factory = functools . partial ( HTTPStream , ignore_length = session . args . ignore_length , keep_alive = session . args . http_keep_alive ) return session . factory . new ( 'HTTPClient' , connection_pool = session . factory [ 'ConnectionPool' ] , stream_facto...
def get_s3_region_from_endpoint ( endpoint ) : """Extracts and returns an AWS S3 region from an endpoint of form ` s3 - ap - southeast - 1 . amazonaws . com ` : param endpoint : Endpoint region to be extracted ."""
# Extract region by regex search . m = _EXTRACT_REGION_REGEX . search ( endpoint ) if m : # Regex matches , we have found a region . region = m . group ( 1 ) if region == 'external-1' : # Handle special scenario for us - east - 1 URL . return 'us-east-1' if region . startswith ( 'dualstack' ) : # Ha...
def define_residues_for_plotting_traj ( self , analysis_cutoff ) : """Since plotting all residues that have made contact with the ligand over a lenghty simulation is not always feasible or desirable . Therefore , only the residues that have been in contact with ligand for a long amount of time will be plotted i...
self . residue_counts_fraction = { } # Calculate the fraction of time a residue spends in each simulation for traj in self . residue_counts : self . residue_counts_fraction [ traj ] = { residue : float ( values ) / len ( self . contacts_per_timeframe [ traj ] ) for residue , values in self . residue_counts [ traj ]...
def visit_root ( self , _ , children ) : """The main node holding all the query . Arguments _ ( node ) : parsimonious . nodes . Node . children : list - 0 : for ` ` WS ` ` ( whitespace ) : ` ` None ` ` . - 1 : for ` ` NAMED _ RESOURCE ` ` : an instance of a subclass of ` ` . resources . Resource ` ` . -...
resource = children [ 1 ] resource . is_root = True return resource
def _reverse_to_source ( self , target , group1 ) : """Args : target ( dict ) : A table containing the reverse transitions for each state group1 ( list ) : A group of states Return : Set : A set of states for which there is a transition with the states of the group"""
new_group = [ ] for dst in group1 : new_group += target [ dst ] return set ( new_group )
def mark_stages ( self , start_time , length , stage_name ) : """Mark stages , only add the new ones . Parameters start _ time : int start time in s of the epoch being scored . length : int duration in s of the epoch being scored . stage _ name : str one of the stages defined in global stages ."""
y_pos = BARS [ 'stage' ] [ 'pos0' ] current_stage = STAGES . get ( stage_name , STAGES [ 'Unknown' ] ) # the - 1 is really important , otherwise we stay on the edge of the rect old_score = self . scene . itemAt ( start_time + length / 2 , y_pos + current_stage [ 'pos0' ] + current_stage [ 'pos1' ] - 1 , self . transfor...
def push_supply ( self , tokens ) : """Adds OPF and CPF data to a Generator ."""
logger . debug ( "Pushing supply data: %s" % tokens ) bus = self . case . buses [ tokens [ "bus_no" ] - 1 ] n_generators = len ( [ g for g in self . case . generators if g . bus == bus ] ) if n_generators == 0 : logger . error ( "No generator at bus [%s] for matching supply" % bus ) return elif n_generators > 1...
def plot_distributions ( y_true , scores , save_to , xlim = None , nbins = 100 , ymax = 3. , dpi = 150 ) : """Scores distributions This function will create ( and overwrite ) the following files : - { save _ to } . scores . png - { save _ to } . scores . eps Parameters y _ true : ( n _ samples , ) array -...
plt . figure ( figsize = ( 12 , 12 ) ) if xlim is None : xlim = ( np . min ( scores ) , np . max ( scores ) ) bins = np . linspace ( xlim [ 0 ] , xlim [ 1 ] , nbins ) plt . hist ( scores [ y_true ] , bins = bins , color = 'g' , alpha = 0.5 , normed = True ) plt . hist ( scores [ ~ y_true ] , bins = bins , color = '...
def readdatacommdct ( idfname , iddfile = 'Energy+.idd' , commdct = None ) : """read the idf file"""
if not commdct : block , commlst , commdct , idd_index = parse_idd . extractidddata ( iddfile ) theidd = eplusdata . Idd ( block , 2 ) else : theidd = iddfile data = eplusdata . Eplusdata ( theidd , idfname ) return data , commdct , idd_index