signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_siblings_treepos ( self , treepos ) : """Given a treeposition , return the treepositions of its siblings ."""
parent_pos = self . get_parent_treepos ( treepos ) siblings_treepos = [ ] if parent_pos is not None : for child_treepos in self . get_children_treepos ( parent_pos ) : if child_treepos != treepos : siblings_treepos . append ( child_treepos ) return siblings_treepos
def process ( self , request , item ) : """Process a PayPal direct payment ."""
warn_untested ( ) from paypal . pro . helpers import PayPalWPP wpp = PayPalWPP ( request ) params = self . cleaned_data params [ 'creditcardtype' ] = self . fields [ 'acct' ] . card_type params [ 'expdate' ] = self . cleaned_data [ 'expdate' ] . strftime ( "%m%Y" ) params [ 'ipaddress' ] = request . META . get ( "REMOT...
def to_python ( self , data ) : """Adds support for txtinfo format"""
try : return super ( OlsrParser , self ) . to_python ( data ) except ConversionException as e : return self . _txtinfo_to_jsoninfo ( e . data )
def copy ( self , newdoc = None , idsuffix = "" ) : """Make a deep copy of this element and all its children . Parameters : newdoc ( : class : ` Document ` ) : The document the copy should be associated with . idsuffix ( str or bool ) : If set to a string , the ID of the copy will be append with this ( preven...
if idsuffix is True : idsuffix = ".copy." + "%08x" % random . getrandbits ( 32 ) # random 32 - bit hash for each copy , same one will be reused for all children c = deepcopy ( self ) if idsuffix : c . addidsuffix ( idsuffix ) c . setparents ( ) c . setdoc ( newdoc ) return c
def show_menu ( title , options , default = None , height = None , width = None , multiselect = False , precolored = False ) : """Shows an interactive menu in the terminal . Arguments : options : list of menu options default : initial option to highlight height : maximum height of the menu width : maximum...
plugins = [ FilterPlugin ( ) ] if any ( isinstance ( opt , OptionGroup ) for opt in options ) : plugins . append ( OptionGroupPlugin ( ) ) if title : plugins . append ( TitlePlugin ( title ) ) if precolored : plugins . append ( PrecoloredPlugin ( ) ) menu = Termenu ( options , default = default , height = h...
def _set_edge_loop_detection_native ( self , v , load = False ) : """Setter method for edge _ loop _ detection _ native , mapped from YANG variable / interface / ethernet / edge _ loop _ detection _ native ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ ed...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = edge_loop_detection_native . edge_loop_detection_native , is_container = 'container' , presence = False , yang_name = "edge-loop-detection-native" , rest_name = "" , parent = self , path_helper = self . _path_helper , extmeth...
def _get_forums_for_user ( self , user , perm_codenames , use_tree_hierarchy = False ) : """Returns all the forums that satisfy the given list of permission codenames . User and group forum permissions are used . If the ` ` use _ tree _ hierarchy ` ` keyword argument is set the granted forums will be filtered s...
granted_forums_cache_key = '{}__{}' . format ( ':' . join ( perm_codenames ) , user . id if not user . is_anonymous else 'anonymous' , ) if granted_forums_cache_key in self . _granted_forums_cache : return self . _granted_forums_cache [ granted_forums_cache_key ] forums = self . _get_all_forums ( ) # First check if...
def vtmlrender ( vtmarkup , plain = None , strict = False , vtmlparser = VTMLParser ( ) ) : """Look for vt100 markup and render vt opcodes into a VTMLBuffer ."""
if isinstance ( vtmarkup , VTMLBuffer ) : return vtmarkup . plain ( ) if plain else vtmarkup try : vtmlparser . feed ( vtmarkup ) vtmlparser . close ( ) except : if strict : raise buf = VTMLBuffer ( ) buf . append_str ( str ( vtmarkup ) ) return buf else : buf = vtmlparser . getv...
def _set_data ( self , ** kwargs ) : """Sets data from given parameters Old values are deleted . If a paremeter is not given , nothing is changed . Parameters shape : 3 - tuple of Integer \t Grid shape grid : Dict of 3 - tuples to strings \t Cell content attributes : List of 3 - tuples \t Cell att...
if "shape" in kwargs : self . shape = kwargs [ "shape" ] if "grid" in kwargs : self . dict_grid . clear ( ) self . dict_grid . update ( kwargs [ "grid" ] ) if "attributes" in kwargs : self . attributes [ : ] = kwargs [ "attributes" ] if "row_heights" in kwargs : self . row_heights = kwargs [ "row_he...
def table_maker ( subset , ind1 , ind2 , row_labels , col_labels , title ) : """` subset ` provides a subsetted boolean of items to consider . If no subset , you can use all with ` np . ones _ like ( ind1 ) = = 1 ` ` ind1 ` is used to subset rows , e . g . , log2fc > 0 . This is used for rows , so row _ label...
table = [ sum ( subset & ind1 & ind2 ) , sum ( subset & ind1 & ~ ind2 ) , sum ( subset & ~ ind1 & ind2 ) , sum ( subset & ~ ind1 & ~ ind2 ) ] print print title print '-' * len ( title ) print print_2x2_table ( table , row_labels = row_labels , col_labels = col_labels ) print print_row_perc_table ( table , row_labels = ...
def to_str ( string ) : """Return the given string ( either byte string or Unicode string ) converted to native - str , that is , a byte string on Python 2 , or a Unicode string on Python 3. Return ` ` None ` ` if ` ` string ` ` is ` ` None ` ` . : param str string : the string to convert to native - str ...
if string is None : return None if isinstance ( string , str ) : return string if PY2 : return string . encode ( "utf-8" ) return string . decode ( "utf-8" )
def check_node_position ( self , parent_id , position , on_same_branch , db_session = None , * args , ** kwargs ) : """Checks if node position for given parent is valid , raises exception if this is not the case : param parent _ id : : param position : : param on _ same _ branch : indicates that we are chec...
return self . service . check_node_position ( parent_id = parent_id , position = position , on_same_branch = on_same_branch , db_session = db_session , * args , ** kwargs )
def chart_type ( cls , plot ) : """Return the member of : ref : ` XlChartType ` that corresponds to the chart type of * plot * ."""
try : chart_type_method = { 'AreaPlot' : cls . _differentiate_area_chart_type , 'Area3DPlot' : cls . _differentiate_area_3d_chart_type , 'BarPlot' : cls . _differentiate_bar_chart_type , 'BubblePlot' : cls . _differentiate_bubble_chart_type , 'DoughnutPlot' : cls . _differentiate_doughnut_chart_type , 'LinePlot' : ...
def call_cmd ( cmdlist , stdin = None ) : """get a shell commands output , error message and return value and immediately return . . . warning : : This returns with the first screen content for interactive commands . : param cmdlist : shellcommand to call , already splitted into a list accepted by : meth ...
termenc = urwid . util . detected_encoding if isinstance ( stdin , str ) : stdin = stdin . encode ( termenc ) try : logging . debug ( "Calling %s" % cmdlist ) proc = subprocess . Popen ( cmdlist , stdout = subprocess . PIPE , stderr = subprocess . PIPE , stdin = subprocess . PIPE if stdin is not None else N...
def ynnm ( n , m ) : """Initial value for recursion formula"""
a = 1.0 / np . sqrt ( 4.0 * np . pi ) pm = np . abs ( m ) out = 0.0 if ( n < pm ) : out = 0.0 elif ( n == 0 ) : out = a else : out = a for k in xrange ( 1 , n + 1 ) : out *= np . sqrt ( ( 2.0 * k + 1.0 ) / 8.0 / k ) if ( n != pm ) : for k in xrange ( n - 1 , pm - 1 , - 1 ) : ...
def game_events ( game_id , innings_endpoint = False ) : """Return list of Inning objects for game matching the game id . Using ` inning _ endpoints = True ` will result in objects with additional , undocumented data properties , but also objects that may be missing properties expected by the user . ` innin...
data = mlbgame . events . game_events ( game_id , innings_endpoint ) return [ mlbgame . events . Inning ( data [ x ] , x ) for x in data ]
def delete ( self , task_id ) : """Deletes a task from a TaskQueue ."""
if isinstance ( task_id , RegisteredTask ) : task_id = task_id . id def cloud_delete ( api ) : api . delete ( task_id ) if len ( self . _threads ) : self . put ( cloud_delete ) else : cloud_delete ( self . _api ) return self
def _normalize_params ( image , width , height , crop ) : """Normalize params and calculate aspect ."""
if width is None and height is None : raise ValueError ( "Either width or height must be set. Otherwise " "resizing is useless." ) if width is None or height is None : aspect = float ( image . width ) / float ( image . height ) if crop : raise ValueError ( "Cropping the image would be useless since ...
def modifiers ( self ) : """For verb phrases ( VP ) , yields a list of the nearest adjectives and adverbs ."""
if self . _modifiers is None : # Iterate over all the chunks and attach modifiers to their VP - anchor . is_modifier = lambda ch : ch . type in ( "ADJP" , "ADVP" ) and ch . relation is None for chunk in self . sentence . chunks : chunk . _modifiers = [ ] for chunk in filter ( is_modifier , self . se...
def _addModuleInfo ( self , moduleInfo ) : """Adds a line with module info to the editor : param moduleInfo : can either be a string or a module info class . In the first case , an object is instantiated as ImportedModuleInfo ( moduleInfo ) ."""
if is_a_string ( moduleInfo ) : moduleInfo = mi . ImportedModuleInfo ( moduleInfo ) line = "{:15s}: {}" . format ( moduleInfo . name , moduleInfo . verboseVersion ) self . editor . appendPlainText ( line ) QtWidgets . QApplication . instance ( ) . processEvents ( )
def download ( self , url , save_path , header = { } , redownload = False ) : """Currently does not use the proxied driver TODO : Be able to use cookies just like headers is used here : return : the path of the file that was saved"""
if save_path is None : logger . error ( "save_path cannot be None" ) return None # Get headers of current web driver header = self . get_headers ( ) if len ( header ) > 0 : # Add more headers if needed header . update ( header ) logger . debug ( "Download {url} to {save_path}" . format ( url = url , save_pa...
def concretize_load_idx ( self , idx , strategies = None ) : """Concretizes a load index . : param idx : An expression for the index . : param strategies : A list of concretization strategies ( to override the default ) . : param min _ idx : Minimum value for a concretized index ( inclusive ) . : param max ...
if isinstance ( idx , int ) : return [ idx ] elif not self . state . solver . symbolic ( idx ) : return [ self . state . solver . eval ( idx ) ] strategies = self . load_strategies if strategies is None else strategies return self . _apply_concretization_strategies ( idx , strategies , 'load' )
def add_json ( self , json_obj , ** kwargs ) : """Adds a json - serializable Python dict as a json file to IPFS . . . code - block : : python > > > c . add _ json ( { ' one ' : 1 , ' two ' : 2 , ' three ' : 3 } ) ' QmVz9g7m5u3oHiNKHj2CJX1dbG1gtismRS3g9NaPBBLbob ' Parameters json _ obj : dict A json - se...
return self . add_bytes ( encoding . Json ( ) . encode ( json_obj ) , ** kwargs )
def pop ( self ) : """Removes a random element from the collection and returns it # Returns ` object ` > A random object from the collection"""
try : return self . _collection . pop ( ) except KeyError : raise KeyError ( "Nothing left in the {}: '{}'." . format ( type ( self ) . __name__ , self ) ) from None
def to_value_list ( original_strings , corenlp_values = None ) : """Convert a list of strings to a list of Values Args : original _ strings ( list [ basestring ] ) corenlp _ values ( list [ basestring or None ] ) Returns : list [ Value ]"""
assert isinstance ( original_strings , ( list , tuple , set ) ) if corenlp_values is not None : assert isinstance ( corenlp_values , ( list , tuple , set ) ) assert len ( original_strings ) == len ( corenlp_values ) return list ( set ( to_value ( x , y ) for ( x , y ) in zip ( original_strings , corenlp_val...
def rationalize ( flt : float , denominators : Set [ int ] = None ) -> Fraction : """Convert a floating point number to a Fraction with a small denominator . Args : flt : A floating point number denominators : Collection of standard denominators . Default is 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 12 , 1...
if denominators is None : denominators = _DENOMINATORS frac = Fraction . from_float ( flt ) . limit_denominator ( ) if frac . denominator not in denominators : raise ValueError ( 'Cannot rationalize' ) return frac
def get_pandasframe ( self ) : """The method loads data from dataset"""
if self . dataset : self . _load_dimensions ( ) return self . _get_pandasframe_one_dataset ( ) return self . _get_pandasframe_across_datasets ( )
def get_relationship_query_session_for_family ( self , family_id ) : """Gets the ` ` OsidSession ` ` associated with the relationship query service for the given family . arg : family _ id ( osid . id . Id ) : the ` ` Id ` ` of the family return : ( osid . relationship . RelationshipQuerySession ) - a ` ` Rel...
if not self . supports_relationship_query ( ) : raise errors . Unimplemented ( ) # Also include check to see if the catalog Id is found otherwise raise errors . NotFound # pylint : disable = no - member return sessions . RelationshipQuerySession ( family_id , runtime = self . _runtime )
def mouseMoved ( self , viewPos ) : """Updates the probe text with the values under the cursor . Draws a vertical line and a symbol at the position of the probe ."""
try : check_class ( viewPos , QtCore . QPointF ) show_data_point = False # shows the data point as a circle in the cross hair plots self . crossPlotRow , self . crossPlotCol = None , None self . probeLabel . setText ( "<span style='color: #808080'>no data at cursor</span>" ) self . crossLineHori...
def sort ( self , key_or_list , direction = None ) : """Sorts a cursor object based on the input : param key _ or _ list : a list / tuple containing the sort specification , i . e . ( ' user _ number ' : - 1 ) , or a basestring : param direction : sorting direction , 1 or - 1 , needed if key _ or _ list is ...
# checking input format sort_specifier = list ( ) if isinstance ( key_or_list , list ) : if direction is not None : raise ValueError ( 'direction can not be set separately ' 'if sorting by multiple fields.' ) for pair in key_or_list : if not ( isinstance ( pair , list ) or isinstance ( pair , tu...
def Tracer_CMFR_N ( t_seconds , t_bar , C_bar , N ) : """Used by Solver _ CMFR _ N . All inputs and outputs are unitless . This is The model function , f ( x , . . . ) . It takes the independent variable as the first argument and the parameters to fit as separate remaining arguments . : param t _ seconds : Li...
return C_bar * E_CMFR_N ( t_seconds / t_bar , N )
def cpu_speed ( self , silent = False ) : """Retrieves the CPU speed of the target . If the target does not support CPU frequency detection , this function will return ` ` 0 ` ` . Args : self ( JLink ) : the ` ` JLink ` ` instance silent ( bool ) : ` ` True ` ` if the CPU detection should not report error...
res = self . _dll . JLINKARM_MeasureCPUSpeedEx ( - 1 , 1 , int ( silent ) ) if res < 0 : raise errors . JLinkException ( res ) return res
def _generic_matrix_calc ( fn , trees , normalise , min_overlap = 4 , overlap_fail_value = 0 , show_progress = True ) : """( fn , trees , normalise ) Calculates all pairwise distances between trees given in the parameter ' trees ' . Distance functions : eucdist _ matrix geodist _ matrix rfdist _ matrix ...
jobs = itertools . combinations ( trees , 2 ) results = [ ] if show_progress : pbar = setup_progressbar ( 'Calculating tree distances' , 0.5 * len ( trees ) * ( len ( trees ) - 1 ) ) pbar . start ( ) for i , ( t1 , t2 ) in enumerate ( jobs ) : results . append ( _generic_distance_calc ( fn , t1 , t2 , norma...
def name ( self ) : """: return : ( shortest ) Name of this reference - it may contain path components"""
# first two path tokens are can be removed as they are # refs / heads or refs / tags or refs / remotes tokens = self . path . split ( '/' ) if len ( tokens ) < 3 : return self . path # could be refs / HEAD return '/' . join ( tokens [ 2 : ] )
def rotate ( self , nDegrees ) : """rotates the image a given number of degrees Parameters : | nDegrees - the number of degrees you want the image rotated ( images start at zero degrees ) . | Positive numbers are clockwise , negative numbers are counter - clockwise"""
self . angle = self . angle + nDegrees self . _transmogrophy ( self . angle , self . percent , self . scaleFromCenter , self . flipH , self . flipV )
def umount ( self , source ) : """Unmount partion : param source : Full partition path like / dev / sda1"""
args = { 'source' : source , } self . _umount_chk . check ( args ) response = self . _client . raw ( 'disk.umount' , args ) result = response . get ( ) if result . state != 'SUCCESS' : raise RuntimeError ( 'failed to umount partition: %s' % result . stderr )
def _check_uri ( cls , uri ) : """Check whether a URI is compatible with a : class : ` . Driver ` subclass . When called from a subclass , execution simply passes through if the URI scheme is valid for that class . If invalid , a ` ValueError ` is raised . : param uri : URI to check for compatibility : ra...
parsed = urlparse ( uri ) if parsed . scheme != cls . uri_scheme : raise ValueError ( "%s objects require the %r URI scheme" % ( cls . __name__ , cls . uri_scheme ) )
def A_term ( i , r , u , l1 , l2 , PAx , PBx , CPx , gamma ) : """THO eq . 2.18 > > > A _ term ( 0,0,0,0,0,0,0,0,1) 1.0 > > > A _ term ( 0,0,0,0,1,1,1,1,1) 1.0 > > > A _ term ( 1,0,0,0,1,1,1,1,1) -1.0 > > > A _ term ( 0,0,0,1,1,1,1,1,1) 1.0 > > > A _ term ( 1,0,0,1,1,1,1,1,1) -2.0 > > > A _ te...
return pow ( - 1 , i ) * binomial_prefactor ( i , l1 , l2 , PAx , PBx ) * pow ( - 1 , u ) * factorial ( i ) * pow ( CPx , i - 2 * r - 2 * u ) * pow ( 0.25 / gamma , r + u ) / factorial ( r ) / factorial ( u ) / factorial ( i - 2 * r - 2 * u )
def merge ( self , other ) : """Add requirements from ' other ' metadata . rb into this one ."""
if not isinstance ( other , MetadataRb ) : raise TypeError ( "MetadataRb to merge should be a 'MetadataRb' " "instance, not %s." , type ( other ) ) current = self . to_dict ( ) new = other . to_dict ( ) # compare and gather cookbook dependencies meta_writelines = [ '%s\n' % self . depends_statement ( cbn , meta ) f...
def to_vec3 ( self ) : """Convert this vector4 instance into a vector3 instance ."""
vec3 = Vector3 ( ) vec3 . x = self . x vec3 . y = self . y vec3 . z = self . z if self . w != 0 : vec3 /= self . w return vec3
def main ( ) : """Main CLI application ."""
parser = get_parser ( ) argcomplete . autocomplete ( parser , always_complete_options = False ) args = parser . parse_args ( ) setup_logger ( level = args . log_level ) try : if args . config and args . command in ( 'aggregate' , 'show-closed-prs' , 'show-all-prs' ) : run ( args ) else : parser ...
def get ( self ) : """Constructs a TaskActionsContext : returns : twilio . rest . autopilot . v1 . assistant . task . task _ actions . TaskActionsContext : rtype : twilio . rest . autopilot . v1 . assistant . task . task _ actions . TaskActionsContext"""
return TaskActionsContext ( self . _version , assistant_sid = self . _solution [ 'assistant_sid' ] , task_sid = self . _solution [ 'task_sid' ] , )
def _method_scope ( input_layer , name ) : """Creates a nested set of name and id scopes and avoids repeats ."""
global _in_method_scope # pylint : disable = protected - access with input_layer . g . as_default ( ) , scopes . var_and_name_scope ( None if _in_method_scope else input_layer . _scope ) , scopes . var_and_name_scope ( ( name , None ) ) as ( scope , var_scope ) : was_in_method_scope = _in_method_scope yield sco...
def eliminate_nested ( input_tup ) : """Function to eliminate the nested tuple from a given tuple . Examples : > > > eliminate _ nested ( ( 1 , 5 , 7 , ( 4 , 6 ) , 10 ) ) (1 , 5 , 7 , 10) > > > eliminate _ nested ( ( 2 , 6 , 8 , ( 5 , 7 ) , 11 ) ) (2 , 6 , 8 , 11) > > > eliminate _ nested ( ( 3 , 7 , 9 ...
result = ( ) for item in input_tup : if not isinstance ( item , tuple ) : result += ( item , ) return result
def _parse ( self ) : """Given self . resource , split information from the CTS API : return : None"""
self . response = self . resource self . resource = self . resource . xpath ( "//ti:passage/tei:TEI" , namespaces = XPATH_NAMESPACES ) [ 0 ] self . _prev_id , self . _next_id = _SharedMethod . prevnext ( self . response ) if not self . citation . is_set ( ) and len ( self . resource . xpath ( "//ti:citation" , namespac...
def df_drop_duplicates ( df , ignore_key_pattern = "time" ) : """Drop duplicates from dataframe ignore columns with keys containing defined pattern . : param df : : param noinfo _ key _ pattern : : return :"""
keys_to_remove = list_contains ( df . keys ( ) , ignore_key_pattern ) # key _ tf = [ key . find ( noinfo _ key _ pattern ) ! = - 1 for key in df . keys ( ) ] # keys _ to _ remove # remove duplicates ks = copy . copy ( list ( df . keys ( ) ) ) for key in keys_to_remove : ks . remove ( key ) df = df . drop_duplicates...
def _create_extractors ( cls , metrics ) : """Build metrics extractors according to the ` metrics ` config : param metrics : Benchmark ` metrics ` configuration section"""
metrics_dict = { } # group entries by ` category ` attribute ( default is " standard " ) for metric , config in six . iteritems ( metrics ) : category = config . get ( 'category' , StdBenchmark . DEFAULT_CATEGORY ) metrics_dict . setdefault ( category , { } ) [ metric ] = config # create one StdExtractor instan...
def SelectPoint ( ) : """Opens an eDNA point picker , where the user can select a single tag . : return : selected tag name"""
# Define all required variables in the correct ctypes format pszPoint = create_string_buffer ( 20 ) nPoint = c_ushort ( 20 ) # Opens the point picker dna_dll . DnaSelectPoint ( byref ( pszPoint ) , nPoint ) tag_result = pszPoint . value . decode ( 'utf-8' ) return tag_result
def _FormatMessage ( self , event ) : """Formats the message . Args : event ( EventObject ) : event . Returns : str : message field . Raises : NoFormatterFound : if no event formatter can be found to match the data type in the event ."""
message , _ = self . _output_mediator . GetFormattedMessages ( event ) if message is None : data_type = getattr ( event , 'data_type' , 'UNKNOWN' ) raise errors . NoFormatterFound ( 'Unable to find event formatter for: {0:s}.' . format ( data_type ) ) return message
def find_elements ( self , selector , by = By . CSS_SELECTOR , limit = 0 ) : """Returns a list of matching WebElements . If " limit " is set and > 0 , will only return that many elements ."""
self . wait_for_ready_state_complete ( ) if page_utils . is_xpath_selector ( selector ) : by = By . XPATH if page_utils . is_link_text_selector ( selector ) : selector = page_utils . get_link_text_from_selector ( selector ) by = By . LINK_TEXT elements = self . driver . find_elements ( by = by , value = sel...
def get_session ( self , token = None , signature = None ) : '''If provided a ` token ` parameter , tries to retrieve a stored ` rauth . OAuth1Session ` instance . Otherwise generates a new session instance with the : class : ` rauth . OAuth1Service . consumer _ key ` and : class : ` rauth . OAuth1Service . c...
if token is not None : access_token , access_token_secret = token session = self . session_obj ( self . consumer_key , self . consumer_secret , access_token , access_token_secret , signature or self . signature_obj , service = self ) else : # pragma : no cover signature = signature or self . signature_obj ...
def pexpire ( self , key , timeout ) : """This command works exactly like : meth : ` ~ tredis . RedisClient . pexpire ` but the time to live of the key is specified in milliseconds instead of seconds . . . note : : * * Time complexity * * : ` ` O ( 1 ) ` ` : param key : The key to set an expiration for ...
return self . _execute ( [ b'PEXPIRE' , key , ascii ( timeout ) . encode ( 'ascii' ) ] , 1 )
def scope ( self , framebuffer , enable_only = None , * , textures = ( ) , uniform_buffers = ( ) , storage_buffers = ( ) ) -> 'Scope' : '''Create a : py : class : ` Scope ` object . Args : framebuffer ( Framebuffer ) : The framebuffer to use when entering . enable _ only ( int ) : The enable _ only flags to s...
textures = tuple ( ( tex . mglo , idx ) for tex , idx in textures ) uniform_buffers = tuple ( ( buf . mglo , idx ) for buf , idx in uniform_buffers ) storage_buffers = tuple ( ( buf . mglo , idx ) for buf , idx in storage_buffers ) res = Scope . __new__ ( Scope ) res . mglo = self . mglo . scope ( framebuffer . mglo , ...
def session_update ( self , session , * _ ) : """Record the sqlalchemy object states in the middle of session , prepare the events for the final pub in session _ commit ."""
self . _session_init ( session ) session . pending_write |= set ( session . new ) session . pending_update |= set ( session . dirty ) session . pending_delete |= set ( session . deleted ) self . logger . debug ( "%s - session_update" % session . meepo_unique_id )
def find_genusspecific_allele_list ( profiles_file , target_genus ) : """A new way of making our specific databases : Make our profiles file have lists of every gene / allele present for each genus instead of just excluding a few genes for each . This way , should have much smaller databases while managing to m...
alleles = list ( ) with open ( profiles_file ) as f : lines = f . readlines ( ) for line in lines : line = line . rstrip ( ) genus = line . split ( ':' ) [ 0 ] if genus == target_genus : alleles = line . split ( ':' ) [ 1 ] . split ( ',' ) [ : - 1 ] return alleles
def __set_interval ( self , value ) : '''Sets the treatment interval @ param value : Interval'''
if not isinstance ( self , Interval ) : raise ValueError ( "'value' must be of type Interval" ) self . __interval = value
def subject ( self ) : """Normalized subject . Only used for debugging and human - friendly logging ."""
# Fetch subject from first message . subject = self . message . get ( 'Subject' , '' ) subject , _ = re . subn ( r'\s+' , ' ' , subject ) return subject
def get_agents ( self , pool_id , agent_name = None , include_capabilities = None , include_assigned_request = None , include_last_completed_request = None , property_filters = None , demands = None ) : """GetAgents . [ Preview API ] Get a list of agents . : param int pool _ id : The agent pool containing the a...
route_values = { } if pool_id is not None : route_values [ 'poolId' ] = self . _serialize . url ( 'pool_id' , pool_id , 'int' ) query_parameters = { } if agent_name is not None : query_parameters [ 'agentName' ] = self . _serialize . query ( 'agent_name' , agent_name , 'str' ) if include_capabilities is not Non...
def _ParseDateTimeValue ( self , parser_mediator , date_time_value ) : """Parses a date time value . Args : parser _ mediator ( ParserMediator ) : mediates interactions between parsers and other components , such as storage and dfvfs . date _ time _ value ( str ) : date time value ( CSSM _ DB _ ATTRIBUTE ...
if date_time_value [ 14 ] != 'Z' : parser_mediator . ProduceExtractionWarning ( 'invalid date and time value: {0!s}' . format ( date_time_value ) ) return None try : year = int ( date_time_value [ 0 : 4 ] , 10 ) month = int ( date_time_value [ 4 : 6 ] , 10 ) day_of_month = int ( date_time_value [ 6 ...
def guess_headers ( self ) : """Attempt to guess what headers may be required in order to use this type . Returns ` guess _ headers ` of all children recursively . * If the typename is in the : const : ` KNOWN _ TYPES ` dictionary , use the header specified there * If it ' s an STL type , include < { type }...
name = self . name . replace ( "*" , "" ) headers = [ ] if name in KNOWN_TYPES : headers . append ( KNOWN_TYPES [ name ] ) elif name in STL : headers . append ( '<{0}>' . format ( name ) ) elif hasattr ( ROOT , name ) and name . startswith ( "T" ) : headers . append ( '<{0}.h>' . format ( name ) ) elif '::'...
def cleanup_classes ( rdf ) : """Remove unnecessary class definitions : definitions of SKOS classes or unused classes . If a class is also a skos : Concept or skos : Collection , remove the ' classness ' of it but leave the Concept / Collection ."""
for t in ( OWL . Class , RDFS . Class ) : for cl in rdf . subjects ( RDF . type , t ) : # SKOS classes may be safely removed if cl . startswith ( SKOS ) : logging . debug ( "removing SKOS class definition: %s" , cl ) replace_subject ( rdf , cl , None ) continue # ...
def eval_agg_call ( self , exp ) : "helper for eval _ callx ; evaluator for CallX that consume multiple rows"
if not isinstance ( self . c_row , list ) : raise TypeError ( 'aggregate function expected a list of rows' ) if len ( exp . args . children ) != 1 : raise ValueError ( 'aggregate function expected a single value' , exp . args ) arg , = exp . args . children # intentional : error if len ! = 1 vals = [ Evaluator ...
def _get_coordinatenames ( self ) : """Create ordered list of coordinate names"""
validnames = ( "direction" , "spectral" , "linear" , "stokes" , "tabular" ) self . _names = [ "" ] * len ( validnames ) n = 0 for key in self . _csys . keys ( ) : for name in validnames : if key . startswith ( name ) : idx = int ( key [ len ( name ) : ] ) self . _names [ idx ] = name...
def _downgrade_v3 ( op ) : """Downgrade assets db by adding a not null constraint on ` ` equities . first _ traded ` `"""
op . create_table ( '_new_equities' , sa . Column ( 'sid' , sa . Integer , unique = True , nullable = False , primary_key = True , ) , sa . Column ( 'symbol' , sa . Text ) , sa . Column ( 'company_symbol' , sa . Text ) , sa . Column ( 'share_class_symbol' , sa . Text ) , sa . Column ( 'fuzzy_symbol' , sa . Text ) , sa ...
def update_payload ( self , fields = None ) : """Wrap submitted data within an extra dict ."""
payload = super ( JobTemplate , self ) . update_payload ( fields ) effective_user = payload . pop ( u'effective_user' , None ) if effective_user : payload [ u'ssh' ] = { u'effective_user' : effective_user } return { u'job_template' : payload }
def get_schema ( self , schema_id ) : """Retrieves the schema with the given schema _ id from the registry and returns it as a ` dict ` ."""
res = requests . get ( self . _url ( '/schemas/ids/{}' , schema_id ) ) raise_if_failed ( res ) return json . loads ( res . json ( ) [ 'schema' ] )
def delete ( login ) : '''Delete user account login : string login name CLI Example : . . code - block : : bash salt ' * ' pdbedit . delete wash'''
if login in list_users ( False ) : res = __salt__ [ 'cmd.run_all' ] ( 'pdbedit --delete {login}' . format ( login = _quote_args ( login ) ) , ) if res [ 'retcode' ] > 0 : return { login : res [ 'stderr' ] if 'stderr' in res else res [ 'stdout' ] } return { login : 'deleted' } return { login : 'absen...
def aaa_config_aaa_authentication_login_first ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) aaa_config = ET . SubElement ( config , "aaa-config" , xmlns = "urn:brocade.com:mgmt:brocade-aaa" ) aaa = ET . SubElement ( aaa_config , "aaa" ) authentication = ET . SubElement ( aaa , "authentication" ) login = ET . SubElement ( authentication , "login" ) first = ET . SubElement ( l...
def stats ( path , hash_type = 'sha256' , follow_symlinks = True ) : '''Return a dict containing the stats about a given file Under Windows , ` gid ` will equal ` uid ` and ` group ` will equal ` user ` . While a file in Windows does have a ' primary group ' , this rarely used attribute generally has no beari...
# This is to mirror the behavior of file . py . ` check _ file _ meta ` expects an # empty dictionary when the file does not exist if not os . path . exists ( path ) : raise CommandExecutionError ( 'Path not found: {0}' . format ( path ) ) if follow_symlinks and sys . getwindowsversion ( ) . major >= 6 : path =...
def _add_arguments ( self ) : """Adds arguments to parser ."""
self . _parser . add_argument ( '-v' , '--version' , action = 'store_true' , help = "show program's version number and exit" ) self . _parser . add_argument ( '-a' , '--alias' , nargs = '?' , const = get_alias ( ) , help = '[custom-alias-name] prints alias for current shell' ) self . _parser . add_argument ( '-l' , '--...
def copy_files_to ( src_fpath_list , dst_dpath = None , dst_fpath_list = None , overwrite = False , verbose = True , veryverbose = False ) : """parallel copier Example : > > > # DISABLE _ DOCTEST > > > from utool . util _ path import * > > > import utool as ut > > > overwrite = False > > > veryverbose =...
from utool import util_list from utool import util_parallel if verbose : print ( '[util_path] +--- COPYING FILES ---' ) print ( '[util_path] * len(src_fpath_list) = %r' % ( len ( src_fpath_list ) ) ) print ( '[util_path] * dst_dpath = %r' % ( dst_dpath , ) ) if dst_fpath_list is None : ensuredir ( dst...
def credential_delete_simulate ( self , * ids ) : """Show the relationships and dependencies for one or more credentials . : param ids : one or more credential ids"""
return self . raw_query ( "credential" , "deleteSimulate" , data = { "credentials" : [ { "id" : str ( id ) } for id in ids ] } )
def receive_pong ( self , pong : Pong ) : """Handles a Pong message ."""
message_id = ( 'ping' , pong . nonce , pong . sender ) async_result = self . messageids_to_asyncresults . get ( message_id ) if async_result is not None : self . log_healthcheck . debug ( 'Pong received' , sender = pex ( pong . sender ) , message_id = pong . nonce , ) async_result . set ( True ) else : self...
def get_all_comments ( chebi_ids ) : '''Returns all comments'''
all_comments = [ get_comments ( chebi_id ) for chebi_id in chebi_ids ] return [ x for sublist in all_comments for x in sublist ]
def change_vlan_id ( self , original , new ) : """Change VLAN ID for a single VLAN , cluster VLAN or inline interface . When changing a single or cluster FW vlan , you can specify the original VLAN and new VLAN as either single int or str value . If modifying an inline interface VLAN when the interface pair...
vlan = self . vlan_interface . get_vlan ( original ) newvlan = str ( new ) . split ( '-' ) splitted = vlan . interface_id . split ( '.' ) vlan . interface_id = '{}.{}' . format ( splitted [ 0 ] , newvlan [ 0 ] ) for interface in vlan . interfaces : if isinstance ( interface , InlineInterface ) : interface ....
def _site_login ( self , repo ) : """Logs the user specified in the repo into the wiki . : arg repo : an instance of config . RepositorySettings with wiki credentials ."""
try : if not self . testmode : self . site . login ( repo . wiki [ "user" ] , repo . wiki [ "password" ] ) except LoginError as e : print ( e [ 1 ] [ 'result' ] ) self . basepage = repo . wiki [ "basepage" ]
def markowitz_portfolio ( cov_mat , exp_rets , target_ret , allow_short = False , market_neutral = False ) : """Computes a Markowitz portfolio . Parameters cov _ mat : pandas . DataFrame Covariance matrix of asset returns . exp _ rets : pandas . Series Expected asset returns ( often historical returns ) ....
if not isinstance ( cov_mat , pd . DataFrame ) : raise ValueError ( "Covariance matrix is not a DataFrame" ) if not isinstance ( exp_rets , pd . Series ) : raise ValueError ( "Expected returns is not a Series" ) if not isinstance ( target_ret , float ) : raise ValueError ( "Target return is not a float" ) i...
def _add_rhoa ( df , spacing ) : """a simple wrapper to compute K factors and add rhoa"""
df [ 'k' ] = redaK . compute_K_analytical ( df , spacing = spacing ) df [ 'rho_a' ] = df [ 'r' ] * df [ 'k' ] if 'Zt' in df . columns : df [ 'rho_a_complex' ] = df [ 'Zt' ] * df [ 'k' ] return df
def get_split_pos_lines ( data , cgi_input , header ) : """Advance across split alleles and return data from each . CGI var file reports alleles separately for heterozygous sites : all variant or reference information is called for the first allele , then for the second . This function moves forward in the fi...
s1_data = [ data ] s2_data = [ ] next_data = cgi_input . readline ( ) . decode ( 'utf-8' ) . rstrip ( '\n' ) . split ( "\t" ) while next_data [ header [ 'allele' ] ] == "1" : s1_data . append ( next_data ) next_data = cgi_input . readline ( ) . decode ( 'utf-8' ) . rstrip ( '\n' ) . split ( "\t" ) while next_da...
def merge_lists ( src , new ) : """Update a value list with a list of new or updated values ."""
l_min , l_max = ( src , new ) if len ( src ) < len ( new ) else ( new , src ) l_min . extend ( None for i in range ( len ( l_min ) , len ( l_max ) ) ) for i , val in enumerate ( new ) : if isinstance ( val , dict ) and isinstance ( src [ i ] , dict ) : new [ i ] = merge_dicts ( src [ i ] , val ) elif is...
def _remove_advices ( target , advices , ctx ) : """Remove advices from input target . : param advices : advices to remove . If None , remove all advices ."""
# if ctx is not None if ctx is not None : # check if intercepted ctx is ctx _ , intercepted_ctx = get_intercepted ( target ) if intercepted_ctx is None or intercepted_ctx is not ctx : return interception_fn = _get_function ( target ) target_advices = getattr ( interception_fn , _ADVICES , None ) if targ...
def generic_html ( self , result , errors ) : """Try to display any object in sensible HTML ."""
h1 = htmlize ( type ( result ) ) out = [ ] result = pre_process_json ( result ) if not hasattr ( result , 'items' ) : # result is a non - container header = "<tr><th>Value</th></tr>" if type ( result ) is list : result = htmlize_list ( result ) else : result = htmlize ( result ) out = [ ...
def get_doctypes ( self , default_doctypes = DEFAULT_DOCTYPES ) : """Returns the list of doctypes to use ."""
for action , value in reversed ( self . steps ) : if action == 'doctypes' : return list ( value ) if self . type is not None : return [ self . type . get_mapping_type_name ( ) ] return default_doctypes
def triples_to_graph ( self , triples , top = None ) : """Create a Graph from * triples * considering codec configuration . The Graph class does not know about information in the codec , so if Graph instantiation depends on special ` TYPE _ REL ` or ` TOP _ VAR ` values , use this function instead of instanti...
inferred_top = triples [ 0 ] [ 0 ] if triples else None ts = [ ] for triple in triples : if triple [ 0 ] == self . TOP_VAR and triple [ 1 ] == self . TOP_REL : inferred_top = triple [ 2 ] else : ts . append ( self . handle_triple ( * triple ) ) top = self . handle_triple ( self . TOP_VAR , self ...
def get_device_topology ( self , id_or_uri ) : """Retrieves the topology information for the rack resource specified by ID or URI . Args : id _ or _ uri : Can be either the resource ID or the resource URI . Return : dict : Device topology ."""
uri = self . _client . build_uri ( id_or_uri ) + "/deviceTopology" return self . _client . get ( uri )
def get_json ( self , instance = True ) : '''get _ json High - level api : get _ json returns json _ val of the config node . Parameters instance : ` bool ` True if only one instance of list or leaf - list is required . False if all instances of list or leaf - list are needed . Returns str A string ...
def get_json_instance ( node ) : pk = Parker ( xml_fromstring = _fromstring , dict_type = OrderedDict ) default_ns = { } nodes = [ node ] + node . findall ( './/' ) for item in nodes : parents = [ p for p in node . findall ( './/{}/..' . format ( item . tag ) ) if item in p . findall ( '*' ) ] ...
def _extract ( self , raw : str , station : str = None ) -> str : """Extracts the raw _ report element from XML response"""
resp = parsexml ( raw ) try : report = resp [ 'response' ] [ 'data' ] [ self . rtype . upper ( ) ] except KeyError : raise self . make_err ( raw ) # Find report string if isinstance ( report , dict ) : report = report [ 'raw_text' ] elif isinstance ( report , list ) and report : report = report [ 0 ] [ ...
def get ( self , sid ) : """Constructs a DeploymentContext : param sid : A string that uniquely identifies the Deployment . : returns : twilio . rest . preview . deployed _ devices . fleet . deployment . DeploymentContext : rtype : twilio . rest . preview . deployed _ devices . fleet . deployment . Deployment...
return DeploymentContext ( self . _version , fleet_sid = self . _solution [ 'fleet_sid' ] , sid = sid , )
def _prepare_connection ( ** kwargs ) : '''Prepare the connection with the remote network device , and clean up the key value pairs , removing the args used for the connection init .'''
pyeapi_kwargs = __salt__ [ 'config.get' ] ( 'pyeapi' , { } ) pyeapi_kwargs . update ( kwargs ) # merge the CLI args with the opts / pillar init_kwargs , fun_kwargs = __utils__ [ 'args.prepare_kwargs' ] ( pyeapi_kwargs , PYEAPI_INIT_KWARGS ) if 'transport' not in init_kwargs : init_kwargs [ 'transport' ] = 'https' c...
def tar_to_bigfile ( self , fname , outfile ) : """Convert tar of multiple FASTAs to one file ."""
fnames = [ ] tmpdir = mkdtemp ( ) # Extract files to temporary directory with tarfile . open ( fname ) as tar : tar . extractall ( path = tmpdir ) for root , _ , files in os . walk ( tmpdir ) : fnames += [ os . path . join ( root , fname ) for fname in files ] # Concatenate with open ( outfile , "w" ) as out : ...
def get_container_name ( self , repo : str , branch : str , git_repo : Repo ) : """Returns the name of the container used for the repo ."""
return "arca_{}_{}_{}" . format ( self . _arca . repo_id ( repo ) , branch , self . _arca . current_git_hash ( repo , branch , git_repo , short = True ) )
def modify_key_parity ( key ) : """The prior use of the function is to return the parity - validated key . The incoming key is expected to be hex data binary representation , e . g . b ' E7A3C8B1'"""
validated_key = b'' for byte in key : if parityOf ( int ( byte ) ) == - 1 : byte_candidate = int ( byte ) + 1 while parityOf ( byte_candidate ) == - 1 : byte_candidate = divmod ( byte_candidate + 1 , 256 ) [ 1 ] validated_key += bytes ( [ byte_candidate ] ) else : val...
def track_from_url ( url , timeout = DEFAULT_ASYNC_TIMEOUT ) : """Create a track object from a public http URL . NOTE : Does not create the detailed analysis for the Track . Call Track . get _ analysis ( ) for that . Args : url : A string giving the URL to read from . This must be on a public machine access...
param_dict = dict ( url = url ) return _upload ( param_dict , timeout , data = None )
def create ( cls , object_type = None , object_uuid = None , ** kwargs ) : """Create a new record identifier . : param object _ type : The object type . ( Default : ` ` None ` ` ) : param object _ uuid : The object UUID . ( Default : ` ` None ` ` )"""
assert 'pid_value' in kwargs kwargs . setdefault ( 'status' , cls . default_status ) if object_type and object_uuid : kwargs [ 'status' ] = PIDStatus . REGISTERED return super ( OAIIDProvider , cls ) . create ( object_type = object_type , object_uuid = object_uuid , ** kwargs )
def set_hostname ( hostname ) : '''Set the hostname of the windows minion , requires a restart before this will be updated . . . versionadded : : 2016.3.0 Args : hostname ( str ) : The hostname to set Returns : bool : ` ` True ` ` if successful , otherwise ` ` False ` ` CLI Example : . . code - bloc...
with salt . utils . winapi . Com ( ) : conn = wmi . WMI ( ) comp = conn . Win32_ComputerSystem ( ) [ 0 ] return comp . Rename ( Name = hostname )
def filter ( self , func ) : """Create a Catalog of a subset of entries based on a condition Note that , whatever specific class this is performed on , the return instance is a Catalog . The entries are passed unmodified , so they will still reference the original catalog instance and include its details su...
return Catalog . from_dict ( { key : entry for key , entry in self . items ( ) if func ( entry ) } )
def to_tess ( obj ) : '''to _ tess ( obj ) yields a Tesselation object that is equivalent to obj ; if obj is a tesselation object already and no changes are requested ( see options ) then obj is returned unmolested . The following objects can be converted into tesselations : * a tesselation object * a mesh ...
if is_tess ( obj ) : return obj elif is_mesh ( obj ) : return obj . tess elif is_topo ( obj ) : return obj . tess else : # couple things to try : ( 1 ) might specify a tess face matrix , ( 2 ) might be a mesh - like obj try : return tess ( obj ) except Exception : pass try : ...
def _encode_ndef_uri_type ( self , data ) : """Implement NDEF URI Identifier Code . This is a small hack to replace some well known prefixes ( such as http : / / ) with a one byte code . If the prefix is not known , 0x00 is used ."""
t = 0x0 for ( code , prefix ) in uri_identifiers : if data [ : len ( prefix ) ] . decode ( 'latin-1' ) . lower ( ) == prefix : t = code data = data [ len ( prefix ) : ] break data = yubico_util . chr_byte ( t ) + data return data
def organization_membership_delete ( self , id , ** kwargs ) : "https : / / developer . zendesk . com / rest _ api / docs / core / organization _ memberships # delete - membership"
api_path = "/api/v2/organization_memberships/{id}.json" api_path = api_path . format ( id = id ) return self . call ( api_path , method = "DELETE" , ** kwargs )
def remove_na ( x , y = None , paired = False , axis = 'rows' ) : """Remove missing values along a given axis in one or more ( paired ) numpy arrays . Parameters x , y : 1D or 2D arrays Data . ` ` x ` ` and ` ` y ` ` must have the same number of dimensions . ` ` y ` ` can be None to only remove missing va...
# Safety checks x = np . asarray ( x ) assert x . size > 1 , 'x must have more than one element.' assert axis in [ 'rows' , 'columns' ] , 'axis must be rows or columns.' if y is None : return _remove_na_single ( x , axis = axis ) elif isinstance ( y , ( int , float , str ) ) : return _remove_na_single ( x , axi...