signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def predict ( self , data , num_iteration = - 1 , raw_score = False , pred_leaf = False , pred_contrib = False , data_has_header = False , is_reshape = True ) : """Predict logic . Parameters data : string , numpy array , pandas DataFrame , H2O DataTable ' s Frame or scipy . sparse Data source for prediction ....
if isinstance ( data , Dataset ) : raise TypeError ( "Cannot use Dataset instance for prediction, please use raw data instead" ) data = _data_from_pandas ( data , None , None , self . pandas_categorical ) [ 0 ] predict_type = C_API_PREDICT_NORMAL if raw_score : predict_type = C_API_PREDICT_RAW_SCORE if pred_lea...
def add ( self , name , value , bitmask = DEFMASK ) : """Add an enum member Args : name : Name of the member value : value of the member bitmask : bitmask . Only use if enum is a bitfield ."""
_add_enum_member ( self . _eid , name , value , bitmask )
def get_request_token ( self , method = 'GET' , decoder = parse_utf8_qsl , key_token = 'oauth_token' , key_token_secret = 'oauth_token_secret' , ** kwargs ) : '''Return a request token pair . : param method : A string representation of the HTTP method to be used , defaults to ` GET ` . : type method : str :...
r = self . get_raw_request_token ( method = method , ** kwargs ) request_token , request_token_secret = process_token_request ( r , decoder , key_token , key_token_secret ) return request_token , request_token_secret
def get ( self , request , * args , ** kwargs ) : """Django view get function . Add items of extra _ context , crumbs and grid to context . Args : request ( ) : Django ' s request object . * args ( ) : request args . * * kwargs ( ) : request kwargs . Returns : response : render to response with contex...
context = self . get_context_data ( ** kwargs ) context . update ( self . extra_context ) context [ 'crumbs' ] = self . get_crumbs ( ) context [ 'title' ] = self . title context [ 'suit' ] = 'suit' in settings . INSTALLED_APPS if context . get ( 'dashboard_grid' , None ) is None and self . grid : context [ 'dashboa...
def heightmap_new ( w : int , h : int , order : str = "C" ) -> np . ndarray : """Return a new numpy . ndarray formatted for use with heightmap functions . ` w ` and ` h ` are the width and height of the array . ` order ` is given to the new NumPy array , it can be ' C ' or ' F ' . You can pass a NumPy array t...
if order == "C" : return np . zeros ( ( h , w ) , np . float32 , order = "C" ) elif order == "F" : return np . zeros ( ( w , h ) , np . float32 , order = "F" ) else : raise ValueError ( "Invalid order parameter, should be 'C' or 'F'." )
def list_media_services_rg ( access_token , subscription_id , rgname ) : '''List the media services in a resource group . Args : access _ token ( str ) : A valid Azure authentication token . subscription _ id ( str ) : Azure subscription id . rgname ( str ) : Azure resource group name . Returns : HTTP r...
endpoint = '' . join ( [ get_rm_endpoint ( ) , '/subscriptions/' , subscription_id , '/resourceGroups/' , rgname , '/providers/microsoft.media/mediaservices?api-version=' , MEDIA_API ] ) return do_get ( endpoint , access_token )
def _create_equivalence_transform ( equiv ) : """Compute an equivalence transformation that transforms this compound to another compound ' s coordinate system . Parameters equiv : np . ndarray , shape = ( n , 3 ) , dtype = float Array of equivalent points . Returns T : CoordinateTransform Transform th...
from mbuild . compound import Compound self_points = np . array ( [ ] ) self_points . shape = ( 0 , 3 ) other_points = np . array ( [ ] ) other_points . shape = ( 0 , 3 ) for pair in equiv : if not isinstance ( pair , tuple ) or len ( pair ) != 2 : raise ValueError ( 'Equivalence pair not a 2-tuple' ) i...
def set_hs_color ( self , hue : float , saturation : float ) : """Set a fixed color and also turn off effects in order to see the color . : param hue : Hue component ( range 0-1) : param saturation : Saturation component ( range 0-1 ) . Yields white for values near 0 , other values are interpreted as 100 % sa...
self . turn_off_effect ( ) if saturation < 0.1 : # Special case ( white ) hm_color = 200 else : hm_color = int ( round ( max ( min ( hue , 1 ) , 0 ) * 199 ) ) self . setValue ( key = "COLOR" , channel = self . _color_channel , value = hm_color )
def unload_plugin ( name , category = None ) : """remove single plugin Parameters name : str plugin name category : str plugin category Examples > > > from pprint import pprint > > > pprint ( view _ plugins ( ) ) { ' decoders ' : { } , ' encoders ' : { } , ' parsers ' : { } } > > > class Decoder...
if category is not None : _all_plugins [ category ] . pop ( name ) else : for cat in _all_plugins : if name in _all_plugins [ cat ] : _all_plugins [ cat ] . pop ( name )
def add_date_facet ( self , * args , ** kwargs ) : """Add a date factory facet"""
self . facets . append ( DateHistogramFacet ( * args , ** kwargs ) )
def _outer_init_full_values ( self ) : """If full _ values has indices in values _ indices , we might want to initialize the full _ values differently , so that subsetting is possible . Here you can initialize the full _ values for the values needed . Keep in mind , that if a key does not exist in full _ valu...
retd = dict ( dL_dKmm = np . zeros ( ( self . Z . shape [ 0 ] , self . Z . shape [ 0 ] ) ) ) if self . has_uncertain_inputs ( ) : retd . update ( dict ( dL_dpsi0 = np . zeros ( self . X . shape [ 0 ] ) , dL_dpsi1 = np . zeros ( ( self . X . shape [ 0 ] , self . Z . shape [ 0 ] ) ) , dL_dpsi2 = np . zeros ( ( self ....
def remove_wirevector ( self , wirevector ) : """Remove a wirevector object to the block ."""
self . wirevector_set . remove ( wirevector ) del self . wirevector_by_name [ wirevector . name ]
def list_storage_services ( conn = None , call = None ) : '''List VMs on this Azure account , with full information'''
if call != 'function' : raise SaltCloudSystemExit ( ( 'The list_storage_services function must be called ' 'with -f or --function.' ) ) if not conn : conn = get_conn ( ) ret = { } accounts = conn . list_storage_accounts ( ) for service in accounts . storage_services : ret [ service . service_name ] = { 'cap...
def fake_run ( self ) : '''Doesn ' t actually run cd - hit . Instead , puts each input sequence into its own cluster . So it ' s as if cdhit was run , but didn ' t cluster anything'''
clusters = { } used_names = set ( ) seq_reader = pyfastaq . sequences . file_reader ( self . infile ) for seq in seq_reader : if seq . id in used_names : raise Error ( 'Sequence name "' + seq . id + '" not unique. Cannot continue' ) clusters [ str ( len ( clusters ) + self . min_cluster_number ) ] = { s...
def get ( self , request , bot_id , format = None ) : """Get list of environment variables serializer : EnvironmentVarSerializer responseMessages : - code : 401 message : Not authenticated"""
return super ( EnvironmentVarList , self ) . get ( request , bot_id , format )
def _analyst_data ( self , ws ) : """Returns a dict that represent the analyst assigned to the worksheet . Keys : username , fullname , email"""
username = ws . getAnalyst ( ) return { 'username' : username , 'fullname' : to_utf8 ( self . user_fullname ( username ) ) , 'email' : to_utf8 ( self . user_email ( username ) ) }
def d2logpdf_dlink2_dvar ( self , link_f , y , Y_metadata = None ) : """: param link _ f : latent variables link ( f ) : type link _ f : Nx1 array : param y : data : type y : Nx1 array : param Y _ metadata : Y _ metadata not used in gaussian : returns : derivative of log likelihood evaluated at points lin...
c = np . zeros_like ( y ) if Y_metadata is not None and 'censored' in Y_metadata . keys ( ) : c = Y_metadata [ 'censored' ] val = np . log ( y ) - link_f val_scaled = val / np . sqrt ( self . variance ) val_scaled2 = val / self . variance a = ( 1 - stats . norm . cdf ( val_scaled ) ) uncensored = ( 1 - c ) * ( 1. /...
def to_gremlin ( self ) : """Return a unicode object with the Gremlin representation of this expression ."""
self . validate ( ) immediate_operator_format = u'({left} {operator} {right})' dotted_operator_format = u'{left}.{operator}({right})' intersects_operator_format = u'(!{left}.{operator}({right}).empty)' translation_table = { u'=' : ( u'==' , immediate_operator_format ) , u'!=' : ( u'!=' , immediate_operator_format ) , u...
def apply_handler_to_all_logs ( handler : logging . Handler , remove_existing : bool = False ) -> None : """Applies a handler to all logs , optionally removing existing handlers . Should ONLY be called from the ` ` if _ _ name _ _ = = ' main ' ` ` script ; see https : / / docs . python . org / 3.4 / howto / log...
# noinspection PyUnresolvedReferences for name , obj in logging . Logger . manager . loggerDict . items ( ) : if remove_existing : obj . handlers = [ ] # http : / / stackoverflow . com / questions / 7484454 obj . addHandler ( handler )
def list_availability_zones ( self , retrieve_all = True , ** _params ) : """Fetches a list of all availability zones ."""
return self . list ( 'availability_zones' , self . availability_zones_path , retrieve_all , ** _params )
def read_file_to_buffer ( filename ) : """Reads a file to string buffer : param filename : : return :"""
f = open ( filename , "r" ) buf = BytesIO ( f . read ( ) ) f . close ( ) return buf
def add_report ( self , report , ignore_errors = False ) : """Add all anchors from a report ."""
if not isinstance ( report , SignedListReport ) : if ignore_errors : return raise ArgumentError ( "You can only add SignedListReports to a UTCAssigner" , report = report ) for reading in report . visible_readings : self . add_reading ( reading ) self . add_point ( report . report_id , report . sent_...
def frombinary ( path , shape = None , dtype = None , ext = 'bin' , start = None , stop = None , recursive = False , nplanes = None , npartitions = None , labels = None , conf = 'conf.json' , order = 'C' , engine = None , credentials = None ) : """Load images from flat binary files . Assumes one image per file , ...
import json from thunder . readers import get_file_reader , FileNotFoundError try : reader = get_file_reader ( path ) ( credentials = credentials ) buf = reader . read ( path , filename = conf ) . decode ( 'utf-8' ) params = json . loads ( buf ) except FileNotFoundError : params = { } if 'dtype' in para...
def _buttonbox ( msg , title , choices , root = None , timeout = None ) : """Display a msg , a title , and a set of buttons . The buttons are defined by the members of the choices list . Return the text of the button that the user selected . @ arg msg : the msg to be displayed . @ arg title : the window tit...
global boxRoot , __replyButtonText , __widgetTexts , buttonsFrame # Initialize _ _ replyButtonText to the first choice . # This is what will be used if the window is closed by the close button . __replyButtonText = choices [ 0 ] if root : root . withdraw ( ) boxRoot = tk . Toplevel ( master = root ) boxRoot...
def app_to_context ( self , context ) : """Return a context encoded tag ."""
if self . tagClass != Tag . applicationTagClass : raise ValueError ( "application tag required" ) # application tagged boolean now has data if ( self . tagNumber == Tag . booleanAppTag ) : return ContextTag ( context , chr ( self . tagLVT ) ) else : return ContextTag ( context , self . tagData )
def write_fmt ( fp , fmt , * args ) : """Writes data to ` ` fp ` ` according to ` ` fmt ` ` ."""
fmt = str ( ">" + fmt ) fmt_size = struct . calcsize ( fmt ) written = write_bytes ( fp , struct . pack ( fmt , * args ) ) assert written == fmt_size , 'written=%d, expected=%d' % ( written , fmt_size ) return written
def MarkDone ( self , responses ) : """Mark a client as done ."""
client_id = responses . request . client_id self . AddResultsToCollection ( responses , client_id ) self . MarkClientDone ( client_id )
def top ( self ) : """Top coordinate ."""
if self . _has_real ( ) : return self . _data . real_top return self . _data . top
def detectMidpCapable ( self ) : """Return detection of a MIDP mobile Java - capable device Detects if the current device supports MIDP , a mobile Java technology ."""
return UAgentInfo . deviceMidp in self . __userAgent or UAgentInfo . deviceMidp in self . __httpAccept
def _build_command ( self , cmds , sync = False ) : """Build full EOS ' s openstack CLI command . Helper method to add commands to enter and exit from openstack CLI modes . : param cmds : The openstack CLI commands that need to be executed in the openstack config mode . : param sync : This flags indicates...
region_cmd = 'region %s' % self . region if sync : region_cmd = self . cli_commands [ const . CMD_REGION_SYNC ] full_command = [ 'enable' , 'configure' , 'cvx' , 'service openstack' , region_cmd , ] full_command . extend ( cmds ) return full_command
def encode ( input , encoding = UTF8 , errors = 'strict' ) : """Encode a single string . : param input : An Unicode string . : param encoding : An : class : ` Encoding ` object or a label string . : param errors : Type of error handling . See : func : ` codecs . register ` . : raises : : exc : ` ~ exception...
return _get_encoding ( encoding ) . codec_info . encode ( input , errors ) [ 0 ]
def set_expected_update_frequency ( self , update_frequency ) : # type : ( str ) - > None """Set expected update frequency Args : update _ frequency ( str ) : Update frequency Returns : None"""
try : int ( update_frequency ) except ValueError : update_frequency = Dataset . transform_update_frequency ( update_frequency ) if not update_frequency : raise HDXError ( 'Invalid update frequency supplied!' ) self . data [ 'data_update_frequency' ] = update_frequency
def notify_widget ( self , widget , message = None , clear_in = CLEAR_NOTIF_BAR_MESSAGE_IN ) : """opens notification popup . : param widget : instance of Widget , widget to display : param message : str , message to remove from list of notifications : param clear _ in : int , time seconds when notification sh...
@ log_traceback def clear_notification ( * args , ** kwargs ) : # the point here is the log _ traceback self . remove_widget ( widget , message = message ) if not widget : return logger . debug ( "display notification widget %s" , widget ) with self . notifications_lock : self . widget_message_dict [ widget...
def available ( self ) : """Returns a set of the available versions . : returns : A set of integers giving the available versions ."""
# Short - circuit if not self . _schema : return set ( ) # Build up the set of available versions avail = set ( self . _schema . __vers_downgraders__ . keys ( ) ) avail . add ( self . _schema . __version__ ) return avail
def spawn_containers ( addrs , env_cls = Environment , env_params = None , mgr_cls = EnvManager , * args , ** kwargs ) : """Spawn environments in a multiprocessing : class : ` multiprocessing . Pool ` . Arguments and keyword arguments are passed down to the created environments at initialization time if * env _...
pool = multiprocessing . Pool ( len ( addrs ) ) kwargs [ 'env_cls' ] = env_cls kwargs [ 'mgr_cls' ] = mgr_cls r = [ ] for i , addr in enumerate ( addrs ) : if env_params is not None : k = env_params [ i ] k [ 'env_cls' ] = env_cls k [ 'mgr_cls' ] = mgr_cls # Copy kwargs so that we can ap...
def make_header ( decoded_seq , maxlinelen = None , header_name = None , continuation_ws = ' ' ) : """Create a Header from a sequence of pairs as returned by decode _ header ( ) decode _ header ( ) takes a header value string and returns a sequence of pairs of the format ( decoded _ string , charset ) where cha...
h = Header ( maxlinelen = maxlinelen , header_name = header_name , continuation_ws = continuation_ws ) for s , charset in decoded_seq : # None means us - ascii but we can simply pass it on to h . append ( ) if charset is not None and not isinstance ( charset , Charset ) : charset = Charset ( charset ) h...
def get_song ( self , id_ ) : """Data for a specific song ."""
endpoint = "songs/{id}" . format ( id = id_ ) return self . _make_request ( endpoint )
def train_token ( self , word , count ) : """Trains a particular token ( increases the weight / count of it ) : param word : the token we ' re going to train : type word : str : param count : the number of occurances in the sample : type count : int"""
if word not in self . tokens : self . tokens [ word ] = 0 self . tokens [ word ] += count self . tally += count
def get_argument_parser ( ) : """Function to obtain the argument parser . Parameters Returns ` argparse . ArgumentParser ` A fully configured ` argparse . ArgumentParser ` object . Notes This function can also be used by the ` sphinx - argparse ` extension for sphinx to generate documentation for this...
desc = 'Convert Entrez IDs to gene symbols.' parser = cli . get_argument_parser ( desc = desc ) file_mv = cli . file_mv g = parser . add_argument_group ( 'Input and output files' ) g . add_argument ( '-e' , '--expression-file' , required = True , type = cli . str_type , metavar = file_mv , help = 'The expression file.'...
def run_experiment ( self ) : """Sign up , run the ` ` participate ` ` method , then sign off and close the driver ."""
try : self . sign_up ( ) self . participate ( ) if self . sign_off ( ) : self . complete_experiment ( "worker_complete" ) else : self . complete_experiment ( "worker_failed" ) finally : self . driver . quit ( )
def parse ( cls , parser , text , pos ) : """Using our own parse to enable the flag below ."""
try : parser . _parsing_parenthesized_simple_values_expression = True remaining_text , recognized_tokens = parser . parse ( text , cls . grammar ) return remaining_text , recognized_tokens except SyntaxError as e : return text , e finally : parser . _parsing_parenthesized_simple_values_expression = ...
def get_interpreter_path ( version = None ) : """Return the executable of a specified or current version ."""
if version and version != str ( sys . version_info [ 0 ] ) : return settings . PYTHON_INTERPRETER + version else : return sys . executable
def _get_features ( self , eopatch = None ) : """A generator of parsed features . : param eopatch : A given EOPatch : type eopatch : EOPatch or None : return : One by one feature : rtype : tuple ( FeatureType , str ) or tuple ( FeatureType , str , str )"""
for feature_type , feature_dict in self . feature_collection . items ( ) : if feature_type is None and self . default_feature_type is not None : feature_type = self . default_feature_type if feature_type is None : for feature_name , new_feature_name in feature_dict . items ( ) : if e...
def is_package_installed ( distribution , pkg ) : """checks if a particular package is installed"""
if ( 'centos' in distribution or 'el' in distribution or 'redhat' in distribution ) : return ( is_rpm_package_installed ( pkg ) ) if ( 'ubuntu' in distribution or 'debian' in distribution ) : return ( is_deb_package_installed ( pkg ) )
def export_maxloss_ruptures ( ekey , dstore ) : """: param ekey : export key , i . e . a pair ( datastore key , fmt ) : param dstore : datastore object"""
oq = dstore [ 'oqparam' ] mesh = get_mesh ( dstore [ 'sitecol' ] ) rlzs_by_gsim = dstore [ 'csm_info' ] . get_rlzs_by_gsim_grp ( ) num_ses = oq . ses_per_logic_tree_path fnames = [ ] for loss_type in oq . loss_dt ( ) . names : ebr = getters . get_maxloss_rupture ( dstore , loss_type ) root = hazard_writers . ru...
def is_nsphere ( points ) : """Check if a list of points is an nsphere . Parameters points : ( n , dimension ) float Points in space Returns check : bool True if input points are on an nsphere"""
center , radius , error = fit_nsphere ( points ) check = error < tol . merge return check
def list_ngrams ( token_list , n = 1 , join = ' ' ) : """Return a list of n - tuples , one for each possible sequence of n items in the token _ list Arguments : join ( bool or str ) : if str , then join ngrom tuples on it before returning True is equivalent to join = ' ' default = True See : http : / / st...
join = ' ' if join is True else join if isinstance ( join , str ) : return [ join . join ( ng ) for ng in list_ngrams ( token_list , n = n , join = False ) ] return list ( zip ( * [ token_list [ i : ] for i in range ( n ) ] ) )
def add_hlinkClick ( self , rId ) : """Add an < a : hlinkClick > child element with r : id attribute set to * rId * ."""
hlinkClick = self . get_or_add_hlinkClick ( ) hlinkClick . rId = rId return hlinkClick
def getSpaceUse ( self ) : """Get disk space usage . @ return : Dictionary of filesystem space utilization stats for filesystems ."""
stats = { } try : out = subprocess . Popen ( [ dfCmd , "-Pk" ] , stdout = subprocess . PIPE ) . communicate ( ) [ 0 ] except : raise Exception ( 'Execution of command %s failed.' % dfCmd ) lines = out . splitlines ( ) if len ( lines ) > 1 : for line in lines [ 1 : ] : fsstats = { } cols = li...
async def add_relation ( self , local_relation , remote_relation ) : """Add a relation to another application . : param str local _ relation : Name of relation on this application : param str remote _ relation : Name of relation on the other application in the form ' < application > [ : < relation _ name > ] ...
if ':' not in local_relation : local_relation = '{}:{}' . format ( self . name , local_relation ) return await self . model . add_relation ( local_relation , remote_relation )
def query_mongo_sort_decend ( database_name , collection_name , query = { } , skip = 0 , limit = getattr ( settings , 'MONGO_LIMIT' , 200 ) , return_keys = ( ) , sortkey = None ) : """return a response _ dict with a list of search results in decending order based on a sort key"""
l = [ ] response_dict = { } try : mongodb_client_url = getattr ( settings , 'MONGODB_CLIENT' , 'mongodb://localhost:27017/' ) mc = MongoClient ( mongodb_client_url , document_class = OrderedDict ) db = mc [ str ( database_name ) ] collection = db [ str ( collection_name ) ] if return_keys : ...
def visibleCount ( self ) : """Returns the number of visible items in this list . : return < int >"""
return sum ( int ( not self . item ( i ) . isHidden ( ) ) for i in range ( self . count ( ) ) )
def remove_library_from_file_system ( self , library_path , library_name ) : """Remove library from hard disk ."""
library_file_system_path = self . get_os_path_to_library ( library_path , library_name ) [ 0 ] shutil . rmtree ( library_file_system_path ) self . refresh_libraries ( )
def _uncheck_descendant ( self , item ) : """Uncheck the boxes of item ' s descendant ."""
children = self . get_children ( item ) for iid in children : self . change_state ( iid , "unchecked" ) self . _uncheck_descendant ( iid )
def create_database ( self , database ) : """Create a database on the InfluxDB server . : param database : the name of the database to create : type database : string : rtype : boolean"""
url = "db" data = { 'name' : database } self . request ( url = url , method = 'POST' , data = data , expected_response_code = 201 ) return True
def _catch_exceptions ( self , exctype , value , tb ) : """Catches all exceptions and logs them ."""
# Now we log it . self . error ( 'Uncaught exception' , exc_info = ( exctype , value , tb ) ) # First , we print to stdout with some colouring . print_exception_formatted ( exctype , value , tb )
def open ( bucket_id , key_id , mode , buffer_size = DEFAULT_BUFFER_SIZE , min_part_size = DEFAULT_MIN_PART_SIZE , session = None , resource_kwargs = None , multipart_upload_kwargs = None , ) : """Open an S3 object for reading or writing . Parameters bucket _ id : str The name of the bucket this object reside...
logger . debug ( '%r' , locals ( ) ) if mode not in MODES : raise NotImplementedError ( 'bad mode: %r expected one of %r' % ( mode , MODES ) ) if resource_kwargs is None : resource_kwargs = { } if multipart_upload_kwargs is None : multipart_upload_kwargs = { } if mode == READ_BINARY : fileobj = Seekable...
def is_valid ( self , instance ) : """Return True if no errors are raised when validating instance . instance can be a dict ( ie , form . cleaned _ data ) , a form , or a model instance . If instance is a form , full _ clean ( ) will be called ."""
errors = self . errors ( instance ) if isinstance ( errors , list ) : return not any ( errors ) return not bool ( errors )
def distcheck ( appname = '' , version = '' , subdir = '' ) : '''checks if the sources compile ( tarball from ' dist ' )'''
import tempfile , tarfile if not appname : appname = Utils . g_module . APPNAME if not version : version = Utils . g_module . VERSION waf = os . path . abspath ( sys . argv [ 0 ] ) tarball = dist ( appname , version ) path = appname + '-' + version if os . path . exists ( path ) : shutil . rmtree ( path ) t...
def model_results ( self ) -> str : """Reads the model . results file"""
with open ( os . path . join ( self . directory , "model.results" ) ) as f : return f . read ( )
def get_environment_vars ( filename ) : """Return a dict of environment variables required to run a service under faketime ."""
if sys . platform == "linux" or sys . platform == "linux2" : return { 'LD_PRELOAD' : path . join ( LIBFAKETIME_DIR , "libfaketime.so.1" ) , 'FAKETIME_SKIP_CMDS' : 'nodejs' , # node doesn ' t seem to work in the current version . 'FAKETIME_TIMESTAMP_FILE' : filename , } elif sys . platform == "darwin" : retu...
def list_priority_class ( self , ** kwargs ) : """list or watch objects of kind PriorityClass This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > thread = api . list _ priority _ class ( async _ req = True ) > > > result = thr...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . list_priority_class_with_http_info ( ** kwargs ) else : ( data ) = self . list_priority_class_with_http_info ( ** kwargs ) return data
def copy_config_input_with_inactive ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) copy_config = ET . Element ( "copy_config" ) config = copy_config input = ET . SubElement ( copy_config , "input" ) with_inactive = ET . SubElement ( input , "with-inactive" , xmlns = "http://tail-f.com/ns/netconf/inactive/1.0" ) callback = kwargs . pop ( 'callback' , self . _callback...
def merge ( self , schema ) : """Merge the contents from the schema . Only objects not already contained in this schema ' s collections are merged . This is to provide for bidirectional import which produce cyclic includes . @ returns : self @ rtype : L { Schema }"""
for item in schema . attributes . items ( ) : if item [ 0 ] in self . attributes : continue self . all . append ( item [ 1 ] ) self . attributes [ item [ 0 ] ] = item [ 1 ] for item in schema . elements . items ( ) : if item [ 0 ] in self . elements : continue self . all . append ( i...
def quast_general_stats_table ( self ) : """Take the parsed stats from the QUAST report and add some to the General Statistics table at the top of the report"""
headers = OrderedDict ( ) headers [ 'N50' ] = { 'title' : 'N50 ({})' . format ( self . contig_length_suffix ) , 'description' : 'N50 is the contig length such that using longer or equal length contigs produces half (50%) of the bases of the assembly (kilo base pairs)' , 'min' : 0 , 'suffix' : self . contig_length_suffi...
def add ( self , data_source , module , package = None ) : """Add data _ source to model . Tries to import module , then looks for data source class definition . : param data _ source : Name of data source to add . : type data _ source : str : param module : Module in which data source resides . Can be abso...
super ( Data , self ) . add ( data_source , module , package ) # only update layer info if it is missing ! if data_source not in self . layer : # copy data source parameters to : attr : ` Layer . layer ` self . layer [ data_source ] = { 'module' : module , 'package' : package } # add a place holder for the data sou...
def main ( self ) : """Scheduler steps : - run ready until exhaustion - if there ' s something scheduled - run overdue scheduled immediately - or if there ' s nothing registered , sleep until next scheduled and then go back to ready - if there ' s nothing registered and nothing scheduled , we ' ve dea...
while True : while self . ready : task , a = self . ready . popleft ( ) self . run_task ( task , * a ) if self . scheduled : timeout = self . scheduled . timeout ( ) # run overdue scheduled immediately if timeout < 0 : task , a = self . scheduled . pop ( ) ...
def headerData ( self , section , orientation , role ) : """Get the text to put in the header of the levels of the indexes . By default it returns ' Index i ' , where i is the section in the index"""
if role == Qt . TextAlignmentRole : if orientation == Qt . Horizontal : return Qt . AlignCenter | Qt . AlignBottom else : return Qt . AlignRight | Qt . AlignVCenter if role != Qt . DisplayRole and role != Qt . ToolTipRole : return None if self . model . header_shape [ 0 ] <= 1 and orientatio...
def needs_invalidation ( self , requirement , cache_file ) : """Check whether a cached binary distribution needs to be invalidated . : param requirement : A : class : ` . Requirement ` object . : param cache _ file : The pathname of a cached binary distribution ( a string ) . : returns : : data : ` True ` if ...
if self . config . trust_mod_times : return requirement . last_modified > os . path . getmtime ( cache_file ) else : checksum = self . recall_checksum ( cache_file ) return checksum and checksum != requirement . checksum
def frac_vol_floc_initial ( ConcAluminum , ConcClay , coag , material ) : """Return the volume fraction of flocs initially present , accounting for both suspended particles and coagulant precipitates . : param ConcAluminum : Concentration of aluminum in solution : type ConcAluminum : float : param ConcClay : ...
return ( ( conc_precipitate ( ConcAluminum , coag ) . magnitude / coag . PrecipDensity ) + ( ConcClay / material . Density ) )
def copy ( self ) : """Make a copy of this runnable . @ return : Copy of this runnable . @ rtype : lems . sim . runnable . Runnable"""
if self . debug : print ( "Coping....." + self . id ) r = Runnable ( self . id , self . component , self . parent ) copies = dict ( ) # Copy simulation time parameters r . time_step = self . time_step r . time_completed = self . time_completed r . time_total = self . time_total # Plasticity and state stack ( ? ) r ...
def retry ( f , exc_classes = DEFAULT_EXC_CLASSES , logger = None , retry_log_level = logging . INFO , retry_log_message = "Connection broken in '{f}' (error: '{e}'); " "retrying with new connection." , max_failures = None , interval = 0 , max_failure_log_level = logging . ERROR , max_failure_log_message = "Max retries...
exc_classes = tuple ( exc_classes ) @ wraps ( f ) def deco ( * args , ** kwargs ) : failures = 0 while True : try : return f ( * args , ** kwargs ) except exc_classes as e : if logger is not None : logger . log ( retry_log_level , retry_log_message . forma...
def rapl_read ( ) : """Read power stats and return dictionary"""
basenames = glob . glob ( '/sys/class/powercap/intel-rapl:*/' ) basenames = sorted ( set ( { x for x in basenames } ) ) pjoin = os . path . join ret = list ( ) for path in basenames : name = None try : name = cat ( pjoin ( path , 'name' ) , fallback = None , binary = False ) except ( IOError , OSErr...
def fromElement ( cls , elem ) : """Read properties from a MetaDataVersion element : param lxml . etree . _ Element elem : Source etree Element"""
self = cls ( ) self . oid = elem . get ( "OID" ) self . name = elem . get ( "Name" ) return self
def add_url ( self ) : """Add non - empty URLs to the queue ."""
if self . url : self . url_data . add_url ( self . url , line = self . parser . CurrentLineNumber , column = self . parser . CurrentColumnNumber ) self . url = u""
def create_parser ( ) : """construct the program options"""
parser = argparse . ArgumentParser ( prog = constants . PROGRAM_NAME , description = constants . PROGRAM_DESCRIPTION ) parser . add_argument ( "-cd" , "--%s" % constants . LABEL_CONFIG_DIR , help = "the directory for configuration file lookup" , ) parser . add_argument ( "-c" , "--%s" % constants . LABEL_CONFIG , help ...
def get_unique_object_contents ( self , location : str ) -> Tuple [ bool , str , Union [ str , Dict [ str , str ] ] ] : """Utility method to find a unique singlefile or multifile object . This method throws * ObjectNotFoundOnFileSystemError if no file is found * ObjectPresentMultipleTimesOnFileSystemError if ...
# First check what is present on the filesystem according to the filemapping simpleobjects_found = self . find_simpleobject_file_occurrences ( location ) complexobject_attributes_found = self . find_multifile_object_children ( location , no_errors = True ) # Then handle the various cases if len ( simpleobjects_found ) ...
def viable_source_types_for_generator ( generator ) : """Caches the result of ' viable _ source _ types _ for _ generator ' ."""
assert isinstance ( generator , Generator ) if generator not in __viable_source_types_cache : __vstg_cached_generators . append ( generator ) __viable_source_types_cache [ generator ] = viable_source_types_for_generator_real ( generator ) return __viable_source_types_cache [ generator ]
def assertDateTimesPast ( self , sequence , strict = True , msg = None ) : '''Fail if any elements in ` ` sequence ` ` are not in the past . If the max element is a datetime , " past " is defined as anything prior to ` ` datetime . now ( ) ` ` ; if the max element is a date , " past " is defined as anything p...
if not isinstance ( sequence , collections . Iterable ) : raise TypeError ( 'First argument is not iterable' ) # Cannot compare datetime to date , so if dates are provided use # date . today ( ) , if datetimes are provided use datetime . today ( ) if isinstance ( max ( sequence ) , datetime ) : target = datetim...
def inspect ( object ) : """A better dir ( ) showing attributes and values"""
for k in dir ( object ) : try : details = getattr ( object , k ) except Exception as e : details = e try : details = str ( details ) except Exception as e : details = e print ( "{}: {}" . format ( k , details ) , file = sys . stderr )
def warn ( self , key ) : """Returns True if the warning setting is enabled ."""
return ( not self . quiet and not self . warn_none and ( self . warn_all or getattr ( self , "warn_%s" % key ) ) )
def visit_arguments ( self , node : AST , dfltChaining : bool = True ) -> str : """Return ` node ` s representation as argument list ."""
args = node . args dflts = node . defaults vararg = node . vararg kwargs = node . kwonlyargs kwdflts = node . kw_defaults kwarg = node . kwarg self . compact = True n_args_without_dflt = len ( args ) - len ( dflts ) args_src = ( arg . arg for arg in args [ : n_args_without_dflt ] ) dflts_src = ( f"{arg.arg}={self.visit...
def list_only ( ) : """List - Mode : Retrieve and display data then exit ."""
( cred , providers ) = config_read ( ) conn_objs = cld . get_conns ( cred , providers ) nodes = cld . get_data ( conn_objs , providers ) node_dict = make_node_dict ( nodes , "name" ) table . indx_table ( node_dict )
def get_all_email_receivers_of_recurring ( self , recurring_id ) : """Get all email receivers of recurring This will iterate over all pages until it gets all elements . So if the rate limit exceeded it will throw an Exception and you will get nothing : param recurring _ id : the recurring id : return : list...
return self . _iterate_through_pages ( get_function = self . get_email_receivers_of_recurring_per_page , resource = RECURRING_EMAIL_RECEIVERS , ** { 'recurring_id' : recurring_id } )
def extract_bzip2 ( archive , compression , cmd , verbosity , interactive , outdir ) : """Extract a BZIP2 archive with the bz2 Python module ."""
targetname = util . get_single_outfile ( outdir , archive ) try : with bz2 . BZ2File ( archive ) as bz2file : with open ( targetname , 'wb' ) as targetfile : data = bz2file . read ( READ_SIZE_BYTES ) while data : targetfile . write ( data ) data = bz2f...
def pop ( self ) : """Pops a task off the front of the queue & runs it . Typically , you ' ll favor using a ` ` Worker ` ` to handle processing the queue ( to constantly consume ) . However , if you need to custom - process the queue in - order , this method is useful . Ex : : # Tasks were previously adde...
data = self . backend . pop ( self . queue_name ) if data : task = self . task_class . deserialize ( data ) return self . execute ( task )
def cancelMarketData ( self , contracts = None ) : """Cancel streaming market data for contract https : / / www . interactivebrokers . com / en / software / api / apiguide / java / cancelmktdata . htm"""
if contracts == None : contracts = list ( self . contracts . values ( ) ) elif not isinstance ( contracts , list ) : contracts = [ contracts ] for contract in contracts : # tickerId = self . tickerId ( contract . m _ symbol ) tickerId = self . tickerId ( self . contractString ( contract ) ) self . ibCon...
def use_mock ( self , mock , * args , ** kwarg ) : """Context manager or decorator in order to use a coroutine as mock of service endpoint in a test . : param mock : Coroutine to use as mock . It should behave like : meth : ` ~ ClientSession . request ` . : type mock : coroutine : param service _ name : Nam...
return UseMockDefinition ( mock , self , * args , ** kwarg )
def main ( ) : """Core function for the script"""
commands = [ 'update' , 'list' , 'get' , 'info' , 'count' , 'search' , 'download' ] parser = argparse . ArgumentParser ( description = "Command line access to software repositories for TI calculators, primarily ticalc.org and Cemetech" ) parser . add_argument ( "action" , metavar = "ACTION" , type = str , help = "The c...
def construct_1d_arraylike_from_scalar ( value , length , dtype ) : """create a np . ndarray / pandas type of specified shape and dtype filled with values Parameters value : scalar value length : int dtype : pandas _ dtype / np . dtype Returns np . ndarray / pandas type of length , filled with value""...
if is_datetime64tz_dtype ( dtype ) : from pandas import DatetimeIndex subarr = DatetimeIndex ( [ value ] * length , dtype = dtype ) elif is_categorical_dtype ( dtype ) : from pandas import Categorical subarr = Categorical ( [ value ] * length , dtype = dtype ) else : if not isinstance ( dtype , ( np...
def make_wheel_filename_generic ( wheel ) : """Wheel filenames contain the python version and the python ABI version for the wheel . https : / / www . python . org / dev / peps / pep - 0427 / # file - name - convention Since we ' re distributing a rust binary this doesn ' t matter for us . . ."""
name , version , python , abi , platform = wheel . split ( "-" ) # our binary handles multiple abi / versions of python python , abi = "py2.py3" , "none" # hack , lets pretend to be manylinux1 so we can do a binary distribution if platform == "linux_x86_64.whl" : platform = "manylinux1_x86_64.whl" elif platform == ...
def get_working_days_delta ( self , start , end ) : """Return the number of working day between two given dates . The order of the dates provided doesn ' t matter . In the following example , there are 5 days , because of the week - end : > > > cal = WesternCalendar ( ) # does not include easter monday > > ...
start = cleaned_date ( start ) end = cleaned_date ( end ) if start == end : return 0 if start > end : start , end = end , start # Starting count here count = 0 while start < end : start += timedelta ( days = 1 ) if self . is_working_day ( start ) : count += 1 return count
def version ( self ) : """Return kernel and btrfs version ."""
return dict ( buttersink = theVersion , btrfs = self . butterStore . butter . btrfsVersion , linux = platform . platform ( ) , )
def parse_objective_coefficient ( entry ) : """Return objective value for reaction entry . Detect objectives that are specified using the non - standardized kinetic law parameters which are used by many pre - FBC SBML models . The objective coefficient is returned for the given reaction , or None if undefin...
for parameter in entry . kinetic_law_reaction_parameters : pid , name , value , units = parameter if ( pid == 'OBJECTIVE_COEFFICIENT' or name == 'OBJECTIVE_COEFFICIENT' ) : return value return None
def killCellRegion ( self , centerColumn , radius ) : """Kill cells around a centerColumn , within radius"""
self . deadCols = topology . wrappingNeighborhood ( centerColumn , radius , self . _columnDimensions ) self . deadColumnInputSpan = self . getConnectedSpan ( self . deadCols ) self . removeDeadColumns ( )
def filter ( self , u ) : """Filter the valid identities for this matcher . : param u : unique identity which stores the identities to filter : returns : a list of identities valid to work with this matcher . : raises ValueError : when the unique identity is not an instance of UniqueIdentity class"""
if not isinstance ( u , UniqueIdentity ) : raise ValueError ( "<u> is not an instance of UniqueIdentity" ) filtered = [ ] for id_ in u . identities : email = None if self . sources and id_ . source . lower ( ) not in self . sources : continue if self . strict : if self . _check_email ( i...
def align_and_build_tree ( seqs , moltype , best_tree = False , params = None ) : """Returns an alignment and a tree from Sequences object seqs . seqs : a cogent . core . alignment . SequenceCollection object , or data that can be used to build one . moltype : cogent . core . moltype . MolType object best _...
aln = align_unaligned_seqs ( seqs , moltype = moltype , params = params ) tree = build_tree_from_alignment ( aln , moltype , best_tree , params ) return { 'Align' : aln , 'Tree' : tree }
def _return ( self , ary ) : """Wrap the ary to return an Array type"""
if isinstance ( ary , Array ) : return ary return Array ( ary , copy = False )
def run ( ) : """Main script entry to handle the arguments given to the script ."""
_parser_options ( ) set_verbose ( args [ "verbose" ] ) if _check_global_settings ( ) : _load_db ( ) else : exit ( - 1 ) # Check the server configuration against the script arguments passed in . _setup_server ( ) if args [ "rollback" ] : _server_rollback ( ) okay ( "The server rollback appears to have be...
def _fetch_output_files ( self , retrieved ) : """Checks the output folder for standard output and standard error files , returns their absolute paths on success . : param retrieved : A dictionary of retrieved nodes , as obtained from the parser ."""
from aiida . common . datastructures import calc_states from aiida . common . exceptions import InvalidOperation import os # check in order not to overwrite anything # state = self . _ calc . get _ state ( ) # if state ! = calc _ states . PARSING : # raise InvalidOperation ( " Calculation not in { } state " # . format ...