signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def try_ntimes ( _howmany , func , * argv , ** kwarg ) : """Try a function n times . Try to execute func ( * argv , * * kwarg ) ` ` _ howmany ` ` times . If it successfully run one time , then return as normal . If it fails N times , then raise the exception in the last run . * * 中文文档 * * 反复尝试一个函数或方法 ` ` ...
if ( not isinstance ( _howmany , int ) ) or ( _howmany < 1 ) : raise Exception ( "'_howmany' argument has to be int and greater than 0" ) counter = 1 while counter <= _howmany : try : return func ( * argv , ** kwarg ) except Exception as e : current_exception = e counter += 1 raise c...
async def init ( self ) -> None : '''Initialize configuration and start tasks .'''
self . stats = await self . insert ( self . stats ) self . configuration = await self . insert ( self . configuration ) if not self . executor : try : max_workers = self . config . get ( 'executor_workers' ) except Exception : max_workers = None self . executor = ThreadPoolExecutor ( max_wor...
def getmakeidfobject ( idf , key , name ) : """get idfobject or make it if it does not exist"""
idfobject = idf . getobject ( key , name ) if not idfobject : return idf . newidfobject ( key , Name = name ) else : return idfobject
def animate ( self , filename = 'constellation.mp4' , epochs = [ 1900 , 2100 ] , dt = 5 , dpi = 300 , fps = 10 , ** kw ) : '''Animate a finder chart .'''
scatter = self . finder ( ** kw ) plt . tight_layout ( ) figure = plt . gcf ( ) if '.gif' in filename : try : writer = ani . writers [ 'pillow' ] ( fps = fps ) except ( RuntimeError , KeyError ) : writer = ani . writers [ 'imagemagick' ] ( fps = fps ) except : raise RuntimeError ( 'T...
def enable ( self , key_id , ** kwargs ) : """Enable a deploy key for a project . Args : key _ id ( int ) : The ID of the key to enable * * kwargs : Extra options to send to the server ( e . g . sudo ) Raises : GitlabAuthenticationError : If authentication is not correct GitlabProjectDeployKeyError : If...
path = '%s/%s/enable' % ( self . path , key_id ) self . gitlab . http_post ( path , ** kwargs )
def set_last_col_idx ( self , last_col_idx ) : '''Parameters param last _ col _ idx : int number of columns'''
assert last_col_idx >= self . _max_col self . _max_col = last_col_idx return self
def _prepare_env ( self ) : # pragma : no cover """Setup the document ' s environment , if necessary ."""
env = self . state . document . settings . env if not hasattr ( env , self . directive_name ) : # Track places where we use this directive , so we can check for # outdated documents in the future . state = DirectiveState ( ) setattr ( env , self . directive_name , state ) else : state = getattr ( env , self...
def double_click ( self , on_element = None ) : """Double - clicks an element . : Args : - on _ element : The element to double - click . If None , clicks on current mouse position ."""
if on_element : self . move_to_element ( on_element ) if self . _driver . w3c : self . w3c_actions . pointer_action . double_click ( ) for _ in range ( 4 ) : self . w3c_actions . key_action . pause ( ) else : self . _actions . append ( lambda : self . _driver . execute ( Command . DOUBLE_CLICK ,...
def _handle_load ( cls , handler , file_object , validate = False , ** kwargs ) : """Loads caller , used by partial method for dynamic handler assignments . : param object handler : The loads handler : param file file _ object : The file object to load from : param bool validate : Performs content validation ...
return from_dict ( cls , handler . load ( cls , file_object , ** kwargs ) , validate = validate )
def place_items_in_square ( items , t ) : """Returns a list of rows that are stored as a priority queue to be used with heapq functions . > > > place _ items _ in _ square ( [ 1,5,7 ] , 4) [ ( 2 , 1 , [ ( 1 , 5 ) , ( 3 , 7 ) ] ) , ( 3 , 0 , [ ( 1 , 1 ) ] ) ] > > > place _ items _ in _ square ( [ 1,5,7 ] , 3...
# A minheap ( because that ' s all that heapq supports : / ) # of the length of each row . Why this is important is because # we ' ll be popping the largest rows when figuring out row displacements . # Each item is a tuple of ( t - | row | , y , [ ( xpos _ 1 , item _ 1 ) , . . . ] ) . # Until the call to heapq . heapif...
def is_sqlatype_date ( coltype : TypeEngine ) -> bool : """Is the SQLAlchemy column type a date type ?"""
coltype = _coltype_to_typeengine ( coltype ) # No longer valid in SQLAlchemy 1.2.11: # return isinstance ( coltype , sqltypes . _ DateAffinity ) return ( isinstance ( coltype , sqltypes . DateTime ) or isinstance ( coltype , sqltypes . Date ) )
def union_categoricals ( to_union , sort_categories = False , ignore_order = False ) : """Combine list - like of Categorical - like , unioning categories . All categories must have the same dtype . . . versionadded : : 0.19.0 Parameters to _ union : list - like of Categorical , CategoricalIndex , or Serie...
from pandas import Index , Categorical , CategoricalIndex , Series from pandas . core . arrays . categorical import _recode_for_categories if len ( to_union ) == 0 : raise ValueError ( 'No Categoricals to union' ) def _maybe_unwrap ( x ) : if isinstance ( x , ( CategoricalIndex , Series ) ) : return x ....
def ParseReportDescriptor ( rd , desc ) : """Parse the binary report descriptor . Parse the binary report descriptor into a DeviceDescriptor object . Args : rd : The binary report descriptor desc : The DeviceDescriptor object to update with the results from parsing the descriptor . Returns : None"""
rd = bytearray ( rd ) pos = 0 report_count = None report_size = None usage_page = None usage = None while pos < len ( rd ) : key = rd [ pos ] # First step , determine the value encoding ( either long or short ) . key_size , value_length = GetValueLength ( rd , pos ) if key & REPORT_DESCRIPTOR_KEY_MASK =...
def add_log_type ( name , display , color , bcolor ) : """name : call name ( A - Z and ' _ ' ) display : display message in [ - ] color : text color ( see bashutils . colors ) bcolor : background color ( see bashutils . colors )"""
global MESSAGE_LOG v_name = name . replace ( " " , "_" ) . upper ( ) val = 0 lkey = MESSAGE_LOG . keys ( ) while val in lkey : val += 1 MESSAGE_LOG [ val ] = [ v_name , ( display , color , bcolor , ) ] setattr ( LOG , v_name , val )
def format_error ( status = None , title = None , detail = None , code = None ) : '''Formatting JSON API Error Object Constructing an error object based on JSON API standard ref : http : / / jsonapi . org / format / # error - objects Args : status : Can be a http status codes title : A summary of error ...
error = { } error . update ( { 'title' : title } ) if status is not None : error . update ( { 'status' : status } ) if detail is not None : error . update ( { 'detail' : detail } ) if code is not None : error . update ( { 'code' : code } ) return error
def is_none_or ( self ) : """Ensures : attr : ` subject ` is either ` ` None ` ` , or satisfies subsequent ( chained ) conditions : : Ensure ( None ) . is _ none _ or . is _ an ( int )"""
if self . _subject is None : return NoOpInspector ( subject = self . _subject , error_factory = self . _error_factory ) else : return self
def get_dilation_rates ( hparams , width ) : """Get a list of valid dilation rates . Args : hparams : HParams . width : spatial dimension . Ensures that the effective filter size is not larger than the spatial dimension . Returns : allowed _ dilations : A list of dilation rates ."""
# dil _ rate = 1 means no dilation . allowed_dilations = [ [ 1 ] * 5 ] apply_dilations = hparams . get ( "latent_apply_dilations" , False ) dilation_rates = hparams . get ( "latent_dilation_rates" , [ 1 , 3 ] ) if apply_dilations : for rate in dilation_rates : # k + ( k - 1 ) * rate but k is harcoded to be 3 everyw...
def convert_depthtospace ( node , ** kwargs ) : """Map MXNet ' s depth _ to _ space operator attributes to onnx ' s DepthToSpace operator and return the created node ."""
name , input_nodes , attrs = get_inputs ( node , kwargs ) blksize = int ( attrs . get ( "block_size" , 0 ) ) node = onnx . helper . make_node ( "DepthToSpace" , input_nodes , [ name ] , blocksize = blksize , name = name , ) return [ node ]
def secret_finder ( self ) : """Parses the supplied secret . txt file for the consumer key and secrets"""
secretlist = list ( ) if os . path . isfile ( self . secret_file ) : # Open the file , and put the contents into a list with open ( self . secret_file , 'r' ) as secret : for line in secret : secretlist . append ( line . rstrip ( ) ) # Extract the key and secret from the list self . cons...
def to_pb ( self ) : """Converts the garbage collection rule to a protobuf . : rtype : : class : ` . table _ v2 _ pb2 . GcRule ` : returns : The converted current object ."""
max_age = _helpers . _timedelta_to_duration_pb ( self . max_age ) return table_v2_pb2 . GcRule ( max_age = max_age )
def labelForAction ( self , action ) : """Returns the label that contains the inputed action . : return < XDockActionLabel > | | None"""
for label in self . actionLabels ( ) : if label . action ( ) == action : return label return None
def axis_angle ( self ) : """: obj : ` numpy . ndarray ` of float : The axis - angle representation for the rotation ."""
qw , qx , qy , qz = self . quaternion theta = 2 * np . arccos ( qw ) omega = np . array ( [ 1 , 0 , 0 ] ) if theta > 0 : rx = qx / np . sqrt ( 1.0 - qw ** 2 ) ry = qy / np . sqrt ( 1.0 - qw ** 2 ) rz = qz / np . sqrt ( 1.0 - qw ** 2 ) omega = np . array ( [ rx , ry , rz ] ) return theta * omega
def write_data ( data ) : """Write the data to the data . json file Args : data ( dict ) : The updated data dictionary for Modis"""
sorted_dict = sort_recursive ( data ) with open ( _datafile , 'w' ) as file : _json . dump ( sorted_dict , file , indent = 2 )
def _get_ids_from_name_public ( self , name ) : """Get public images which match the given name ."""
results = self . list_public_images ( name = name ) return [ result [ 'id' ] for result in results ]
def list_nodes ( ) : '''List virtual machines . . code - block : : bash salt - cloud - Q'''
session = _get_session ( ) vms = session . xenapi . VM . get_all_records ( ) ret = { } for vm in vms : record = session . xenapi . VM . get_record ( vm ) if not record [ 'is_a_template' ] and not record [ 'is_control_domain' ] : try : base_template_name = record [ 'other_config' ] [ 'base_te...
def _startSchedulesNode ( self , name , attrs ) : """Process the start of a node under xtvd / schedules"""
if name == 'schedule' : self . _programId = attrs . get ( 'program' ) self . _stationId = attrs . get ( 'station' ) self . _time = self . _parseDateTime ( attrs . get ( 'time' ) ) self . _duration = self . _parseDuration ( attrs . get ( 'duration' ) ) self . _new = attrs . has_key ( 'new' ) self...
def get_spatial_type ( spatial_model ) : """Translate a spatial model string to a spatial type ."""
if spatial_model in [ 'SkyDirFunction' , 'PointSource' , 'Gaussian' ] : return 'SkyDirFunction' elif spatial_model in [ 'SpatialMap' ] : return 'SpatialMap' elif spatial_model in [ 'RadialGaussian' , 'RadialDisk' ] : try : import pyLikelihood if hasattr ( pyLikelihood , 'RadialGaussian' ) : ...
def plot_dendrogram ( ax , obj , show_diameters = True ) : '''Dendrogram of ` obj ` Args : obj : Neuron or tree neurom . Neuron , neurom . Tree show _ diameters : boolean Determines if node diameters will be show or not .'''
# create dendrogram and generate rectangle collection dnd = Dendrogram ( obj , show_diameters = show_diameters ) dnd . generate ( ) # render dendrogram and take into account neurite displacement which # starts as zero . It is important to avoid overlapping of neurites # and to determine tha limits of the figure . _rend...
def append ( self , key , _item ) : # type : ( Union [ Key , str ] , Any ) - > InlineTable """Appends a ( key , item ) to the table ."""
if not isinstance ( _item , Item ) : _item = item ( _item ) if not isinstance ( _item , ( Whitespace , Comment ) ) : if not _item . trivia . indent and len ( self . _value ) > 0 : _item . trivia . indent = " " if _item . trivia . comment : _item . trivia . comment = "" self . _value . append...
def cancel ( self , consumer_tag = None ) : """Cancels the current consuming action by using the stored consumer _ tag . If a consumer _ tag is given , that one is used instead . Parameters consumer _ tag : string Tag of consumer to cancel"""
if not consumer_tag : if not hasattr ( self , "consumer_tag" ) : return consumer_tag = self . consumer_tag self . channel . basic_cancel ( consumer_tag )
def read_logodata ( handle ) : """Get weblogo data for a sequence alignment . Returns a list of tuples : ( posn , letter _ counts , entropy , weight )"""
seqs = weblogolib . read_seq_data ( handle , alphabet = unambiguous_protein_alphabet ) ldata = weblogolib . LogoData . from_seqs ( seqs ) letters = ldata . alphabet . letters ( ) counts = ldata . counts . array logodata = [ ] for i , coldata , entropy , weight in zip ( range ( len ( counts ) ) , counts , ldata . entrop...
async def service_observable ( self , limit ) -> int : """Service the observable ' s inBox and outBox : return : the number of messages successfully serviced"""
if not self . isReady ( ) : return 0 o = self . _service_observable_out_box ( limit ) i = await self . _observable . serviceQueues ( limit ) return o + i
def set_instance ( self , thing : type , value , overwrite = False ) : """Set an instance of a thing ."""
if thing in self . instances and not overwrite : raise DiayException ( 'instance for %r already exists' % thing ) self . instances [ thing ] = value
def factory ( resp ) : """Return a ResponseError subclass based on the API payload . All errors are documented : https : / / docs . mollie . com / guides / handling - errors # all - possible - status - codes More exceptions should be added here when appropriate , and when useful examples of API errors are avail...
status = resp [ 'status' ] if status == 401 : return UnauthorizedError ( resp ) elif status == 404 : return NotFoundError ( resp ) elif status == 422 : return UnprocessableEntityError ( resp ) else : # generic fallback return ResponseError ( resp )
def _to_dict ( self ) : """Return a json dictionary representing this model ."""
_dict = { } if hasattr ( self , 'begin' ) and self . begin is not None : _dict [ 'begin' ] = self . begin if hasattr ( self , 'end' ) and self . end is not None : _dict [ 'end' ] = self . end return _dict
def data ( self , index , role = QtCore . Qt . UserRole ) : """Used by the view to determine data to present See : qtdoc : ` QAbstractItemModel < QAbstractItemModel . data > ` , and : qtdoc : ` subclassing < qabstractitemmodel . subclassing > `"""
if role == QtCore . Qt . DisplayRole : row = index . row ( ) field = self . _headers [ index . column ( ) ] val = self . model . paramValue ( row , field ) if 1 <= index . column ( ) <= 3 : # standard units for data , not necessary current for UI # view will scale and convert appropriately u...
def on_message ( self , unused_channel , basic_deliver , properties , body ) : """Called on receipt of a message from a queue . Processes the message using the self . _ process method or function and positively acknowledges the queue if successful . If processing is not succesful , the message can either be r...
if self . check_tx_id : try : tx_id = self . tx_id ( properties ) logger . info ( 'Received message' , queue = self . _queue , delivery_tag = basic_deliver . delivery_tag , app_id = properties . app_id , tx_id = tx_id ) except KeyError as e : self . reject_message ( basic_deliver . deliv...
def get_feed_posts ( self ) -> Iterator [ Post ] : """Get Posts of the user ' s feed . : return : Iterator over Posts of the user ' s feed ."""
data = self . context . graphql_query ( "d6f4427fbe92d846298cf93df0b937d3" , { } ) [ "data" ] while True : feed = data [ "user" ] [ "edge_web_feed_timeline" ] yield from ( Post ( self . context , edge [ "node" ] ) for edge in feed [ "edges" ] if not edge [ "node" ] [ "__typename" ] == "GraphSuggestedUserFeedUni...
def get_recursive_subclasses ( cls ) : """Return list of all subclasses for a class , including subclasses of direct subclasses"""
return cls . __subclasses__ ( ) + [ g for s in cls . __subclasses__ ( ) for g in get_recursive_subclasses ( s ) ]
def _print_percent ( self ) : '''Print how much is done in percentage .'''
fraction_done = ( ( self . continue_value or 0 + self . current_value ) / self . max_value ) self . _print ( '{fraction_done:.1%}' . format ( fraction_done = fraction_done ) )
def status ( self , obj ) : """Get the wifi interface status ."""
reply = self . _send_cmd_to_wpas ( obj [ 'name' ] , 'STATUS' , True ) result = reply . split ( '\n' ) status = '' for l in result : if l . startswith ( 'wpa_state=' ) : status = l [ 10 : ] return status_dict [ status . lower ( ) ]
def push_subscription_decrypt_push ( self , data , decrypt_params , encryption_header , crypto_key_header ) : """Decrypts ` data ` received in a webpush request . Requires the private key dict from ` push _ subscription _ generate _ keys ( ) ` _ ( ` decrypt _ params ` ) as well as the Encryption and server Cryp...
salt = self . __decode_webpush_b64 ( encryption_header . split ( "salt=" ) [ 1 ] . strip ( ) ) dhparams = self . __decode_webpush_b64 ( crypto_key_header . split ( "dh=" ) [ 1 ] . split ( ";" ) [ 0 ] . strip ( ) ) p256ecdsa = self . __decode_webpush_b64 ( crypto_key_header . split ( "p256ecdsa=" ) [ 1 ] . strip ( ) ) d...
def count_single_dots ( self ) : """Count all strokes of this recording that have only a single dot ."""
pointlist = self . get_pointlist ( ) single_dots = 0 for stroke in pointlist : if len ( stroke ) == 1 : single_dots += 1 return single_dots
def _lua_to_python ( lval , return_status = False ) : """Convert Lua object ( s ) into Python object ( s ) , as at times Lua object ( s ) are not compatible with Python functions"""
import lua lua_globals = lua . globals ( ) if lval is None : # Lua None - - > Python None return None if lua_globals . type ( lval ) == "table" : # Lua table - - > Python list pval = [ ] for i in lval : if return_status : if i == 'ok' : return lval [ i ] if i ...
def _get_setter_fun ( object_type , # type : Type parameter , # type : Parameter private_property_name # type : str ) : """Utility method to find the overridden setter function for a given property , or generate a new one : param object _ type : : param property _ name : : param property _ type : : param pr...
# the property will have the same name than the constructor argument property_name = parameter . name overridden_setters = getmembers ( object_type , _has_annotation ( __SETTER_OVERRIDE_ANNOTATION , property_name ) ) if len ( overridden_setters ) > 0 : # - - check that we only have one if len ( overridden_setters )...
def compute ( chart ) : """Computes the behavior ."""
factors = [ ] # Planets in House1 or Conjunct Asc house1 = chart . getHouse ( const . HOUSE1 ) planetsHouse1 = chart . objects . getObjectsInHouse ( house1 ) asc = chart . getAngle ( const . ASC ) planetsConjAsc = chart . objects . getObjectsAspecting ( asc , [ 0 ] ) _set = _merge ( planetsHouse1 , planetsConjAsc ) fac...
def time_correlation_by_diagonalization ( P , pi , obs1 , obs2 = None , time = 1 , rdl = None ) : """calculates time correlation . Raises P to power ' times ' by diagonalization . If rdl tuple ( R , D , L ) is given , it will be used for further calculation ."""
if rdl is None : raise ValueError ( "no rdl decomposition" ) R , D , L = rdl d_times = np . diag ( D ) ** time diag_inds = np . diag_indices_from ( D ) D_time = np . zeros ( D . shape , dtype = d_times . dtype ) D_time [ diag_inds ] = d_times P_time = np . dot ( np . dot ( R , D_time ) , L ) # multiply element - wi...
def builddata ( self , mopt = None , data = None , pdata = None , prior = None ) : """Rebuild pdata to account for marginalization ."""
if pdata is None : if data is None : raise ValueError ( 'no data or pdata' ) pdata = gvar . BufferDict ( ) for m in self . flatmodels : pdata [ m . datatag ] = ( m . builddata ( data ) if m . ncg <= 1 else MultiFitter . coarse_grain ( m . builddata ( data ) , m . ncg ) ) else : npdata = ...
def items_iter ( self , limit ) : '''Get an iterator of the ' items ' in each page . Instead of a feature collection from each page , the iterator yields the features . : param int limit : The number of ' items ' to limit to . : return : iter of items in page'''
pages = ( page . get ( ) for page in self . _pages ( ) ) items = itertools . chain . from_iterable ( ( p [ self . ITEM_KEY ] for p in pages ) ) if limit is not None : items = itertools . islice ( items , limit ) return items
def parse ( lang_sample ) : """tally word popularity using novel extracts , etc"""
words = words_from_archive ( lang_sample , include_dups = True ) counts = zero_default_dict ( ) for word in words : counts [ word ] += 1 return set ( words ) , counts
def send_post ( self , mri , method_name , ** params ) : """Abstract method to dispatch a Post to the server Args : mri ( str ) : The mri of the Block method _ name ( str ) : The name of the Method within the Block params : The parameters to send Returns : The return results from the server"""
typ , parameters = convert_to_type_tuple_value ( serialize_object ( params ) ) uri = NTURI ( typ [ 2 ] ) uri = uri . wrap ( path = "%s.%s" % ( mri , method_name ) , kws = parameters , scheme = "pva" ) value = self . _ctxt . rpc ( mri , uri , timeout = None ) return convert_value_to_dict ( value )
def main ( ) : """Main program ."""
args = command . parse_args ( ) with btrfs . FileSystem ( args . dir ) as mount : # mount . rescanSizes ( ) fInfo = mount . FS_INFO ( ) pprint . pprint ( fInfo ) vols = mount . subvolumes # for dev in mount . devices : # pprint . pprint ( dev ) for vol in vols : print ( vol ) return 0
def dynamic ( cls , label , val_mean , val_range ) : """Creates a static parameter . Parameters label : str A human - readable label for the parameter . val _ mean : float The mean value of the parameter . val _ range : float The minimum and maximum variance from the mean allowed for parameter ."""
return cls ( label , ParameterType . DYNAMIC , ( val_mean , val_range ) )
def validate_url ( url ) : """Validates the URL : param url : : return :"""
if validators . url ( url ) : return url elif validators . domain ( url ) : return "http://{}" . format ( url ) return ""
def outerproduct ( a , b ) : """Numeric . outerproduct ( [ 0.46474895 , 0.46348238 , 0.53923529 , 0.46428344 , 0.50223047 ] , [ - 0.16049719 , 0.17086812 , 0.1692107 , 0.17433657 , 0.1738235 , 0.17292975 , 0.17553493 , 0.17222987 , - 0.17038313 , 0.17725782, 0.18428386 ] ) = > [ [ - 0.0745909 , 0.07941078 ,...
result = zeros ( ( len ( a ) , len ( b ) ) ) for i in range ( len ( a ) ) : for j in range ( len ( b ) ) : result [ i ] [ j ] = a [ i ] * b [ j ] return result
def str_dict_cast ( dict_ , include_keys = True , include_vals = True , ** kwargs ) : """Converts any bytes - like items in input dict to string - like values , with respect to python version Parameters dict _ : dict any bytes - like objects contained in the dict will be converted to a string include _ ...
new_keys = str_list_cast ( dict_ . keys ( ) , ** kwargs ) if include_keys else dict_ . keys ( ) new_vals = str_list_cast ( dict_ . values ( ) , ** kwargs ) if include_vals else dict_ . values ( ) new_dict = dict ( zip_ ( new_keys , new_vals ) ) return new_dict
def program_checks ( job , input_args ) : """Checks that dependency programs are installed . input _ args : dict Dictionary of input arguments ( from main ( ) )"""
# Program checks for program in [ 'curl' , 'docker' , 'unzip' , 'samtools' ] : assert which ( program ) , 'Program "{}" must be installed on every node.' . format ( program ) job . addChildJobFn ( download_shared_files , input_args )
def get_email_body ( self , sample ) : """Returns the email body text"""
retest = sample . getRetest ( ) lab_address = api . get_bika_setup ( ) . laboratory . getPrintAddress ( ) setup = api . get_setup ( ) body = Template ( setup . getEmailBodySampleInvalidation ( ) ) . safe_substitute ( dict ( sample_link = self . get_html_link ( sample ) , retest_link = self . get_html_link ( retest ) , ...
def to_df ( self , recommended_only = False , include_io = True ) : """Return a pandas DataFrame for each model and dataset . Parameters recommended _ only : bool , optional If True , only recommended models for each session are included . If no model is recommended , then a row with it ' s ID will be inclu...
od = BMDS . _df_ordered_dict ( include_io ) [ session . _add_to_to_ordered_dict ( od , i , recommended_only ) for i , session in enumerate ( self ) ] return pd . DataFrame ( od )
def run ( configobj = None ) : """TEAL interface for the ` acsccd ` function ."""
acsccd ( configobj [ 'input' ] , exec_path = configobj [ 'exec_path' ] , time_stamps = configobj [ 'time_stamps' ] , verbose = configobj [ 'verbose' ] , quiet = configobj [ 'quiet' ] # dqicorr = configobj [ ' dqicorr ' ] , # atodcorr = configobj [ ' atodcorr ' ] , # blevcorr = configobj [ ' blevcorr ' ] , # biascorr = ...
async def check_authorized ( self , identity ) : """Works like : func : ` Security . identity ` , but when check is failed : func : ` UnauthorizedError ` exception is raised . : param identity : Claim : return : Checked claim or return ` ` None ` ` : raise : : func : ` UnauthorizedError `"""
identify = await self . identify ( identity ) if identify is None : raise UnauthorizedError ( ) return identify
def vote_total ( self ) : """Calculates vote total as total _ upvotes - total _ downvotes . We are adding a method here instead of relying on django - secretballot ' s addition since that doesn ' t work for subclasses ."""
modelbase_obj = self . modelbase_obj return modelbase_obj . votes . filter ( vote = + 1 ) . count ( ) - modelbase_obj . votes . filter ( vote = - 1 ) . count ( )
def load_file ( self , path = None , just_settings = False ) : """Loads a data file . After the file is loaded , calls self . after _ load _ file ( self ) , which you can overwrite if you like ! just _ settings = True will only load the configuration of the controls , and will not plot anything or run after _...
# if it ' s just the settings file , make a new databox if just_settings : d = _d . databox ( ) header_only = True # otherwise use the internal databox else : d = self header_only = False # import the settings if they exist in the header if not None == _d . databox . load_file ( d , path , filters = sel...
def _records_commit ( record_ids ) : """Commit all records ."""
for record_id in record_ids : record = Record . get_record ( record_id ) record . commit ( )
def get_next_token ( string ) : '''" eats " up the string until it hits an ending character to get valid leaf expressions . For example , given \\ Phi _ { z } ( L ) = \\ sum _ { i = 1 } ^ { N } \\ frac { 1 } { C _ { i } \\ times V _ { \\ rm max , i } } , this function would pull out \\ Phi , stopping at _ @ s...
STOP_CHARS = "_ {}^ \n ,()=" UNARY_CHARS = "^_" # ^ and _ are valid leaf expressions - - just ones that should be handled on their own if string [ 0 ] in STOP_CHARS : return string [ 0 ] , string [ 1 : ] expression = [ ] for i , c in enumerate ( string ) : if c in STOP_CHARS : break else : e...
def _build_models_query ( self , query ) : """Builds a query from ` query ` that filters to documents only from registered models ."""
registered_models_ct = self . build_models_list ( ) if registered_models_ct : restrictions = [ xapian . Query ( '%s%s' % ( TERM_PREFIXES [ DJANGO_CT ] , model_ct ) ) for model_ct in registered_models_ct ] limit_query = xapian . Query ( xapian . Query . OP_OR , restrictions ) query = xapian . Query ( xapian ...
def get_domain_connect_template_async_context ( self , domain , provider_id , service_id , redirect_uri , params = None , state = None , service_id_in_path = False ) : """Makes full Domain Connect discovery of a domain and returns full context to request async consent . : param domain : str : param provider _ i...
if params is None : params = { } config = self . get_domain_config ( domain ) self . check_template_supported ( config , provider_id , service_id ) if config . urlAsyncUX is None : raise InvalidDomainConnectSettingsException ( "No asynch UX URL in config" ) if service_id_in_path : if type ( service_id ) is ...
def _get_identifiers ( self , limit ) : """This will process the id mapping file provided by Biogrid . The file has a very large header , which we scan past , then pull the identifiers , and make equivalence axioms : param limit : : return :"""
LOG . info ( "getting identifier mapping" ) line_counter = 0 f = '/' . join ( ( self . rawdir , self . files [ 'identifiers' ] [ 'file' ] ) ) myzip = ZipFile ( f , 'r' ) # assume that the first entry is the item fname = myzip . namelist ( ) [ 0 ] foundheader = False # TODO align this species filter with the one above #...
def fetch_plos_images ( article_doi , output_dir , document ) : """Fetch the images for a PLoS article from the internet . PLoS images are known through the inspection of < graphic > and < inline - graphic > elements . The information in these tags are then parsed into appropriate URLs for downloading ."""
log . info ( 'Processing images for {0}...' . format ( article_doi ) ) # A dict of URLs for PLoS subjournals journal_urls = { 'pgen' : 'http://www.plosgenetics.org/article/{0}' , 'pcbi' : 'http://www.ploscompbiol.org/article/{0}' , 'ppat' : 'http://www.plospathogens.org/article/{0}' , 'pntd' : 'http://www.plosntds.org/...
def _convert_sam_function_resource ( name , resource_properties , layers ) : """Converts a AWS : : Serverless : : Function resource to a Function configuration usable by the provider . : param string name : LogicalID of the resource NOTE : This is * not * the function name because not all functions declare a na...
codeuri = SamFunctionProvider . _extract_sam_function_codeuri ( name , resource_properties , "CodeUri" ) LOG . debug ( "Found Serverless function with name='%s' and CodeUri='%s'" , name , codeuri ) return Function ( name = name , runtime = resource_properties . get ( "Runtime" ) , memory = resource_properties . get ( "...
def status ( self ) : """Set messages"""
self . count_repo += 1 if self . check == 1 : self . count_news += 1 self . st = "{0}News in ChangeLog.txt{1}" . format ( self . meta . color [ "GREEN" ] , self . meta . color [ "ENDC" ] ) elif self . check == 0 : self . st = "No changes in ChangeLog.txt"
def set_button_visible ( self , visible ) : """Sets the clear button as ` ` visible ` ` : param visible : Visible state ( True = visible , False = hidden ) ."""
self . button . setVisible ( visible ) left , top , right , bottom = self . getTextMargins ( ) if visible : right = self . _margin + self . _spacing else : right = 0 self . setTextMargins ( left , top , right , bottom )
def native ( self ) : """The native Python datatype representation of this value : return : A unicode string or None"""
if self . contents is None : return None if self . _native is None : self . _native = self . _map [ self . __int__ ( ) ] return self . _native
def get_wifiinfo ( self , callb = None ) : """Convenience method to request the wifi info from the device This will request the information from the device and request that callb be executed when a response is received . The is no default callback : param callb : Callable to be used when the response is recei...
response = self . req_with_resp ( GetWifiInfo , StateWifiInfo , callb = callb ) return None
def delete ( node_name ) : """Delete a specific node"""
result = { } node = nago . core . get_node ( node_name ) if not node : result [ 'status' ] = 'error' result [ 'message' ] = "node not found." else : node . delete ( ) result [ 'status' ] = 'success' result [ 'message' ] = 'node deleted.' return result
def read_l2tp ( self , length ) : """Read Layer Two Tunnelling Protocol . Structure of L2TP header [ RFC 2661 ] : 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 | T | L | x | x | S | x | O | P | x | x | x | x | Ver | Length ( opt ) | | Tunnel ID | Session ID | | Ns ( opt ) | Nr ...
if length is None : length = len ( self ) _flag = self . _read_binary ( 1 ) _vers = self . _read_fileng ( 1 ) . hex ( ) [ 1 ] _hlen = self . _read_unpack ( 2 ) if int ( _flag [ 1 ] ) else None _tnnl = self . _read_unpack ( 2 ) _sssn = self . _read_unpack ( 2 ) _nseq = self . _read_unpack ( 2 ) if int ( _flag [ 4 ] ...
def scan_patch ( project , patch_file , binaries , ips , urls , file_audit_list , file_audit_project_list , flag_list , ignore_list , file_ignore , ignore_directories , url_ignore , ip_ignore , apikey ) : """Scan actions for each commited file in patch set"""
global failure split_path = patch_file . split ( project + '/' , 1 ) [ - 1 ] if not any ( x in split_path for x in ignore_directories ) : if is_binary ( patch_file ) and binaries : hashlist = get_lists . GetLists ( ) binary_hash = hashlist . binary_hash ( project , split_path ) with open ( p...
def model_typedefs ( vk , model ) : """Fill the model with typedefs model [ ' typedefs ' ] = { ' name ' : ' type ' , . . . }"""
model [ 'typedefs' ] = { } # bitmasks and basetypes bitmasks = [ x for x in vk [ 'registry' ] [ 'types' ] [ 'type' ] if x . get ( '@category' ) == 'bitmask' ] basetypes = [ x for x in vk [ 'registry' ] [ 'types' ] [ 'type' ] if x . get ( '@category' ) == 'basetype' ] for typedef in bitmasks + basetypes : if not typ...
def newest ( self ) : """Gets the newest entry in the view , regardless of sort order"""
if self . _order_by == 'newest' : return self . first if self . _order_by == 'oldest' : return self . last return max ( self . entries , key = lambda x : ( x . date , x . id ) )
def enabled ( self ) : """whether the user is allowed to interact with the widget . Item is enabled only if all it ' s parent elements are"""
enabled = self . _enabled if not enabled : return False if self . parent and isinstance ( self . parent , Widget ) : if self . parent . enabled == False : return False return True
def get_artists ( self , search , start = 0 , max_items = 100 ) : """Search for artists . See get _ music _ service _ information for details on the arguments"""
return self . get_music_service_information ( 'artists' , search , start , max_items )
def create_skeleton ( self ) : """Create the role ' s directory and file structure ."""
utils . string_to_file ( os . path . join ( self . output_path , "VERSION" ) , "master\n" ) for folder in c . ANSIBLE_FOLDERS : create_folder_path = os . path . join ( self . output_path , folder ) utils . mkdir_p ( create_folder_path ) mainyml_template = default_mainyml_template . replace ( "%role_name" , ...
def create_secret ( namespace , name , sources , apiserver_url = None , force = False , update = False , saltenv = 'base' ) : '''. . versionadded : : 2016.3.0 Create k8s secrets in the defined namespace from the list of files CLI Example : . . code - block : : bash salt ' * ' k8s . create _ secret namespace...
ret = { 'name' : name , 'result' : True , 'comment' : '' , 'changes' : { } } if not sources : return { 'name' : name , 'result' : False , 'comment' : 'No source available' , 'changes' : { } } apiserver_url = _guess_apiserver ( apiserver_url ) # we need namespace to create secret in it if not _get_namespaces ( apise...
def retrieve_state_ids ( self , activity , agent , registration = None , since = None ) : """Retrieve state id ' s from the LRS with the provided parameters : param activity : Activity object of desired states : type activity : : class : ` tincan . activity . Activity ` : param agent : Agent object of desired...
if not isinstance ( activity , Activity ) : activity = Activity ( activity ) if not isinstance ( agent , Agent ) : agent = Agent ( agent ) request = HTTPRequest ( method = "GET" , resource = "activities/state" ) request . query_params = { "activityId" : activity . id , "agent" : agent . to_json ( self . version...
def pong ( self , event = 'PONG' , data = '' , ** kw ) : # pragma : no cover """P0NG / PING"""
self . bot . log . debug ( '%s ping-pong (%s)' , event , data ) if self . reconn_handle is not None : self . reconn_handle . cancel ( ) self . reconn_handle = self . bot . loop . call_later ( self . timeout , self . reconnect ) if self . ping_handle is not None : self . ping_handle . cancel ( ) self . ping_hand...
def check_ratebase ( self , rate ) : """Helper function"""
split = rate [ 'name' ] . partition ( '/' ) if split [ 1 ] : ratebase = split [ 0 ] if ratebase != self . base : raise RuntimeError ( "%s: %s has different base rate:\n%s" % ( self . name , ratebase , rate ) ) elif rate [ 'name' ] == self . base : pass # Codes beginning with ' X ' are treated specia...
def _slice_vcf_chr21 ( vcf_file , out_dir ) : """Slice chr21 of qsignature SNPs to reduce computation time"""
tmp_file = os . path . join ( out_dir , "chr21_qsignature.vcf" ) if not utils . file_exists ( tmp_file ) : cmd = ( "grep chr21 {vcf_file} > {tmp_file}" ) . format ( ** locals ( ) ) out = subprocess . check_output ( cmd , shell = True ) return tmp_file
def _fetch_analysis_for_local_id ( analysis , ans_cond ) : """This function returns an analysis when the derivative IDs conditions are met . : analysis : the analysis full object which we want to obtain the rules for . : ans _ cond : the local id with the target derivative reflex rule id ."""
# Getting the first reflexed analysis from the chain first_reflexed = analysis . getOriginalReflexedAnalysis ( ) # Getting all reflexed analysis created due to this first analysis analyses_catalog = getToolByName ( analysis , CATALOG_ANALYSIS_LISTING ) derivatives_brains = analyses_catalog ( getOriginalReflexedAnalysis...
def create_namespaced_local_subject_access_review ( self , namespace , body , ** kwargs ) : """create a LocalSubjectAccessReview This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > thread = api . create _ namespaced _ local _ su...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . create_namespaced_local_subject_access_review_with_http_info ( namespace , body , ** kwargs ) else : ( data ) = self . create_namespaced_local_subject_access_review_with_http_info ( namespace , body , ** kwargs ) retu...
def type ( self ) : """The type of the functional ."""
if self . xc in self . defined_aliases : return self . defined_aliases [ self . xc ] . type xc = ( self . x , self . c ) if xc in self . defined_aliases : return self . defined_aliases [ xc ] . type # If self is not in defined _ aliases , use LibxcFunc family if self . xc is not None : return self . xc . fa...
def any ( self , values , axis = 0 ) : """compute if any item evaluates to true in each group Parameters values : array _ like , [ keys , . . . ] values to take boolean predicate over per group axis : int , optional alternative reduction axis for values Returns unique : ndarray , [ groups ] unique k...
values = np . asarray ( values ) if not values . dtype == np . bool : values = values != 0 return self . unique , self . reduce ( values , axis = axis ) > 0
def show ( self , idx ) : """Print the instruction"""
print ( self . get_name ( ) + " " + self . get_output ( idx ) , end = ' ' )
def deterministic_generate_k ( generator_order , secret_exponent , val , hash_f = hashlib . sha256 ) : """: param generator _ order : result from : method : ` pycoin . ecdsa . Generator . Generator . order ` , necessary to ensure the k value is within bound : param secret _ exponent : an integer secret _ expone...
n = generator_order bln = bit_length ( n ) order_size = ( bln + 7 ) // 8 hash_size = hash_f ( ) . digest_size v = b'\x01' * hash_size k = b'\x00' * hash_size priv = intstream . to_bytes ( secret_exponent , length = order_size ) shift = 8 * hash_size - bln if shift > 0 : val >>= shift if val > n : val -= n h1 = ...
def reverse_subarray ( arr , until ) : """Function to reverse a portion of a list up to a particular position . > > > reverse _ subarray ( [ 1 , 2 , 3 , 4 , 5 , 6 ] , 4) [4 , 3 , 2 , 1 , 5 , 6] > > > reverse _ subarray ( [ 4 , 5 , 6 , 7 ] , 2) [5 , 4 , 6 , 7] > > > reverse _ subarray ( [ 9 , 8 , 7 , 6 , 5...
return arr [ : until ] [ : : - 1 ] + arr [ until : ]
def unwrap_stream ( stream_name ) : """Temporarily unwraps a given stream ( stdin , stdout , or stderr ) to undo the effects of wrap _ stdio _ in _ codecs ( ) ."""
wrapped_stream = None try : wrapped_stream = getattr ( sys , stream_name ) if hasattr ( wrapped_stream , '_original_stream' ) : setattr ( sys , stream_name , wrapped_stream . _original_stream ) yield finally : if wrapped_stream : setattr ( sys , stream_name , wrapped_stream )
def puppeteer ( ctx , port , auto_restart , args ) : """Run puppeteer fetcher if puppeteer is installed ."""
import subprocess g = ctx . obj _quit = [ ] puppeteer_fetcher = os . path . join ( os . path . dirname ( pyspider . __file__ ) , 'fetcher/puppeteer_fetcher.js' ) cmd = [ 'node' , puppeteer_fetcher , str ( port ) ] try : _puppeteer = subprocess . Popen ( cmd ) except OSError : logging . warning ( 'puppeteer not ...
def _parse_numbers ( text ) : '''Convert a string to a number , allowing for a K | M | G | T postfix , 32.8K . Returns a decimal number if the string is a real number , or the string unchanged otherwise .'''
if text . isdigit ( ) : return decimal . Decimal ( text ) try : postPrefixes = { 'K' : '10E3' , 'M' : '10E6' , 'G' : '10E9' , 'T' : '10E12' , 'P' : '10E15' , 'E' : '10E18' , 'Z' : '10E21' , 'Y' : '10E24' } if text [ - 1 ] in postPrefixes . keys ( ) : v = decimal . Decimal ( text [ : - 1 ] ) ...
def set_buffer_options ( self , options , bufnr = None ) : """Set buffer - local options for a buffer , defaulting to current . Args : options ( dict ) : Options to set , with keys being Vim option names . For Boolean options , use a : class : ` bool ` value as expected , e . g . ` ` { ' buflisted ' : Fal...
buf = self . _vim . buffers [ bufnr ] if bufnr else self . _vim . current . buffer # Special case handling for filetype , see doc on ` ` set _ filetype ` ` filetype = options . pop ( 'filetype' , None ) if filetype : self . set_filetype ( filetype ) for opt , value in options . items ( ) : buf . options [ opt ]...
def _getH2singleTrait ( self , K , verbose = None ) : """Internal function for parameter initialization estimate variance components and fixed effect using a linear mixed model with an intercept and 2 random effects ( one is noise ) Args : K : covariance matrix of the non - noise random effect term"""
verbose = dlimix . getVerbose ( verbose ) # Fit single trait model varg = sp . zeros ( self . P ) varn = sp . zeros ( self . P ) fixed = sp . zeros ( ( 1 , self . P ) ) for p in range ( self . P ) : y = self . Y [ : , p : p + 1 ] # check if some sull value I = sp . isnan ( y [ : , 0 ] ) if I . sum ( ) >...
def filter_out_empty ( tuples : list ) -> list : """Function to exclude empty tuples from a list of various tuples . Args : tuples ( list ) : A list of tuples of any length . Returns : list : A version of the input list minus any empty tuple entries . Example : > > > filter _ out _ empty ( [ ( ) , ( ) ,...
return [ t for t in tuples if t ]