signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def setModel ( self , model ) : """sets the model for the auto parameters : param model : The data stucture for this editor to provide access to : type model : : class : ` QAutoParameterModel < sparkle . gui . stim . qauto _ parameter _ model . QAutoParameterModel > `"""
self . paramList . setModel ( model ) model . hintRequested . connect ( self . hintRequested ) model . rowsInserted . connect ( self . updateTitle ) model . rowsRemoved . connect ( self . updateTitle ) self . updateTitle ( )
def p_for_stmt ( p ) : """for _ stmt : FOR ident EQ expr SEMI stmt _ list END _ STMT | FOR LPAREN ident EQ expr RPAREN SEMI stmt _ list END _ STMT | FOR matrix EQ expr SEMI stmt _ list END _ STMT"""
if len ( p ) == 8 : if not isinstance ( p [ 2 ] , node . ident ) : raise_exception ( SyntaxError , "Not implemented: for loop" , new_lexer ) p [ 2 ] . props = "I" # I = for - loop iteration variable p [ 0 ] = node . for_stmt ( ident = p [ 2 ] , expr = p [ 4 ] , stmt_list = p [ 6 ] )
def _call ( self , x , out ) : """Implement ` ` self ( x , out ) ` ` ."""
with writable_array ( out ) as out_arr : resize_array ( x . asarray ( ) , self . range . shape , offset = self . offset , pad_mode = self . pad_mode , pad_const = self . pad_const , direction = 'forward' , out = out_arr )
def autocommit ( data_access ) : """Make statements autocommit . : param data _ access : a DataAccess instance"""
if not data_access . autocommit : data_access . commit ( ) old_autocommit = data_access . autocommit data_access . autocommit = True try : yield data_access finally : data_access . autocommit = old_autocommit
def parse_args ( args = sys . argv [ 1 : ] ) : """Parse command line arguments for Grole server running as static file server"""
parser = argparse . ArgumentParser ( ) parser . add_argument ( '-a' , '--address' , help = 'address to listen on, default localhost' , default = 'localhost' ) parser . add_argument ( '-p' , '--port' , help = 'port to listen on, default 1234' , default = 1234 , type = int ) parser . add_argument ( '-d' , '--directory' ,...
def GET_AUTH ( self ) : # pylint : disable = arguments - differ """GET request"""
userdata = self . database . users . find_one ( { "email" : self . user_manager . session_email ( ) } ) if not userdata : raise web . notfound ( ) return self . template_helper . get_renderer ( ) . preferences . profile ( "" , False )
def make_links ( self ) : """Replace the default behaviour of make _ links . More specifically , this method implements the logic required to connect DFPT calculation to ` DDK ` files . Remember that DDK is an extension introduced in AbiPy to deal with the irdddk input variable and the fact that the 3 files w...
for dep in self . deps : for d in dep . exts : if d == "DDK" : ddk_task = dep . node out_ddk = ddk_task . outdir . has_abiext ( "DDK" ) if not out_ddk : raise RuntimeError ( "%s didn't produce the DDK file" % ddk_task ) # Get ( fortran ) idir a...
def add_file ( self , fieldname , filename , filePath , mimetype = None ) : """Add a file to be uploaded . Inputs : fieldname - name of the POST value fieldname - name of the file to pass to the server filePath - path to the local file on disk mimetype - MIME stands for Multipurpose Internet Mail Extensio...
body = filePath if mimetype is None : mimetype = mimetypes . guess_type ( filename ) [ 0 ] or 'application/octet-stream' self . files . append ( ( fieldname , filename , mimetype , body ) )
def get ( self , request , * args , ** kwargs ) : '''Invoices can be viewed only if the validation string is provided , unless the user is logged in and has view _ all _ invoice permissions'''
user_has_validation_string = self . get_object ( ) . validationString user_has_permissions = request . user . has_perm ( 'core.view_all_invoices' ) if request . GET . get ( 'v' , None ) == user_has_validation_string or user_has_permissions : return super ( ViewInvoiceView , self ) . get ( request , * args , ** kwar...
async def Track ( self , payloads ) : '''payloads : typing . Sequence [ ~ Payload ] Returns - > typing . Sequence [ ~ PayloadResult ]'''
# map input types to rpc msg _params = dict ( ) msg = dict ( type = 'PayloadsHookContext' , request = 'Track' , version = 1 , params = _params ) _params [ 'payloads' ] = payloads reply = await self . rpc ( msg ) return reply
def snmp_server_enable_trap_trap_flag ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) snmp_server = ET . SubElement ( config , "snmp-server" , xmlns = "urn:brocade.com:mgmt:brocade-snmp" ) enable = ET . SubElement ( snmp_server , "enable" ) trap = ET . SubElement ( enable , "trap" ) trap_flag = ET . SubElement ( trap , "trap-flag" ) callback = kwargs . pop ( 'callback'...
def _GetIgnoredDirs ( self ) : """Get ignored directories values from database table . If no values found user will be prompted to enter values for this table . Returns string List of ignored directories from database table ."""
goodlogging . Log . Info ( "CLEAR" , "Loading ignored directories from database:" ) goodlogging . Log . IncreaseIndent ( ) ignoredDirs = self . _db . GetIgnoredDirs ( ) if ignoredDirs is None : goodlogging . Log . Info ( "CLEAR" , "No ignored directories exist in database" ) ignoredDirs = self . _UserUpdateIgno...
def import_string ( import_name , silent = False ) : """Imports an object based on a string . This is useful if you want to use import paths as endpoints or something similar . An import path can be specified either in dotted notation ( ` ` xml . sax . saxutils . escape ` ` ) or with a colon as object delimit...
try : if ':' in import_name : module , obj_name = import_name . split ( ':' , 1 ) elif '.' in import_name : module , obj_name = import_name . rsplit ( '.' , 1 ) else : return __import__ ( import_name ) return getattr ( __import__ ( module , None , None , [ obj_name ] ) , obj_name...
def clean ( self ) : """* parse and clean the html document with Mercury Parser * * * Return : * * - ` ` filePath ` ` - - path to the cleaned HTML document * * Usage : * * See class usage"""
self . log . debug ( 'starting the ``clean`` method' ) url = self . url # PARSE THE CONTENT OF THE WEBPAGE AT THE URL parser_response = self . _request_parsed_article_from_mercury ( url ) if "503" in str ( parser_response ) : return None article = parser_response . json ( ) if not article : return None # GRAB T...
def DeregisterFormatter ( cls , formatter_class ) : """Deregisters a formatter class . The formatter classes are identified based on their lower case data type . Args : formatter _ class ( type ) : class of the formatter . Raises : KeyError : if formatter class is not set for the corresponding data type ....
formatter_data_type = formatter_class . DATA_TYPE . lower ( ) if formatter_data_type not in cls . _formatter_classes : raise KeyError ( 'Formatter class not set for data type: {0:s}.' . format ( formatter_class . DATA_TYPE ) ) del cls . _formatter_classes [ formatter_data_type ]
def upload_complete ( self , path , url , quiet ) : """function to complete an upload to retrieve a path from a url Parameters path : the path for the upload that is read in url : the url to send the POST to quiet : suppress verbose output ( default is False )"""
file_size = os . path . getsize ( path ) try : with tqdm ( total = file_size , unit = 'B' , unit_scale = True , unit_divisor = 1024 , disable = quiet ) as progress_bar : with io . open ( path , 'rb' , buffering = 0 ) as fp : reader = TqdmBufferedReader ( fp , progress_bar ) session =...
def read_data ( self , ** kwargs ) : '''Read the datafile specified in Sample . datafile and return the resulting object . Does NOT assign the data to self . data It ' s advised not to use this method , but instead to access the data through the FCMeasurement . data attribute .'''
meta , data = parse_fcs ( self . datafile , ** kwargs ) return data
def num_throats ( self , labels = 'all' , mode = 'union' ) : r"""Return the number of throats of the specified labels Parameters labels : list of strings , optional The throat labels that should be included in the count . If not supplied , all throats are counted . mode : string , optional Specifies how...
# Count number of pores of specified type Ts = self . _get_indices ( labels = labels , mode = mode , element = 'throat' ) Nt = sp . shape ( Ts ) [ 0 ] return Nt
def broadcast ( self , data_dict ) : '''Send to the visualizer ( if there is one ) or enqueue for later'''
if self . vis_socket : self . queued_messages . append ( data_dict ) self . send_all_updates ( )
def preview ( self , n = 10 , k = 'items' , kheader = 'displayLink' , klink = 'link' , kdescription = 'snippet' ) : """Print a preview of the search results . Args : n ( int ) : Maximum number of search results to preview k ( str ) : Key in : class : ` api . results ` . metadata to preview kheader ( str...
if 'searchType' in self . cseargs : searchType = self . cseargs [ 'searchType' ] else : searchType = None items = self . metadata [ k ] # ( cse _ print ) Print results for i , kv in enumerate ( items [ : n ] ) : if 'start' in self . cseargs : i += int ( self . cseargs [ 'start' ] ) # ( print _ h...
def revnet_164_cifar ( ) : """Tiny hparams suitable for CIFAR / etc ."""
hparams = revnet_cifar_base ( ) hparams . bottleneck = True hparams . num_channels = [ 16 , 32 , 64 ] hparams . num_layers_per_block = [ 8 , 8 , 8 ] return hparams
def document ( self ) : """Render the error document"""
resp = request . environ . get ( 'pylons.original_response' ) content = literal ( resp . body ) or cgi . escape ( request . GET . get ( 'message' ) ) page = error_document_template % dict ( prefix = request . environ . get ( 'SCRIPT_NAME' , '' ) , code = cgi . escape ( request . GET . get ( 'code' , str ( resp . status...
def step ( self , amt = 1 ) : "Make a frame of the animation"
self . move_particles ( ) if self . has_moving_emitters : self . move_emitters ( ) self . start_new_particles ( ) self . render_particles ( ) if self . emitters == [ ] and self . particles == [ ] : self . completed = True
def best_case ( self , matrix , m_list , indices_left ) : """Computes a best case given a matrix and manipulation list . Args : matrix : the current matrix ( with some permutations already performed ) m _ list : [ ( multiplication fraction , number _ of _ indices , indices , species ) ] describing the man...
m_indices = [ ] fraction_list = [ ] for m in m_list : m_indices . extend ( m [ 2 ] ) fraction_list . extend ( [ m [ 0 ] ] * m [ 1 ] ) indices = list ( indices_left . intersection ( m_indices ) ) interaction_matrix = matrix [ indices , : ] [ : , indices ] fractions = np . zeros ( len ( interaction_matrix ) ) + 1...
def has_documented_type_or_fields ( self , include_inherited_fields = False ) : """Returns whether this type , or any of its fields , are documented . Use this when deciding whether to create a block of documentation for this type ."""
if self . doc : return True else : return self . has_documented_fields ( include_inherited_fields )
def validate_probability ( p : float , p_str : str ) -> float : """Validates that a probability is between 0 and 1 inclusively . Args : p : The value to validate . p _ str : What to call the probability in error messages . Returns : The probability p if the probability if valid . Raises : ValueError i...
if p < 0 : raise ValueError ( '{} was less than 0.' . format ( p_str ) ) elif p > 1 : raise ValueError ( '{} was greater than 1.' . format ( p_str ) ) return p
def shorten_line ( tokens , source , indentation , indent_word , max_line_length , aggressive = False , experimental = False , previous_line = '' ) : """Separate line at OPERATOR . Multiple candidates will be yielded ."""
for candidate in _shorten_line ( tokens = tokens , source = source , indentation = indentation , indent_word = indent_word , aggressive = aggressive , previous_line = previous_line ) : yield candidate if aggressive : for key_token_strings in SHORTEN_OPERATOR_GROUPS : shortened = _shorten_line_at_tokens ...
def from_dict ( cls , d , alternative_paths = { } , datasets = None , pwd = None , ignore_keys = [ 'attrs' , 'plotter' , 'ds' ] , only = None , chname = { } , ** kwargs ) : """Create a list from the dictionary returned by : meth : ` array _ info ` This classmethod creates an : class : ` ~ psyplot . data . ArrayLi...
pwd = pwd or getcwd ( ) if only is None : def only_filter ( arr_name , info ) : return True elif callable ( only ) : only_filter = only elif isstring ( only ) : def only_filter ( arr_name , info ) : return patt . search ( arr_name ) is not None patt = re . compile ( only ) only = Non...
def _get_max_subplot_ids ( fig ) : """Given an input figure , return a dict containing the max subplot number for each subplot type in the figure Parameters fig : dict A plotly figure dict Returns dict A dict from subplot type strings to integers indicating the largest subplot number in the figure o...
max_subplot_ids = { subplot_type : 0 for subplot_type in _subplot_types } max_subplot_ids [ 'xaxis' ] = 0 max_subplot_ids [ 'yaxis' ] = 0 for trace in fig . get ( 'data' , [ ] ) : trace_type = trace . get ( 'type' , 'scatter' ) subplot_types = _trace_to_subplot . get ( trace_type , [ ] ) for subplot_type in...
def get_mean_and_stddevs ( self , sites , rup , dists , imt , stddev_types ) : """See : meth : ` superclass method < . base . GroundShakingIntensityModel . get _ mean _ and _ stddevs > ` for spec of input and result values ."""
# extract dictionaries of coefficients specific to required # intensity measure type C = self . COEFFS [ imt ] mean = self . _compute_mean ( C , rup , dists , sites , imt ) stddevs = self . _get_stddevs ( C , stddev_types , sites . vs30 . shape [ 0 ] ) return mean , stddevs
def decode ( cls , command_str ) : """Decode a string encoded command back into a Command object . Args : command _ str ( str ) : The encoded command string output from a previous call to encode . Returns : Command : The decoded Command object ."""
name , _ , arg = command_str . partition ( " " ) args = [ ] if len ( arg ) > 0 : if arg [ 0 ] != '{' or arg [ - 1 ] != '}' : raise DataError ( "Invalid command, argument is not contained in { and }" , arg = arg , cmd = name ) arg = arg [ 1 : - 1 ] args = arg . split ( "," ) proc = [ ] for arg in arg...
def paragraph ( node ) : """Process a paragraph , which includes all content under it"""
text = '' if node . string_content is not None : text = node . string_content o = nodes . paragraph ( '' , ' ' . join ( text ) ) o . line = node . sourcepos [ 0 ] [ 0 ] for n in MarkDown ( node ) : o . append ( n ) return o
def get_plugins ( modules , classes ) : """Find all given ( sub - ) classes in all modules . @ param modules : the modules to search @ ptype modules : iterator of modules @ return : found classes @ rytpe : iterator of class objects"""
for module in modules : for plugin in get_module_plugins ( module , classes ) : yield plugin
def visit_FormattedValue ( self , node ) : """FormattedValue ( expr value , int ? conversion , expr ? format _ spec )"""
self . result += '{' self . visit ( node . value ) self . result += { - 1 : '' , # no formatting 97 : '!a' , # ascii formatting 114 : '!r' , # repr formatting 115 : '!s' , # string formatting } [ node . conversion ] if node . format_spec : self . result += ':' self . visit_joined_str ( node . format_spec ) self...
def _hijack_target ( self ) : """Replaces the target method on the target object with the proxy method ."""
if self . _target . is_class_or_module ( ) : setattr ( self . _target . obj , self . _method_name , self ) elif self . _attr . kind == 'property' : proxy_property = ProxyProperty ( double_name ( self . _method_name ) , self . _original_method , ) setattr ( self . _target . obj . __class__ , self . _method_n...
def OnToggle ( self , event ) : """Toggle button event handler"""
if self . selection_toggle_button . GetValue ( ) : self . entry_line . last_selection = self . entry_line . GetSelection ( ) self . entry_line . last_selection_string = self . entry_line . GetStringSelection ( ) self . entry_line . last_table = self . main_window . grid . current_table self . entry_line...
def autogen_argparse_block ( extra_args = [ ] ) : """SHOULD TURN ANY REGISTERED ARGS INTO A A NEW PARSING CONFIG FILE FOR BETTER - - help COMMANDS import utool as ut _ _ REGISTERED _ ARGS _ _ = ut . util _ arg . _ _ REGISTERED _ ARGS _ _ Args : extra _ args ( list ) : ( default = [ ] ) CommandLine : p...
# import utool as ut # NOQA # _ _ REGISTERED _ ARGS _ _ # TODO FINISHME grouped_args = [ ] # Group similar a args for argtup in __REGISTERED_ARGS__ : argstr_list , type_ , default , help_ = argtup argstr_set = set ( argstr_list ) # < MULTIKEY _ SETATTR > # hack in multikey setattr n * * 2 yuck found...
def convert ( self , plugin = None ) : """Return a : class : ` PluginBlockType ` for the given plugin name . If plugin is ` ` None ` ` , return the first registered plugin ."""
if plugin : plugin = kurt . plugin . Kurt . get_plugin ( plugin ) if plugin . name in self . _plugins : return self . _plugins [ plugin . name ] else : err = BlockNotSupported ( "%s doesn't have %r" % ( plugin . display_name , self ) ) err . block_type = self raise err else :...
def _fetch_url_data ( self , url , username , password , verify , custom_headers ) : '''Hit a given http url and return the stats lines'''
# Try to fetch data from the stats URL auth = ( username , password ) url = "%s%s" % ( url , STATS_URL ) custom_headers . update ( headers ( self . agentConfig ) ) self . log . debug ( "Fetching haproxy stats from url: %s" % url ) response = requests . get ( url , auth = auth , headers = custom_headers , verify = verif...
def _write_build_file ( self ) : """Write Maven build file ( pom . xml )"""
self . write ( destination = self . _base_output_directory , filename = "pom.xml" , template_name = "pom.xml.tpl" , version = self . api_version , product_accronym = self . _product_accronym , class_prefix = self . _class_prefix , root_api = self . api_root , api_prefix = self . api_prefix , product_name = self . _prod...
def rabin_karp_factor ( s , t , k ) : """Find a common factor by Rabin - Karp : param string s : haystack : param string t : needle : param int k : factor length : returns : ( i , j ) such that s [ i : i + k ] = = t [ j : j + k ] or None . In case of tie , lexicographical minimum ( i , j ) is returned :...
last_pos = pow ( DOMAIN , k - 1 ) % PRIME pos = { } assert k > 0 if len ( s ) < k or len ( t ) < k : return None hash_t = 0 for j in range ( k ) : # store hashing values hash_t = ( DOMAIN * hash_t + ord ( t [ j ] ) ) % PRIME for j in range ( len ( t ) - k + 1 ) : if hash_t in pos : pos [ hash_t ] . ...
def shutdown ( self , container , instances = None , map_name = None , ** kwargs ) : """Shut down container instances from a container configuration . Typically this means stopping and removing containers . Note that not all policy classes necessarily implement this method . : param container : Container name ....
return self . run_actions ( 'shutdown' , container , instances = instances , map_name = map_name , ** kwargs )
def GetWSAActionFault ( operation , name ) : """Find wsa : Action attribute , and return value or WSA . FAULT for the default ."""
attr = operation . faults [ name ] . action if attr is not None : return attr return WSA . FAULT
def install_cygwin ( name , install_args = None , override_args = False ) : '''Instructs Chocolatey to install a package via Cygwin . name The name of the package to be installed . Only accepts a single argument . install _ args A list of install arguments you want to pass to the installation process i . ...
return install ( name , source = 'cygwin' , install_args = install_args , override_args = override_args )
def t_INDENTIFIER ( t ) : r'( \ $ ? [ _ a - zA - Z ] [ _ a - zA - Z0-9 ] * ) | ( _ _ [ A - Z _ ] + _ _ )'
if t . value in reserved : t . type = t . value . upper ( ) if t . value in reservedMap : t . value = reservedMap [ t . value ] elif t . value in strStatment : t . type = 'STATEMENT' return t
def count_relations ( graph ) -> Counter : """Return a histogram over all relationships in a graph . : param pybel . BELGraph graph : A BEL graph : return : A Counter from { relation type : frequency }"""
return Counter ( data [ RELATION ] for _ , _ , data in graph . edges ( data = True ) )
def _evaluate ( self , R , phi = 0. , t = 0. ) : """NAME : _ evaluate PURPOSE : evaluate the potential at R , phi , t INPUT : R - Galactocentric cylindrical radius phi - azimuth t - time OUTPUT : Phi ( R , phi , t ) HISTORY : 2011-10-19 - Started - Bovy ( IAS )"""
# Calculate relevant time if not self . _tform is None : if t < self . _tform : smooth = 0. elif t < self . _tsteady : deltat = t - self . _tform xi = 2. * deltat / ( self . _tsteady - self . _tform ) - 1. smooth = ( 3. / 16. * xi ** 5. - 5. / 8 * xi ** 3. + 15. / 16. * xi + .5 )...
def render_scene ( self ) : "render scene one time"
self . init_gl ( ) # should be a no - op after the first frame is rendered glfw . make_context_current ( self . window ) self . renderer . render_scene ( ) # Done rendering # glfw . swap _ buffers ( self . window ) # avoid double buffering to avoid stalling glFlush ( ) # single buffering glfw . poll_events ( )
def split_name ( name ) : """Extracts pieces of name from full name string . Full name can have one of these formats : < NAME _ TEXT > | / < NAME _ TEXT > / | < NAME _ TEXT > / < NAME _ TEXT > / | / < NAME _ TEXT > / < NAME _ TEXT > | < NAME _ TEXT > / < NAME _ TEXT > / < NAME _ TEXT > < NAME _ TEXT >...
given1 , _ , rem = name . partition ( "/" ) surname , _ , given2 = rem . partition ( "/" ) return given1 . strip ( ) , surname . strip ( ) , given2 . strip ( )
def reset_script ( self ) : """Clear any partially received script ."""
self . remote_bridge . status = BRIDGE_STATUS . IDLE self . remote_bridge . error = 0 self . remote_bridge . parsed_script = None self . _device . script = bytearray ( ) return [ 0 ]
def immediate_postdominators ( self , end , target_graph = None ) : """Get all immediate postdominators of sub graph from given node upwards . : param str start : id of the node to navigate forwards from . : param networkx . classes . digraph . DiGraph target _ graph : graph to analyse , default is self . graph...
return self . _immediate_dominators ( end , target_graph = target_graph , reverse_graph = True )
def compute_total ( self , precision = None ) : '''Gets the total of the invoice with a defined decimal precision @ param precision : int Number of decimal places @ return : Decimal'''
return quantize ( ( self . compute_gross ( precision ) + self . compute_taxes ( precision ) - self . compute_discounts ( precision ) ) , places = precision )
def factory ( container , name = None ) : """A decorator to register a factory on the container . For more information see : meth : ` Container . add _ factory ` ."""
def register ( factory ) : container . add_factory ( factory , name ) return factory return register
def _is_valid_inherit_element ( self , element ) : """Check that the children of element can be manipulated to apply the CSS properties . : param element : The element . : type element : hatemile . util . html . htmldomelement . HTMLDOMElement : return : True if the children of element can be manipulated to...
# pylint : disable = no - self - use tag_name = element . get_tag_name ( ) return ( ( tag_name in AccessibleCSSImplementation . VALID_INHERIT_TAGS ) and ( not element . has_attribute ( CommonFunctions . DATA_IGNORE ) ) )
def refresh ( self ) : """Updates the current line decoration"""
if self . enabled and self . line : self . _clear_deco ( ) brush = QtGui . QBrush ( self . _color ) self . _decoration = TextDecoration ( self . editor . textCursor ( ) , start_line = self . line ) self . _decoration . set_background ( brush ) self . _decoration . set_full_width ( ) self . _deco...
def find_revision_number ( self , revision = None ) : """Find the local revision number of the given revision ."""
# Make sure the local repository exists . self . create ( ) # Try to find the revision number of the specified revision . revision = revision or self . default_revision output = self . context . capture ( 'hg' , 'id' , '--rev=%s' % revision , '--num' ) . rstrip ( '+' ) # Validate the ` hg id - - num ' output . if not o...
def num_pores ( self , labels = 'all' , mode = 'or' ) : r"""Returns the number of pores of the specified labels Parameters labels : list of strings , optional The pore labels that should be included in the count . If not supplied , all pores are counted . labels : list of strings Label of pores to be re...
# Count number of pores of specified type Ps = self . _get_indices ( labels = labels , mode = mode , element = 'pore' ) Np = sp . shape ( Ps ) [ 0 ] return Np
def to_bitstream ( self ) : '''Create bitstream from properties'''
# Verify that properties make sense self . sanitize ( ) # Start with the TTL bitstream = BitArray ( 'uint:32=%d' % self . ttl ) # Add the locator count bitstream += BitArray ( 'uint:8=%d' % len ( self . locator_records ) ) # Add the EID prefix mask length bitstream += BitArray ( 'uint:8=%d' % self . eid_prefix . prefix...
def _islinklike ( dir_path ) : '''Parameters dir _ path : str Directory path . Returns bool ` ` True ` ` if : data : ` dir _ path ` is a link * or * junction .'''
dir_path = ph . path ( dir_path ) if platform . system ( ) == 'Windows' : if dir_path . isjunction ( ) : return True elif dir_path . islink ( ) : return True return False
def copy ( self , target_parent , name = None , include_children = True , include_instances = True ) : """Copy the ` Part ` to target parent , both of them having the same category . . . versionadded : : 2.3 : param target _ parent : ` Part ` object under which the desired ` Part ` is copied : type target _ p...
if self . category == Category . MODEL and target_parent . category == Category . MODEL : # Cannot add a model under an instance or vice versa copied_model = relocate_model ( part = self , target_parent = target_parent , name = name , include_children = include_children ) if include_instances : instance...
def paired_environment_phenotype_grid ( environment , phenotypes , ** kwargs ) : """Plots the given environment ( EnvironmentFile object ) and phenotypes (2d array of numbers or binary strings ) onto the same image and saves the image based on the name of the environment file . The environment file will be re...
denom , palette = get_kwargs ( environment , kwargs ) print ( "plot world" ) plot_world ( environment , palette = environment . resource_palette , denom = denom ) print ( "plot phens" ) plot_phens ( phenotypes , palette = environment . task_palette , denom = denom ) print ( "save" ) plt . savefig ( "phenotype_niches_" ...
def items ( self ) : """Return a copied list of the property names and values of this CIM instance . Each item in the returned list is a tuple of property name ( in the original lexical case ) and property value . The order of properties is preserved ."""
return [ ( key , v . value ) for key , v in self . properties . items ( ) ]
def getPixmap ( self , matrix = None , colorspace = None , alpha = 0 , clip = None ) : """getPixmap ( self , matrix = None , colorspace = None , alpha = 0 , clip = None ) - > Pixmap"""
return _fitz . DisplayList_getPixmap ( self , matrix , colorspace , alpha , clip )
def data_received ( self , data ) : """Used to signal ` asyncio . Protocol ` of incoming data ."""
if self . _on_data : self . _on_data ( data ) return self . _queued_data . append ( data )
def predict_quantiles ( self , X , quantiles = ( 2.5 , 97.5 ) , Y_metadata = None , likelihood = None , kern = None ) : """Get the predictive quantiles around the prediction at X : param X : The points at which to make a prediction : type X : np . ndarray ( Xnew x self . input _ dim ) : param quantiles : tupl...
qs = super ( WarpedGP , self ) . predict_quantiles ( X , quantiles , Y_metadata = Y_metadata , likelihood = likelihood , kern = kern ) if self . predict_in_warped_space : return [ self . warping_function . f_inv ( q ) for q in qs ] return qs
def create_modelo ( self ) : """Get an instance of modelo services facade ."""
return Modelo ( self . networkapi_url , self . user , self . password , self . user_ldap )
def update_floatingip ( floatingip_id , port = None , profile = None ) : '''Updates a floatingIP CLI Example : . . code - block : : bash salt ' * ' neutron . update _ floatingip network - name port - name : param floatingip _ id : ID of floatingIP : param port : ID or name of port , to associate floatingi...
conn = _auth ( profile ) return conn . update_floatingip ( floatingip_id , port )
def _parse_value ( self , raw ) : """Parses value : param raw : raw value : return : Parsed value"""
try : if not raw . startswith ( "0" ) : val = float ( raw ) if ( val % 1 ) == 0 : # integer val = int ( raw ) return str ( val ) return self . num_format . format ( val ) else : raise ValueError ( "Cannot parse int!" ) except : return str ( raw )
def check_status ( zap_helper , timeout ) : """Check if ZAP is running and able to receive API calls . You can provide a timeout option which is the amount of time in seconds the command should wait for ZAP to start if it is not currently running . This is useful to run before calling other commands if ZAP wa...
with helpers . zap_error_handler ( ) : if zap_helper . is_running ( ) : console . info ( 'ZAP is running' ) elif timeout is not None : zap_helper . wait_for_zap ( timeout ) console . info ( 'ZAP is running' ) else : console . error ( 'ZAP is not running' ) sys . exit ...
def add_site ( self , site_name , location_name = None , er_data = None , pmag_data = None ) : """Create a Site object and add it to self . sites . If a location name is provided , add the site to location . sites as well ."""
if location_name : location = self . find_by_name ( location_name , self . locations ) if not location : location = self . add_location ( location_name ) else : location = None # # check all declinations / azimuths / longitudes in range 0 = > 360. # for key , value in er _ data . items ( ) : # er _ ...
def _get_available_letters ( field_name , queryset ) : """Makes a query to the database to return the first character of each value of the field and table passed in . Returns a set that represents the letters that exist in the database ."""
if django . VERSION [ 1 ] <= 4 : result = queryset . values ( field_name ) . annotate ( fl = FirstLetter ( field_name ) ) . values ( 'fl' ) . distinct ( ) return set ( [ res [ 'fl' ] for res in result if res [ 'fl' ] is not None ] ) else : from django . db import connection qn = connection . ops . quote...
def rebuild_schema ( doc , r , df ) : """Rebuild the schema for a resource based on a dataframe"""
import numpy as np # Re - get the resource in the doc , since it may be different . try : r = doc . resource ( r . name ) except AttributeError : # Maybe r is actually a resource name r = doc . resource ( r ) def alt_col_name ( name , i ) : import re if not name : return 'col{}' . format ( i ) ...
def convert_list ( self , list_input ) : """Iterate over the JSON list and process it to generate either an HTML table or a HTML list , depending on what ' s inside . If suppose some key has array of objects and all the keys are same , instead of creating a new row for each such entry , club such values , t...
if not list_input : return "" converted_output = "" column_headers = None if self . clubbing : column_headers = self . column_headers_from_list_of_dicts ( list_input ) if column_headers is not None : converted_output += self . table_init_markup converted_output += '<thead>' converted_output += '<tr>...
def _internal_kv_get ( key ) : """Fetch the value of a binary key ."""
worker = ray . worker . get_global_worker ( ) if worker . mode == ray . worker . LOCAL_MODE : return _local . get ( key ) return worker . redis_client . hget ( key , "value" )
def get_index ( self , as_dict = False , grouping_pattern = None ) : """Returns the index of the DataFrames in the system Parameters as _ dict : boolean , optional If True , returns a 1:1 key - value matching for further processing prior to groupby functions . Otherwise ( default ) the index is returned a...
possible_dataframes = [ 'A' , 'L' , 'Z' , 'Y' , 'F' , 'FY' , 'M' , 'S' , 'D_cba' , 'D_pba' , 'D_imp' , 'D_exp' , 'D_cba_reg' , 'D_pba_reg' , 'D_imp_reg' , 'D_exp_reg' , 'D_cba_cap' , 'D_pba_cap' , 'D_imp_cap' , 'D_exp_cap' , ] for df in possible_dataframes : if ( df in self . __dict__ ) and ( getattr ( self , df ) ...
def sct2e ( sc , sclkdp ) : """Convert encoded spacecraft clock ( " ticks " ) to ephemeris seconds past J2000 ( ET ) . http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / sct2e _ c . html : param sc : NAIF spacecraft ID code . : type sc : int : param sclkdp : SCLK , encoded as ...
sc = ctypes . c_int ( sc ) sclkdp = ctypes . c_double ( sclkdp ) et = ctypes . c_double ( ) libspice . sct2e_c ( sc , sclkdp , ctypes . byref ( et ) ) return et . value
def sample ( records , k , random_seed = None ) : """Choose a length - ` ` k ` ` subset of ` ` records ` ` , retaining the input order . If k > len ( records ) , all are returned . If an integer ` ` random _ seed ` ` is provided , sets ` ` random . seed ( ) ` `"""
if random_seed is not None : random . seed ( random_seed ) result = [ ] for i , record in enumerate ( records ) : if len ( result ) < k : result . append ( record ) else : r = random . randint ( 0 , i ) if r < k : result [ r ] = record return result
def strace_read ( self , num_instructions ) : """Reads and returns a number of instructions captured by STRACE . The number of instructions must be a non - negative value of at most ` ` 0x10000 ` ` ( ` ` 65536 ` ` ) . Args : self ( JLink ) : the ` ` JLink ` ` instance . num _ instructions ( int ) : number...
if num_instructions < 0 or num_instructions > 0x10000 : raise ValueError ( 'Invalid instruction count.' ) buf = ( ctypes . c_uint32 * num_instructions ) ( ) buf_size = num_instructions res = self . _dll . JLINK_STRACE_Read ( ctypes . byref ( buf ) , buf_size ) if res < 0 : raise errors . JLinkException ( 'Faile...
def memory_objects_for_hash ( self , n ) : """Returns a set of : class : ` SimMemoryObjects ` that contain expressions that contain a variable with the hash"""
return set ( [ self [ i ] for i in self . addrs_for_hash ( n ) ] )
def query ( self , query_str , * query_args , ** query_options ) : """run a raw query on the db query _ str - - string - - the query to run * query _ args - - if the query _ str is a formatting string , pass the values in this * * query _ options - - any query options can be passed in by using key = val synta...
with self . connection ( ** query_options ) as connection : query_options [ 'connection' ] = connection return self . _query ( query_str , query_args , ** query_options )
def v ( msg , * args , ** kwargs ) : '''log a message at verbose level ;'''
return logging . log ( VERBOSE , msg , * args , ** kwargs )
def _sendAction ( self , action , attrs = None , chan_vars = None ) : """Send action to Asterisk Manager Interface . @ param action : Action name @ param attrs : Tuple of key - value pairs for action attributes . @ param chan _ vars : Tuple of key - value pairs for channel variables ."""
self . _conn . write ( "Action: %s\r\n" % action ) if attrs : for ( key , val ) in attrs : self . _conn . write ( "%s: %s\r\n" % ( key , val ) ) if chan_vars : for ( key , val ) in chan_vars : self . _conn . write ( "Variable: %s=%s\r\n" % ( key , val ) ) self . _conn . write ( "\r\n" )
def ensure_instance ( value , types ) : """Ensure value is an instance of a certain type > > > ensure _ instance ( 1 , [ str ] ) Traceback ( most recent call last ) : TypeError : > > > ensure _ instance ( 1 , str ) Traceback ( most recent call last ) : TypeError : > > > ensure _ instance ( 1 , int ) ...
if not isinstance ( value , types ) : raise TypeError ( "expected instance of {}, got {}" . format ( types , value ) )
def loads ( s , single = False ) : """Deserialize : class : ` Eds ` string representations Args : s ( str ) : Eds string single ( bool ) : if ` True ` , only return the first Xmrs object Returns : a generator of : class : ` Eds ` objects ( unless the * single * option is ` True ` )"""
es = deserialize ( s ) if single : return next ( es ) return es
def update_ssl_termination ( self , securePort = None , enabled = None , secureTrafficOnly = None ) : """Updates existing SSL termination information for the load balancer without affecting the existing certificates / keys ."""
return self . manager . update_ssl_termination ( self , securePort = securePort , enabled = enabled , secureTrafficOnly = secureTrafficOnly )
def newton_iterate ( evaluate_fn , s , t ) : r"""Perform a Newton iteration . In this function , we assume that : math : ` s ` and : math : ` t ` are nonzero , this makes convergence easier to detect since " relative error " at ` ` 0.0 ` ` is not a useful measure . There are several tolerance / threshold qu...
# Several quantities will be tracked throughout the iteration : # * norm _ update _ prev : | | p { n } - p { n - 1 } | | = | | dp { n - 1 } | | # * norm _ update : | | p { n + 1 } - p { n } | | = | | dp { n } | | # * linear _ updates : This is a count on the number of times that # ` ` dp { n } ` ` " looks like " ` ` dp...
def print_direction_mean ( mean_dictionary ) : """Does a pretty job printing a Fisher mean and associated statistics for directional data . Parameters mean _ dictionary : output dictionary of pmag . fisher _ mean Examples Generate a Fisher mean using ` ` ipmag . fisher _ mean ` ` and then print it nicely ...
print ( 'Dec: ' + str ( round ( mean_dictionary [ 'dec' ] , 1 ) ) + ' Inc: ' + str ( round ( mean_dictionary [ 'inc' ] , 1 ) ) ) print ( 'Number of directions in mean (n): ' + str ( mean_dictionary [ 'n' ] ) ) print ( 'Angular radius of 95% confidence (a_95): ' + str ( round ( mean_dictionary [ 'alpha95' ] , 1 ) ) ) p...
def to_json ( cls , obj ) : """Serialize wrapped datetime . timedelta instance to a string the with the following format : [ DAYS ] d [ SECONDS ] s [ MICROSECONDS ] us"""
return "{0}d {1}s {2}us" . format ( obj . days , obj . seconds , obj . microseconds )
def close ( self , code : int = None , reason : str = None ) -> None : """Closes the WebSocket connection ."""
if not self . server_terminated : if not self . stream . closed ( ) : if code is None and reason is not None : code = 1000 # " normal closure " status code if code is None : close_data = b"" else : close_data = struct . pack ( ">H" , code ) ...
def _read_charge_and_multiplicity ( self ) : """Parses charge and multiplicity ."""
temp_charge = read_pattern ( self . text , { "key" : r"\$molecule\s+([\-\d]+)\s+\d" } , terminate_on_match = True ) . get ( 'key' ) if temp_charge != None : self . data [ "charge" ] = int ( temp_charge [ 0 ] [ 0 ] ) else : temp_charge = read_pattern ( self . text , { "key" : r"Sum of atomic charges \=\s+([\d\-\...
def readValuesBigWigToWig ( self , reference , start , end ) : """Read a bigwig file and return a protocol object with values within the query range . This method uses the bigWigToWig command line tool from UCSC GoldenPath . The tool is used to return values within a query region . The output is in wiggle f...
if not self . checkReference ( reference ) : raise exceptions . ReferenceNameNotFoundException ( reference ) if start < 0 : raise exceptions . ReferenceRangeErrorException ( reference , start , end ) # TODO : CHECK IF QUERY IS BEYOND END cmd = [ "bigWigToWig" , self . _sourceFile , "stdout" , "-chrom=" + re...
def generateSteps ( self , minStep ) : """Generate allowed steps with step > = minStep in increasing order ."""
self . checkFinite ( minStep ) if self . binary : base = 2.0 mantissas = [ 1.0 ] exponent = math . floor ( math . log ( minStep , 2 ) - EPSILON ) else : base = 10.0 mantissas = [ 1.0 , 2.0 , 5.0 ] exponent = math . floor ( math . log10 ( minStep ) - EPSILON ) while True : multiplier = base *...
def init_parsecmdline ( argv = [ ] ) : """Parse arguments from the command line : param argv : list of arguments"""
# main argument parser parser = argparse . ArgumentParser ( prog = PKG_NAME ) # - - version parser . add_argument ( '--version' , action = 'version' , version = version ) # - c , - - config < file _ name > parser . add_argument ( "-c" , "--config" , action = "store" , dest = "config_file" , default = config . CONF_DEFA...
def condensed_coords ( i , j , n ) : """Transform square distance matrix coordinates to the corresponding index into a condensed , 1D form of the matrix . Parameters i : int Row index . j : int Column index . n : int Size of the square matrix ( length of first or second dimension ) . Returns ix ...
# guard conditions if i == j or i >= n or j >= n or i < 0 or j < 0 : raise ValueError ( 'invalid coordinates: %s, %s' % ( i , j ) ) # normalise order i , j = sorted ( [ i , j ] ) # calculate number of items in rows before this one ( sum of arithmetic # progression ) x = i * ( ( 2 * n ) - i - 1 ) / 2 # add on previo...
def get_vnetwork_vswitches_output_vnetwork_vswitches_pnic ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) get_vnetwork_vswitches = ET . Element ( "get_vnetwork_vswitches" ) config = get_vnetwork_vswitches output = ET . SubElement ( get_vnetwork_vswitches , "output" ) vnetwork_vswitches = ET . SubElement ( output , "vnetwork-vswitches" ) pnic = ET . SubElement ( vnetwork_vswitches , "pnic"...
def decode_length ( self , data , state ) : """Extract and decode a frame length from the data buffer . The consumed data should be removed from the buffer . If the length data is incomplete , must raise a ` ` NoFrames ` ` exception . : param data : A ` ` bytearray ` ` instance containing the data so far ...
# Do we have enough data yet ? if len ( data ) < self . fmt . size : raise exc . NoFrames ( ) # Extract the length length = self . fmt . unpack ( six . binary_type ( data [ : self . fmt . size ] ) ) [ 0 ] del data [ : self . fmt . size ] # Return the length return length
def create_database ( self , name , path = None , force = False ) : """Create a new Impala database Parameters name : string Database name path : string , default None HDFS path where to store the database data ; otherwise uses Impala default"""
if path : # explicit mkdir ensures the user own the dir rather than impala , # which is easier for manual cleanup , if necessary self . hdfs . mkdir ( path ) statement = ddl . CreateDatabase ( name , path = path , can_exist = force ) return self . _execute ( statement )
def create_geoms ( self , plot ) : """Make information needed to draw a legend for each of the layers . For each layer , that information is a dictionary with the geom to draw the guide together with the data and the parameters that will be used in the call to geom ."""
def get_legend_geom ( layer ) : if hasattr ( layer . geom , 'draw_legend' ) : geom = layer . geom . __class__ else : name = 'geom_{}' . format ( layer . geom . legend_geom ) geom = Registry [ name ] return geom # A layer either contributes to the guide , or it does not . The # guide ...
def map_subcommands ( self , func ) : """Run ` func ` against all the subcommands attached to our root command ."""
def crawl ( cmd ) : for sc in cmd . subcommands . values ( ) : yield from crawl ( sc ) yield cmd return map ( func , crawl ( self . root_command ) )
def insert_statement ( table , columns , values ) : """Generate an insert statement string for dumping to text file or MySQL execution ."""
if not all ( isinstance ( r , ( list , set , tuple ) ) for r in values ) : values = [ [ r ] for r in values ] rows = [ ] for row in values : new_row = [ ] for col in row : if col is None : new_col = 'NULL' elif isinstance ( col , ( int , float , Decimal ) ) : new_col ...