signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def visit_ListComp ( self , node ) : """Generate a curried lambda function [ x + y for x , y in [ [ 1 , 4 ] , [ 2 , 5 ] , [ 3 , 6 ] ] ] becomes [ [ 1 , 4 ] , [ 2 , 5 ] , [ 3 , 6 ] ] ] . map ( ( [ x , y ] ) = > x + y )"""
try : generator , = node . generators except ValueError : raise NotImplementedError ( 'Only single loop comprehensions are allowed' ) names = find_names ( generator . target ) argslist = [ ast . arg ( arg = name . id , annotation = None ) for name in names ] if len ( names ) <= 1 : signature = ast . argumen...
def print_results ( results , outfile ) : """Write results to outfile"""
for stanza_words , scheme in results : outfile . write ( str ( ' ' ) . join ( stanza_words ) + str ( '\n' ) ) outfile . write ( str ( ' ' ) . join ( map ( str , scheme ) ) + str ( '\n\n' ) ) outfile . close ( ) logging . info ( "Wrote result" )
def area ( self , value = None ) : """Get / set the surface area of actor . . . hint : : | largestregion . py | _"""
mass = vtk . vtkMassProperties ( ) mass . SetGlobalWarningDisplay ( 0 ) mass . SetInputData ( self . polydata ( ) ) mass . Update ( ) ar = mass . GetSurfaceArea ( ) if value is not None : if not ar : colors . printc ( "~bomb Area is zero: cannot rescale." , c = 1 , end = "" ) colors . printc ( " Con...
def sniff_field_spelling ( mlog , source ) : '''attempt to detect whether APM or PX4 attributes names are in use'''
position_field_type_default = position_field_types [ 0 ] # Default to PX4 spelling msg = mlog . recv_match ( source ) mlog . _rewind ( ) # Unfortunately it ' s either call this or return a mutated object position_field_selection = [ spelling for spelling in position_field_types if hasattr ( msg , spelling [ 0 ] ) ] ret...
async def send_friend_request ( self ) : """| coro | Sends the user a friend request . . . note : : This only applies to non - bot accounts . Raises Forbidden Not allowed to send a friend request to the user . HTTPException Sending the friend request failed ."""
await self . _state . http . send_friend_request ( username = self . name , discriminator = self . discriminator )
def resolve_deps ( base_dir , file_index ) : """Given a base directory and an initial set of files , retrieves dependencies and adds them to the file _ index ."""
def flatten ( tree , index = { } ) : for include in tree . get ( 'include' , [ ] ) : fname = base_dir + "/" + include assert os . path . exists ( fname ) , "File %s does not exist." % fname if fname not in index : index [ fname ] = read_spec ( fname ) index . update (...
def crawl_result_path ( result_path , include_log ) : """crawl _ result _ path ."""
result = { 'logs' : [ ] , 'args' : [ ] , 'commands' : [ ] , 'snapshots' : [ ] } if os . path . isdir ( result_path ) : if include_log : result [ 'logs' ] = load_result_json ( result_path , 'log' ) result [ 'args' ] = load_result_json ( result_path , 'args' ) result [ 'commands' ] = load_result_json ...
def serve_forever ( self , banner = None ) : """Interact with the user . : param banner : ( optional ) the banner to print before the first interaction . Defaults to ` ` None ` ` ."""
if hasattr ( readline , "read_history_file" ) : try : readline . read_history_file ( self . histfile ) except IOError : pass atexit . register ( self . _save_history ) super ( Shell , self ) . serve_forever ( banner )
def pull ( remote = 'origin' , branch = 'master' ) : """git pull commit"""
print ( cyan ( "Pulling changes from repo ( %s / %s)..." % ( remote , branch ) ) ) local ( "git pull %s %s" % ( remote , branch ) )
def send ( self , id_ , text , identities , context = None ) : """Send messages when using RapidSMS 0.14.0 or later . We can send multiple messages in one Tropo program , so we do that . : param id _ : Unused , included for compatibility with RapidSMS . : param string text : The message text to send . : p...
# Build our program from_ = self . config [ 'number' ] . replace ( '-' , '' ) commands = [ ] for identity in identities : # We ' ll include a ' message ' command for each recipient . # The Tropo doc explicitly says that while passing a list # of destination numbers is not a syntax error , only the # first number on the...
def size ( self , units = "MiB" ) : """Returns the physical volume size in the given units . Default units are MiB . * Args : * * units ( str ) : Unit label ( ' MiB ' , ' GiB ' , etc . . . ) . Default is MiB ."""
self . open ( ) size = lvm_pv_get_size ( self . handle ) self . close ( ) return size_convert ( size , units )
def transform_outgoing ( self , son , collection ) : """Recursively restore all transformed keys ."""
if isinstance ( son , dict ) : for ( key , value ) in son . items ( ) : if self . replacement in key : k = self . revert_key ( key ) son [ k ] = self . transform_outgoing ( son . pop ( key ) , collection ) elif isinstance ( value , dict ) : # recurse into sub - docs ...
def sort_args ( args ) : """Put flags at the end"""
args = args . copy ( ) flags = [ i for i in args if FLAGS_RE . match ( i [ 1 ] ) ] for i in flags : args . remove ( i ) return args + flags
def reconstruct_full_url ( self , port_override = None ) : """Reconstruct the full URL of a request . This is based on the URL reconstruction code in Python PEP 333: http : / / www . python . org / dev / peps / pep - 0333 / # url - reconstruction . Rebuild the hostname from the pieces available in the environ...
return '{0}://{1}{2}' . format ( self . url_scheme , self . reconstruct_hostname ( port_override ) , self . relative_url )
def refresh ( self ) : "Refresh an expired token"
# Construct the credentials for the verification request oauth = OAuth1 ( self . consumer_key , client_secret = self . consumer_secret , resource_owner_key = self . oauth_token , resource_owner_secret = self . oauth_token_secret , rsa_key = self . rsa_key , signature_method = self . _signature_method ) # Make the verif...
def images ( self , fields = None , token = None ) : """Returns image info keys for kind containing token Args : - fields : < list > image info values wanted - token : < str > substring to match image kind EXAMPLES Get all available image info : > > > page . images ( ) Get all image kinds : > > > pa...
if 'image' not in self . data : return out = [ ] for img in self . data [ 'image' ] : if token and token not in img [ 'kind' ] : continue info = { } for key in img : if fields and key not in fields : continue info . update ( { key : img [ key ] } ) if info : ...
def draw_figure ( self , data_for_color = None , data_for_size = None , data_for_clouds = None , rot_bonds = None , color_for_clouds = "Blues" , color_type_color = "viridis" ) : """Draws molecule through Molecule ( ) and then puts the final figure together with Figure ( ) ."""
self . molecule = Molecule ( self . topol_data ) self . draw = Draw ( self . topol_data , self . molecule , self . hbonds , self . pistacking , self . salt_bridges , self . lig_descr ) self . draw . draw_molecule ( data_for_color , data_for_size , data_for_clouds , rot_bonds , color_for_clouds , color_type_color ) self...
def on_menu_import_meas_file ( self , event ) : """Open measurement file , reset self . magic _ file and self . WD , and reset everything ."""
# use new measurement file and corresponding WD meas_file = self . choose_meas_file ( ) WD = os . path . split ( meas_file ) [ 0 ] self . WD = WD self . magic_file = meas_file # reset backend with new files self . reset_backend ( )
def delete ( self , name ) : """deletes model with given name"""
if name not in self . _parent : raise KeyError ( 'model "{}" not present' . format ( name ) ) del self . _parent [ name ] if self . _current_model_group == name : self . _current_model_group = None
def from_dict ( cls , dct , project = None , delim = ' | ' ) : r"""This method converts a correctly formatted dictionary into OpenPNM objects , and returns a handle to the * project * containing them . Parameters dct : dictionary The Python dictionary containing the data . The nesting and labeling of the ...
if project is None : project = ws . new_project ( ) # Uncategorize pore / throat and labels / properties , if present fd = FlatDict ( dct , delimiter = delim ) # If . is the delimiter , replace with | otherwise things break if delim == '.' : delim = ' | ' for key in list ( fd . keys ( ) ) : new_key ...
def init_app ( self , app ) : """Register this extension with the flask app . : param app : A flask application"""
# Save this so we can use it later in the extension if not hasattr ( app , 'extensions' ) : # pragma : no cover app . extensions = { } app . extensions [ 'flask-jwt-extended' ] = self # Set all the default configurations for this extension self . _set_default_configuration_options ( app ) self . _set_error_handler_...
def _find_existing_instance ( self ) : """I find existing VMs that are already running that might be orphaned instances of this worker ."""
if not self . connection : return None domains = yield self . connection . all ( ) for d in domains : name = yield d . name ( ) if name . startswith ( self . workername ) : self . domain = d break self . ready = True
def add_int ( self , n ) : """Add an integer to the stream . @ param n : integer to add @ type n : int"""
self . packet . write ( struct . pack ( '>I' , n ) ) return self
def getrange ( self , key_prefix , strip = False ) : """Get a range of keys starting with a common prefix as a mapping of keys to values . : param str key _ prefix : Common prefix among all keys : param bool strip : Optionally strip the common prefix from the key names in the returned dict : return dict :...
self . cursor . execute ( "select key, data from kv where key like ?" , [ '%s%%' % key_prefix ] ) result = self . cursor . fetchall ( ) if not result : return { } if not strip : key_prefix = '' return dict ( [ ( k [ len ( key_prefix ) : ] , json . loads ( v ) ) for k , v in result ] )
def equation_of_time_pvcdrom ( dayofyear ) : """Equation of time from PVCDROM . ` PVCDROM ` _ is a website by Solar Power Lab at Arizona State University ( ASU ) . . _ PVCDROM : http : / / www . pveducation . org / pvcdrom / 2 - properties - sunlight / solar - time Parameters dayofyear : numeric Returns...
# day angle relative to Vernal Equinox , typically March 22 ( day number 81) bday = _calculate_simple_day_angle ( dayofyear ) - ( 2.0 * np . pi / 365.0 ) * 80.0 # same value but about 2x faster than Spencer ( 1971) return 9.87 * np . sin ( 2.0 * bday ) - 7.53 * np . cos ( bday ) - 1.5 * np . sin ( bday )
def from_df ( cls , df_long , df_short ) : """Builds TripleOrbitPopulation from DataFrame ` ` DataFrame ` ` objects must be of appropriate form to pass to : func : ` OrbitPopulation . from _ df ` . : param df _ long , df _ short : : class : ` pandas . DataFrame ` objects to pass to : func : ` OrbitPopulat...
pop = cls ( 1 , 1 , 1 , 1 , 1 ) # dummy population pop . orbpop_long = OrbitPopulation . from_df ( df_long ) pop . orbpop_short = OrbitPopulation . from_df ( df_short ) return pop
def reduce_sort ( self , js_cmp = None , options = None ) : """Adds the Javascript built - in ` ` Riak . reduceSort ` ` to the query as a reduce phase . : param js _ cmp : A Javascript comparator function as specified by Array . sort ( ) : type js _ cmp : string : param options : phase options , containin...
if options is None : options = dict ( ) if js_cmp : options [ 'arg' ] = js_cmp return self . reduce ( "Riak.reduceSort" , options = options )
def connect ( self , interface , event , object_path , handler ) : """Connect to a DBus signal . If ` ` object _ path ` ` is None , subscribe for all objects and invoke the callback with the object _ path as its first argument ."""
if object_path : def callback ( connection , sender_name , object_path , interface_name , signal_name , parameters ) : return handler ( * unpack_variant ( parameters ) ) else : def callback ( connection , sender_name , object_path , interface_name , signal_name , parameters ) : return handler ( ...
def result_tree_list ( cl ) : """Displays the headers and data list together"""
import django result = { 'cl' : cl , 'result_headers' : list ( result_headers ( cl ) ) , 'results' : list ( tree_results ( cl ) ) } if django . VERSION [ 0 ] == 1 and django . VERSION [ 1 ] > 2 : from django . contrib . admin . templatetags . admin_list import result_hidden_fields result [ 'result_hidden_fields...
def check_errors ( self , response ) : "Check some common errors ."
# Read content . content = response . content if 'status' not in content : raise self . GeneralError ( 'We expect a status field.' ) # Return the decoded content if status is success . if content [ 'status' ] == 'success' : response . _content = content return # Expect messages if some kind of error . if 'm...
def result_report_class_wise_average ( self ) : """Report class - wise averages Returns str result report in string format"""
results = self . results_class_wise_average_metrics ( ) output = self . ui . section_header ( 'Class-wise average metrics (macro-average)' , indent = 2 ) + '\n' output += self . ui . line ( 'Accuracy' , indent = 2 ) + '\n' output += self . ui . data ( field = 'Accuracy' , value = float ( results [ 'accuracy' ] [ 'accur...
def read_hdf ( filename : PathLike , key : str ) -> AnnData : """Read ` ` . h5 ` ` ( hdf5 ) file . Note : Also looks for fields ` ` row _ names ` ` and ` ` col _ names ` ` . Parameters filename Filename of data file . key Name of dataset in the file ."""
with h5py . File ( filename , 'r' ) as f : # the following is necessary in Python 3 , because only # a view and not a list is returned keys = [ k for k in f . keys ( ) ] if key == '' : raise ValueError ( ( 'The file {} stores the following sheets:\n{}\n' 'Call read/read_hdf5 with one of them.' ) . forma...
def get_artist_tracks ( self , artist , cacheable = False ) : """Get a list of tracks by a given artist scrobbled by this user , including scrobble time ."""
# Not implemented : # " Can be limited to specific timeranges , defaults to all time . " warnings . warn ( "User.get_artist_tracks is deprecated and will be removed in a future " "version. User.get_track_scrobbles is a partial replacement. " "See https://github.com/pylast/pylast/issues/298" , DeprecationWarning , stack...
def xpath ( self , xpath , ** kwargs ) : """Perform an XPath query on the current node . : param string xpath : XPath query . : param dict kwargs : Optional keyword arguments that are passed through to the underlying XML library implementation . : return : results of the query as a list of : class : ` Node ...
result = self . adapter . xpath_on_node ( self . impl_node , xpath , ** kwargs ) if isinstance ( result , ( list , tuple ) ) : return [ self . _maybe_wrap_node ( r ) for r in result ] else : return self . _maybe_wrap_node ( result )
def alignment_changed ( self , settings , key , user_data ) : """If the gconf var window _ halignment be changed , this method will be called and will call the move function in guake ."""
RectCalculator . set_final_window_rect ( self . settings , self . guake . window ) self . guake . set_tab_position ( ) self . guake . force_move_if_shown ( )
def is_locked ( self ) : """Returns whether model is locked"""
if not self . __locked__ : return False elif self . get_parent ( ) : return self . get_parent ( ) . is_locked ( ) return True
def get_image_code ( self , id_code , access_token = None , user_id = None ) : """Get the image of a code , by its id"""
if access_token : self . req . credential . set_token ( access_token ) if user_id : self . req . credential . set_user_id ( user_id ) if not self . check_credentials ( ) : raise CredentialsError ( 'credentials invalid' ) return self . req . get ( '/Codes/' + id_code + '/export/png/url' )
def get_namespace_statistics ( self , namespace , start_offset , end_offset ) : """Get namespace statistics for the period between start _ offset and end _ offset ( inclusive )"""
cursor = self . cursor cursor . execute ( 'SELECT SUM(data_points), SUM(byte_count) ' 'FROM gauged_statistics WHERE namespace = %s ' 'AND offset BETWEEN %s AND %s' , ( namespace , start_offset , end_offset ) ) return [ long ( count or 0 ) for count in cursor . fetchone ( ) ]
def _filter_headers ( self ) : """Add headers designed for filtering messages based on objects . Returns : dict : Filter - related headers to be combined with the existing headers"""
headers = { } for user in self . usernames : headers [ "fedora_messaging_user_{}" . format ( user ) ] = True for package in self . packages : headers [ "fedora_messaging_rpm_{}" . format ( package ) ] = True for container in self . containers : headers [ "fedora_messaging_container_{}" . format ( container ...
def render_theming_css ( ) : """Template tag that renders the needed css files for the theming app ."""
css = getattr ( settings , 'ADMIN_TOOLS_THEMING_CSS' , False ) if not css : css = '/' . join ( [ 'admin_tools' , 'css' , 'theming.css' ] ) return mark_safe ( '<link rel="stylesheet" type="text/css" media="screen" href="%s" />' % staticfiles_storage . url ( css ) )
def optional_data ( self , product_type ) : """Schedules tasks , if any , that produce product _ type to be executed before the requesting task . There need not be any tasks that produce the required product type . All this method guarantees is that if there are any then they will be executed before the request...
self . _optional_dependencies . add ( product_type ) self . require_data ( product_type )
def available ( self , context ) : """Domain availability . : param resort . engine . execution . Context context : Current execution context ."""
try : if self . __available is None : status_code , msg = self . __endpoint . get ( "" ) self . __available = status_code == 200 except : self . __available = False return self . __available
def member ( self , user , objects = False ) : """Returns a user as a dict of attributes"""
try : member = self . search ( uid = user , objects = objects ) [ 0 ] except IndexError : return None if objects : return member return member [ 1 ]
def path_exists_or_creatable ( pathname : str ) -> bool : """Checks whether the given path exists or is creatable . This function is guaranteed to _ never _ raise exceptions . Returns ` True ` if the passed pathname is a valid pathname for the current OS _ and _ either currently exists or is hypothetically ...
try : # To prevent " os " module calls from raising undesirable exceptions on # invalid pathnames , is _ pathname _ valid ( ) is explicitly called first . return is_pathname_valid ( pathname ) and ( os . path . exists ( pathname ) or is_path_creatable ( pathname ) ) # Report failure on non - fatal filesystem compla...
def run ( self , cmd , fn = None , globals = None , locals = None ) : """Run the cmd ` cmd ` with trace"""
if globals is None : import __main__ globals = __main__ . __dict__ if locals is None : locals = globals self . reset ( ) if isinstance ( cmd , str ) : str_cmd = cmd cmd = compile ( str_cmd , fn or "<wdb>" , "exec" ) self . compile_cache [ id ( cmd ) ] = str_cmd if fn : from linecache import ...
def _calc_ML ( sampler , modelidx = 0 , e_range = None , e_npoints = 100 ) : """Get ML model from blob or compute them from chain and sampler . modelfn"""
ML , MLp , MLerr , ML_model = find_ML ( sampler , modelidx ) if e_range is not None : # prepare bogus data for calculation e_range = validate_array ( "e_range" , u . Quantity ( e_range ) , physical_type = "energy" ) e_unit = e_range . unit energy = ( np . logspace ( np . log10 ( e_range [ 0 ] . value ) , np...
def _proxy ( self ) : """Generate an instance context for the instance , the context is capable of performing various actions . All instance actions are proxied to the context : returns : AssetVersionContext for this AssetVersionInstance : rtype : twilio . rest . serverless . v1 . service . asset . asset _ ve...
if self . _context is None : self . _context = AssetVersionContext ( self . _version , service_sid = self . _solution [ 'service_sid' ] , asset_sid = self . _solution [ 'asset_sid' ] , sid = self . _solution [ 'sid' ] , ) return self . _context
def average_precision ( truth , recommend ) : """Average Precision ( AP ) . Args : truth ( numpy 1d array ) : Set of truth samples . recommend ( numpy 1d array ) : Ordered set of recommended samples . Returns : float : AP ."""
if len ( truth ) == 0 : if len ( recommend ) == 0 : return 1. return 0. tp = accum = 0. for n in range ( recommend . size ) : if recommend [ n ] in truth : tp += 1. accum += ( tp / ( n + 1. ) ) return accum / truth . size
def synchronized ( wrapped ) : """Synchronization decorator ."""
@ functools . wraps ( wrapped ) def wrapper ( * args , ** kwargs ) : self = args [ 0 ] with self . _lock : return wrapped ( * args , ** kwargs ) return wrapper
def load_field_config ( self , file_id ) : """Loads the configuration fields file for the id . : param file _ id : the id for the field : return : the fields configuration"""
if file_id not in self . _field_configs : self . _field_configs [ file_id ] = self . _reader . read_yaml_file ( 'field_config_%s.yml' % file_id ) return self . _field_configs [ file_id ]
def get_upcoming_events ( self ) : """Retreives a list of Notification _ Occurrence _ Events that have not ended yet : return : SoftLayer _ Notification _ Occurrence _ Event"""
mask = "mask[id, subject, startDate, endDate, statusCode, acknowledgedFlag, impactedResourceCount, updateCount]" _filter = { 'endDate' : { 'operation' : '> sysdate' } , 'startDate' : { 'operation' : 'orderBy' , 'options' : [ { 'name' : 'sort' , 'value' : [ 'ASC' ] } ] } } return self . client . call ( 'Notification_Occ...
async def join ( self , ctx ) : """Sends you the bot invite link ."""
perms = discord . Permissions . none ( ) perms . read_messages = True perms . send_messages = True perms . manage_messages = True perms . embed_links = True perms . read_message_history = True perms . attach_files = True perms . add_reactions = True await self . bot . send_message ( ctx . message . author , discord . u...
def within ( self , other : "Interval" , inclusive : bool = True ) -> bool : """Is this interval contained within the other ? Args : other : the : class : ` Interval ` to check inclusive : use inclusive rather than exclusive range checks ?"""
if not other : return False if inclusive : return self . start >= other . start and self . end <= other . end else : return self . start > other . start and self . end < other . end
def postcode ( self ) : """: example ' 101-1212'"""
return "%03d-%04d" % ( self . generator . random . randint ( 0 , 999 ) , self . generator . random . randint ( 0 , 9999 ) )
def read_global_register ( self , name , overwrite_config = False ) : '''The function reads the global register , interprets the data and returns the register value . Parameters name : register name overwrite _ config : bool The read values overwrite the config in RAM if true . Returns register value'''
self . register_utils . send_commands ( self . register . get_commands ( "ConfMode" ) ) with self . readout ( fill_buffer = True , callback = None , errback = None ) : commands = [ ] commands . extend ( self . register . get_commands ( "RdRegister" , name = name ) ) self . register_utils . send_commands ( c...
def space_angle ( phi1 , theta1 , phi2 , theta2 ) : """Also called Great - circle - distance - - use long - ass formula from wikipedia ( last in section ) : https : / / en . wikipedia . org / wiki / Great - circle _ distance # Computational _ formulas Space angle only makes sense in lon - lat , so convert zen...
from numpy import pi , sin , cos , arctan2 , sqrt , square lamb1 = pi / 2 - theta1 lamb2 = pi / 2 - theta2 lambdelt = lamb2 - lamb1 under = sin ( phi1 ) * sin ( phi2 ) + cos ( phi1 ) * cos ( phi2 ) * cos ( lambdelt ) over = sqrt ( np . square ( ( cos ( phi2 ) * sin ( lambdelt ) ) ) + square ( cos ( phi1 ) * sin ( phi2 ...
def _input_arg ( self , a ) : """Ask the user for input of a single argument . : param a : argparse . Action instance : return : the user input , asked according to the action"""
# if action of an argument that suppresses any other , just return if a . dest == SUPPRESS or a . default == SUPPRESS : return # prepare the prompt prompt = ( a . help or a . dest ) . capitalize ( ) r = { 'required' : a . required } # now handle each different action if self . is_action ( a , 'store' , 'append' ) :...
def get_version ( ) : """Obtain the version number"""
import imp import os mod = imp . load_source ( 'version' , os . path . join ( 'skdata' , '__init__.py' ) ) return mod . __version__
def onkeyup ( self , key , keycode , ctrl , shift , alt ) : """Called when user types and releases a key . The widget should be able to receive the focus in order to emit the event . Assign a ' tabindex ' attribute to make it focusable . Args : key ( str ) : the character value keycode ( str ) : the numer...
return ( key , keycode , ctrl , shift , alt )
def list_files ( self , remote_path , by = "name" , order = "desc" , limit = None , extra_params = None , is_share = False , ** kwargs ) : """获取目录下的文件列表 . : param remote _ path : 网盘中目录的路径 , 必须以 / 开头 。 . . warning : : * 路径长度限制为1000; * 径中不能包含以下字符 : ` ` \\ \\ ? | " > < : * ` ` ; * 文件名或路径名开头结尾不能是 ` ` . ` ` ...
if order == "desc" : desc = "1" else : desc = "0" params = dict ( ) if extra_params : params . update ( extra_params ) params [ 'dir' ] = remote_path params [ 'order' ] = by params [ 'desc' ] = desc if is_share : return self . _request ( '/share/list' , None , extra_params = params , url = "https://pan....
def update ( self , ** kwargs ) : """Updates the values for a QuantFigure The key - values are automatically assigned to the correct section of the QuantFigure"""
if 'columns' in kwargs : self . _d = ta . _ohlc_dict ( self . df , columns = kwargs . pop ( 'columns' , None ) ) schema = self . _get_schema ( ) annotations = kwargs . pop ( 'annotations' , None ) if annotations : self . layout [ 'annotations' ] [ 'values' ] = utils . make_list ( annotations ) for k , v in list...
def cli ( obj , ids , query , filters ) : """Delete alerts ."""
client = obj [ 'client' ] if ids : total = len ( ids ) else : if not ( query or filters ) : click . confirm ( 'Deleting all alerts. Do you want to continue?' , abort = True ) if query : query = [ ( 'q' , query ) ] else : query = build_query ( filters ) total , _ , _ = client ...
def _get_return_dict ( success = True , data = None , errors = None , warnings = None ) : '''PRIVATE METHOD Creates a new return dict with default values . Defaults may be overwritten . success : boolean ( True ) True indicates a successful result . data : dict < str , obj > ( { } ) Data to be returned to...
data = { } if data is None else data errors = [ ] if errors is None else errors warnings = [ ] if warnings is None else warnings ret = { 'success' : success , 'data' : data , 'errors' : errors , 'warnings' : warnings } return ret
def replace_in_file ( filename : str , text_from : str , text_to : str ) -> None : """Replaces text in a file . Args : filename : filename to process ( modifying it in place ) text _ from : original text to replace text _ to : replacement text"""
log . info ( "Amending {}: {} -> {}" , filename , repr ( text_from ) , repr ( text_to ) ) with open ( filename ) as infile : contents = infile . read ( ) contents = contents . replace ( text_from , text_to ) with open ( filename , 'w' ) as outfile : outfile . write ( contents )
def _getnode ( self , curie ) : """Returns IRI , or blank node curie / iri depending on self . skolemize _ blank _ node setting : param curie : str id as curie or iri : return :"""
if re . match ( r'^_:' , curie ) : if self . are_bnodes_skized is True : node = self . skolemizeBlankNode ( curie ) else : node = curie elif re . match ( r'^http|^ftp' , curie ) : node = curie elif len ( curie . split ( ':' ) ) == 2 : node = StreamedGraph . curie_util . get_uri ( curie )...
def linedelimited ( inlist , delimiter ) : """Returns a string composed of elements in inlist , with each element separated by ' delimiter . ' Used by function writedelimited . Use ' \t ' for tab - delimiting . Usage : linedelimited ( inlist , delimiter )"""
outstr = '' for item in inlist : if type ( item ) != StringType : item = str ( item ) outstr = outstr + item + delimiter outstr = outstr [ 0 : - 1 ] return outstr
def _try_mask_first_row ( row , values , all_close , ignore_order ) : '''mask first row in 2d array values : 2d masked array Each row is either fully masked or not masked at all ignore _ order : bool Ignore column order Return whether masked a row . If False , masked nothing .'''
for row2 in values : mask = ma . getmaskarray ( row2 ) assert mask . sum ( ) in ( 0 , len ( mask ) ) # sanity check : all or none masked if mask [ 0 ] : # Note : at this point row2 ' s mask is either all False or all True continue # mask each value of row1 in row2 if _try_mask_row ( row ...
def get ( which ) : "DEPRECATED ; see : func : ` ~ skyfield . data . hipparcos . load _ dataframe ( ) instead ."
if isinstance ( which , str ) : pattern = ( 'H| %6s' % which ) . encode ( 'ascii' ) for star in load ( lambda line : line . startswith ( pattern ) ) : return star else : patterns = set ( id . encode ( 'ascii' ) . rjust ( 6 ) for id in which ) return list ( load ( lambda line : line [ 8 : 14...
def next ( self ) : """# TODO : docstring : returns : # TODO : docstring"""
try : self . event , self . element = next ( self . iterator ) self . elementTag = clearTag ( self . element . tag ) except StopIteration : clearParsedElements ( self . element ) raise StopIteration return self . event , self . element , self . elementTag
def _generate_serial2 ( func , args_gen , kw_gen = None , ntasks = None , progkw = { } , verbose = None , nTasks = None ) : """internal serial generator"""
if verbose is None : verbose = 2 if ntasks is None : ntasks = nTasks if ntasks is None : ntasks = len ( args_gen ) if verbose > 0 : print ( '[ut._generate_serial2] executing %d %s tasks in serial' % ( ntasks , get_funcname ( func ) ) ) # kw _ gen can be a single dict applied to everything if kw_gen is N...
def preprocess_histogram ( hist , values , edges ) : """Handles edge - cases and extremely - skewed histograms"""
# working with extremely skewed histograms if np . count_nonzero ( hist ) == 0 : # all of them above upper bound if np . all ( values >= edges [ - 1 ] ) : hist [ - 1 ] = 1 # all of them below lower bound elif np . all ( values <= edges [ 0 ] ) : hist [ 0 ] = 1 return hist
def clear ( self ) : """Clear the contents of the data structure"""
self . title = None self . numbers = np . zeros ( 0 , int ) self . atom_types = [ ] # the atom _ types in the second column , used to associate ff parameters self . charges = [ ] # ff charges self . names = [ ] # a name that is unique for the molecule composition and connectivity self . molecules = np . zeros ( 0 , int...
def edit ( id : int , parent : int , alloc : Decimal ) : """Edit asset class"""
saved = False # load app = AppAggregate ( ) item = app . get ( id ) if not item : raise KeyError ( "Asset Class with id %s not found." , id ) if parent : assert parent != id , "Parent can not be set to self." # TODO check if parent exists ? item . parentid = parent saved = True # click . echo ( ...
def verify ( self , signature , msg ) : '''Verify the message'''
if not self . key : return False try : self . key . verify ( signature + msg ) except ValueError : return False return True
def redraw ( self ) : """Queue redraw . The redraw will be performed not more often than the ` framerate ` allows"""
if self . __drawing_queued == False : # if we are moving , then there is a timeout somewhere already self . __drawing_queued = True self . _last_frame_time = dt . datetime . now ( ) gobject . timeout_add ( 1000 / self . framerate , self . __redraw_loop )
def roll_out_and_store ( self , batch_info ) : """Roll out environment and store result in the replay buffer"""
self . model . train ( ) if self . env_roller . is_ready_for_sampling ( ) : rollout = self . env_roller . rollout ( batch_info , self . model , self . settings . rollout_steps ) . to_device ( self . device ) # Store some information about the rollout , no training phase batch_info [ 'frames' ] = rollout . f...
def predict_moments ( self , X ) : """Full predictive distribution from Bayesian linear regression . Parameters X : ndarray ( N * , d ) array query input dataset ( N * samples , d dimensions ) . Returns Ey : ndarray The expected value of y * for the query inputs , X * of shape ( N * , ) . Vy : ndarray...
check_is_fitted ( self , [ 'var_' , 'regularizer_' , 'weights_' , 'covariance_' , 'hypers_' ] ) X = check_array ( X ) Phi = self . basis . transform ( X , * atleast_list ( self . hypers_ ) ) Ey = Phi . dot ( self . weights_ ) Vf = ( Phi . dot ( self . covariance_ ) * Phi ) . sum ( axis = 1 ) return Ey , Vf + self . var...
def add_dependencies ( self , module ) : """Adds a module and its dependencies to the list of dependencies . Top - level entry point for adding a module and its dependecies ."""
if module in self . _processed_modules : return None if hasattr ( module , "__name__" ) : mn = module . __name__ else : mn = '<unknown>' _debug . debug ( "add_dependencies:module=%s" , module ) # If the module in which the class / function is defined is _ _ main _ _ , don ' t add it . Just add its dependenc...
def post_comment ( request , next = None , using = None ) : """Post a comment . HTTP POST is required ."""
# Fill out some initial data fields from an authenticated user , if present data = request . POST . copy ( ) if request . user . is_authenticated : data [ "user" ] = request . user else : return CommentPostBadRequest ( "You must be logged in to comment" ) # Look up the object we ' re trying to comment about cty...
def _handle_dist_server ( ds_type , repos_array ) : """Ask user for whether to use a type of dist server ."""
if ds_type not in ( "JDS" , "CDP" ) : raise ValueError ( "Must be JDS or CDP" ) prompt = "Does your JSS use a %s? (Y|N): " % ds_type result = loop_until_valid_response ( prompt ) if result : repo_dict = ElementTree . SubElement ( repos_array , "dict" ) repo_name_key = ElementTree . SubElement ( repo_dict , ...
def p_Callable ( p ) : '''Callable : NsContentName LPARENT | NsContentName SCOPEOP INDENTIFIER LPARENT | Expression LPARENT | STATIC SCOPEOP INDENTIFIER LPARENT'''
if len ( p ) <= 3 : p [ 0 ] = Callable ( p [ 1 ] , None ) else : p [ 0 ] = Callable ( p [ 1 ] , p [ 3 ] )
def _GetDiscoveryDocFromFlags ( args ) : """Get the discovery doc from flags ."""
if args . discovery_url : try : return util . FetchDiscoveryDoc ( args . discovery_url ) except exceptions . CommunicationError : raise exceptions . GeneratedClientError ( 'Could not fetch discovery doc' ) infile = os . path . expanduser ( args . infile ) or '/dev/stdin' with io . open ( infile ...
def html ( self ) : """Render this test class as html : return :"""
cases = [ x . html ( ) for x in self . cases ] return """ <hr size="2"/> <a name="{anchor}"> <div class="testclass"> <div>Test Class: {name}</div> <div class="testcases"> {cases} </div> </div> </a> """ . format ( anchor = se...
def _open_playlist ( self ) : """open playlist"""
self . _get_active_stations ( ) self . jumpnr = '' self . _random_requested = False txt = '''Reading playlists. Please wait...''' self . _show_help ( txt , NORMAL_MODE , caption = ' ' , prompt = ' ' , is_message = True ) self . selections [ self . operation_mode ] = [ self . selection , self . startPos , self . playing...
def event ( request , slug ) : """: param request : Django request object . : param event _ id : The ` id ` associated with the event . : param is _ preview : Should the listing page be generated as a preview ? This will allow preview specific actions to be done in the template such as turning off tracking ...
# If this is a preview make sure the user has appropriate permissions . event = get_object_or_404 ( models . EventBase . objects . visible ( ) , slug = slug ) context = RequestContext ( request , { 'event' : event , 'page' : event , } ) # TODO Not sure where the ` Event . template ` notion comes from , keeping it # her...
def prt_ev_cnts ( self , ctr , prt = sys . stdout ) : """Prints evidence code counts stored in a collections Counter ."""
for key , cnt in ctr . most_common ( ) : grp , name = self . get_grp_name ( key . replace ( "NOT " , "" ) ) prt . write ( "{CNT:7,} {EV:>7} {GROUP:<15} {NAME}\n" . format ( CNT = cnt , EV = key , GROUP = grp , NAME = name ) )
def Decorate ( cls , class_name , member , parent_member ) : """Decorates a member with @ typecheck . Inherit checks from parent member ."""
if isinstance ( member , property ) : fget = cls . DecorateMethod ( class_name , member . fget , parent_member ) fset = None if member . fset : fset = cls . DecorateMethod ( class_name , member . fset , parent_member ) fdel = None if member . fdel : fdel = cls . DecorateMethod ( clas...
def post ( self , request , * args , ** kwargs ) : """Method for handling POST requests . Unpublishes the the object by calling the object ' s unpublish method . The action is logged , the user is notified with a message . Returns a ' render redirect ' to the result of the ` get _ done _ url ` method ."""
self . object = self . get_object ( ) url = self . get_done_url ( ) if request . POST . get ( 'unpublish' ) : self . object . unpublish ( ) object_url = self . get_object_url ( ) self . log_action ( self . object , CMSLog . UNPUBLISH , url = object_url ) msg = self . write_message ( message = "%s unpubl...
def _set_signatures ( self ) : """Sets return and parameter types for the foreign C functions ."""
# We currently pass structs as void pointers . code_t = ctypes . c_int gpr_t = ctypes . c_int32 int32_t = ctypes . c_int32 node_p = ctypes . c_void_p pointer_t = ctypes . c_void_p state_p = ctypes . c_void_p void = None def sig ( rettype , fname , * ptypes ) : func = getattr ( self . lib , fname ) func . restyp...
def reachable_nodes_reverse ( self , p_id , p_recursive = True ) : """Find neighbors in the inverse graph ."""
return self . reachable_nodes ( p_id , p_recursive , True )
def update ( table , field , value , ** kwargs ) : """Convenience function to convert a field to a fixed value . Accepts the ` ` where ` ` keyword argument . See also : func : ` convert ` ."""
return convert ( table , field , lambda v : value , ** kwargs )
def inv_logistic ( y : Union [ float , np . ndarray ] , k : float , theta : float ) -> Optional [ float ] : r"""Inverse standard logistic function : . . math : : x = ( log ( \ frac { 1 } { y } - 1 ) / - k ) + \ theta Args : y : : math : ` y ` k : : math : ` k ` theta : : math : ` \ theta ` Returns : ...
if y is None or k is None or theta is None : return None # noinspection PyUnresolvedReferences return ( np . log ( ( 1 / y ) - 1 ) / - k ) + theta
def increase_crypto_config ( self , crypto_adapters , crypto_domain_configurations ) : """Add crypto adapters and / or crypto domains to the crypto configuration of this partition . The general principle for maintaining crypto configurations of partitions is as follows : Each adapter included in the crypto ...
crypto_adapter_uris = [ a . uri for a in crypto_adapters ] body = { 'crypto-adapter-uris' : crypto_adapter_uris , 'crypto-domain-configurations' : crypto_domain_configurations } self . manager . session . post ( self . uri + '/operations/increase-crypto-configuration' , body )
def nearest_keys ( self , key ) : """Find the nearest _ keys ( l2 distance ) thanks to a cKDTree query"""
if not isinstance ( key , tuple ) : _key = ( key , ) if self . __stale : self . generate_tree ( ) d , idx = self . __tree . query ( _key , self . k_neighbors , distance_upper_bound = self . distance_upper_bound ) try : return [ self . __keys [ id ] [ 0 ] for id in idx if id < len ( self . __keys ) ] except ...
def set_inasafe_default_value_qsetting ( qsetting , category , inasafe_field_key , value ) : """Helper method to set inasafe default value to qsetting . : param qsetting : QSettings . : type qsetting : QSettings : param category : Category of the default value . It can be global or recent . Global means the...
key = 'inasafe/default_value/%s/%s' % ( category , inasafe_field_key ) qsetting . setValue ( key , value )
def get_quantcols ( pattern , oldheader , coltype ) : """Searches for quantification columns using pattern and header list . Calls reader function to do regexp . Returns a single column for precursor quant ."""
if pattern is None : return False if coltype == 'precur' : return reader . get_cols_in_file ( pattern , oldheader , single_col = True )
def access_token ( self ) : """return an Oauth 2.0 Bearer access token if it can be found"""
access_token = self . get_auth_bearer ( ) if not access_token : access_token = self . query_kwargs . get ( 'access_token' , '' ) if not access_token : access_token = self . body_kwargs . get ( 'access_token' , '' ) return access_token
def gnupg_home ( ) : """Returns appropriate arguments if GNUPGHOME is set"""
if 'GNUPGHOME' in os . environ : gnupghome = os . environ [ 'GNUPGHOME' ] if not os . path . isdir ( gnupghome ) : raise CryptoritoError ( "Invalid GNUPGHOME directory" ) return [ "--homedir" , gnupghome ] else : return [ ]
def _dK_dR ( self , R ) : """Return numpy array of dK / dR from K1 up to and including Kn ."""
return - self . _ns * self . _N / R ** 2 / self . _sin_alpha
def tetrahedral_barycentric_coordinates ( tetra , pt ) : '''tetrahedral _ barycentric _ coordinates ( tetrahedron , point ) yields a list of weights for each vertex in the given tetrahedron in the same order as the vertices given . If all weights are 0 , then the point is not inside the tetrahedron .'''
# I found a description of this algorithm here ( Nov . 2017 ) : # http : / / steve . hollasch . net / cgindex / geometry / ptintet . html tetra = np . asarray ( tetra ) if tetra . shape [ 0 ] != 4 : if tetra . shape [ 1 ] == 4 : if tetra . shape [ 0 ] == 3 : tetra = np . transpose ( tetra , ( 1 ...