signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def choice ( self , index : Index , choices : Array , p : Array = None , additional_key : Any = None ) -> pd . Series : """Decides between a weighted or unweighted set of choices . Given a a set of choices with or without corresponding weights , returns an indexed set of decisions from those choices . This is ...
return choice ( self . _key ( additional_key ) , index , choices , p , self . index_map )
def address_exclude ( self , other ) : """Remove an address from a larger block . For example : addr1 = ip _ network ( ' 192.0.2.0/28 ' ) addr2 = ip _ network ( ' 192.0.2.1/32 ' ) list ( addr1 . address _ exclude ( addr2 ) ) = [ IPv4Network ( ' 192.0.2.0/32 ' ) , IPv4Network ( ' 192.0.2.2/31 ' ) , IPv4N...
if not self . _version == other . _version : raise TypeError ( "%s and %s are not of the same version" % ( self , other ) ) if not isinstance ( other , _BaseNetwork ) : raise TypeError ( "%s is not a network object" % other ) if not other . subnet_of ( self ) : raise ValueError ( '%s not contained in %s' % ...
def open_jar ( self , path , overwrite = False , compressed = True , jar_rules = None ) : """Yields a Jar that will be written when the context exits . : API : public : param string path : the path to the jar file : param bool overwrite : overwrite the file at ` ` path ` ` if it exists ; ` ` False ` ` by defa...
jar = Jar ( path ) try : yield jar except jar . Error as e : raise TaskError ( 'Failed to write to jar at {}: {}' . format ( path , e ) ) with jar . _render_jar_tool_args ( self . get_options ( ) ) as args : if args : # Don ' t build an empty jar args . append ( '-update={}' . format ( self . _flag ...
def send_config_set ( self , config_commands = None , exit_config_mode = False , delay_factor = 1 , max_loops = 150 , strip_prompt = False , strip_command = False , config_mode_command = None , ) : """Remain in configuration mode ."""
return super ( VyOSSSH , self ) . send_config_set ( config_commands = config_commands , exit_config_mode = exit_config_mode , delay_factor = delay_factor , max_loops = max_loops , strip_prompt = strip_prompt , strip_command = strip_command , config_mode_command = config_mode_command , )
def loadThingObjects ( numCorticalColumns = 1 , objDataPath = './data/' ) : """Load simulated sensation data on a number of different objects There is one file per object , each row contains one feature , location pairs The format is as follows [ ( - 33.6705 , 75.5003 , 2.4207 ) / 10 ] = > [ [ list of active ...
# create empty simple object machine objects = createObjectMachine ( machineType = "simple" , numInputBits = 20 , sensorInputSize = 1024 , externalInputSize = 1024 , numCorticalColumns = numCorticalColumns , numFeatures = 0 , numLocations = 0 , ) for _ in range ( numCorticalColumns ) : objects . locations . append ...
def draw ( self , mode , selection ) : """Draw program in given mode , with given selection ( IndexBuffer or first , count ) ."""
if not self . _linked : raise RuntimeError ( 'Cannot draw program if code has not been set' ) # Init gl . check_error ( 'Check before draw' ) mode = as_enum ( mode ) # Draw if len ( selection ) == 3 : # Selection based on indices id_ , gtype , count = selection if count : self . _pre_draw ( ) ...
def walk_json ( d , func ) : """Walk over a parsed JSON nested structure ` d ` , apply ` func ` to each leaf element and replace it with result"""
if isinstance ( d , Mapping ) : return OrderedDict ( ( k , walk_json ( v , func ) ) for k , v in d . items ( ) ) elif isinstance ( d , list ) : return [ walk_json ( v , func ) for v in d ] else : return func ( d )
def remnant_mass_ulim ( eta , ns_g_mass , bh_spin_z , ns_sequence , max_ns_g_mass , shift ) : """Function that determines the maximum remnant disk mass for an NS - BH system with given symmetric mass ratio , NS mass , and BH spin parameter component along the orbital angular momentum . This is a wrapper to ...
# Sanity checks if not ( eta > 0. and eta <= 0.25 and abs ( bh_spin_z ) <= 1 ) : raise Exception ( """The absolute value of the BH spin z-component must be <=1. Eta must be between 0 and 0.25. The function remnant_mass_ulim was launched with eta={0} and chi_z={1}. Unphysical paramet...
def get_cmd ( self ) : """If self . config . cmd is not None , return that . Otherwise , read the Procfile inside the build code , parse it ( as yaml ) , and pull out the command for self . config . proc _ name ."""
if self . config . cmd is not None : return self . config . cmd procfile_path = os . path . join ( get_app_path ( self . config ) , 'Procfile' ) with open ( procfile_path , 'r' ) as f : procs = yaml . safe_load ( f ) return procs [ self . config . proc_name ]
def _collection_names_result ( self , callback , results , error = None ) : """callback to for collection names query , filters out collection names"""
names = [ r [ 'name' ] for r in results if r [ 'name' ] . count ( '.' ) == 1 ] assert error == None , repr ( error ) strip = len ( self . _pool . _dbname ) + 1 callback ( [ name [ strip : ] for name in names ] )
def check_even ( num ) : """This Python function checks if a number is even or not using bitwise operators . Args : num : The input integer number to check for evenness . Returns : A boolean value . True if the number is even , False if it ' s not . Examples : > > > check _ even ( 1) False > > > che...
return True if ( ( num ^ 1 ) == ( num + 1 ) ) else False
def _extract_median ( image , mask = slice ( None ) , size = 1 , voxelspacing = None ) : """Internal , single - image version of ` median ` ."""
# set voxel spacing if voxelspacing is None : voxelspacing = [ 1. ] * image . ndim # determine structure element size in voxel units size = _create_structure_array ( size , voxelspacing ) return _extract_intensities ( median_filter ( image , size ) , mask )
def radius_of_gyration ( coords , periodic ) : '''Calculate the square root of the mean distance squared from the center of gravity .'''
gc = geometric_center ( coords , periodic ) return ( periodic_distance ( coords , gc , periodic ) ** 2 ) . sum ( ) / len ( coords )
def IsHFS ( self ) : """Determines if the file system is HFS , HFS + or HFSX . Returns : bool : True if the file system is HFS ."""
tsk_fs_type = self . GetFsType ( ) return tsk_fs_type in [ pytsk3 . TSK_FS_TYPE_HFS , pytsk3 . TSK_FS_TYPE_HFS_DETECT ]
def read_data ( self , scaling_factor = 1E-9 , strain_headers = None ) : '''Reads the data from the csv file : param float scaling _ factor : Scaling factor used for all strain values ( default 1E - 9 for nanostrain ) : param list strain _ headers : List of the variables in the file that correspond to str...
if strain_headers : self . strain . data_variables = strain_headers else : self . strain . data_variables = STRAIN_VARIABLES datafile = open ( self . filename , 'r' ) reader = csv . DictReader ( datafile ) self . strain . data = dict ( [ ( name , [ ] ) for name in reader . fieldnames ] ) for row in reader : ...
def apply_filter ( self , criteria ) : """Apply the given filter criteria on the given column . : param str criteria : the criteria to apply criteria example : " color " : " string " , " criterion1 " : " string " , " criterion2 " : " string " , " dynamicCriteria " : " string " , " filterOn " : " strin...
url = self . build_url ( self . _endpoints . get ( 'apply_filter' ) ) return bool ( self . session . post ( url , data = { 'criteria' : criteria } ) )
def count_leaves ( x ) : """Return the number of non - sequence items in a given recursive sequence ."""
if hasattr ( x , 'keys' ) : x = list ( x . values ( ) ) if hasattr ( x , '__getitem__' ) : return sum ( map ( count_leaves , x ) ) return 1
def set_vnic_connectivity_status ( nic_spec , to_connect ) : """sets the device spec as connected or disconnected : param nic _ spec : the specification : param to _ connect : bool"""
nic_spec . device . connectable = vim . vm . device . VirtualDevice . ConnectInfo ( ) nic_spec . device . connectable . connected = to_connect nic_spec . device . connectable . startConnected = to_connect
def _choose_split_points ( cls , sorted_keys , shard_count ) : """Returns the best split points given a random set of datastore . Keys ."""
assert len ( sorted_keys ) >= shard_count index_stride = len ( sorted_keys ) / float ( shard_count ) return [ sorted_keys [ int ( round ( index_stride * i ) ) ] for i in range ( 1 , shard_count ) ]
def show ( self , m_a ) : """Display ( with a pretty print ) this object : param m _ a : : class : ` MethodAnalysis ` object"""
bytecode . PrettyShow ( m_a , m_a . basic_blocks . gets ( ) , self . notes ) bytecode . PrettyShowEx ( m_a . exceptions . gets ( ) )
def create ( self , create_missing = None ) : """Do extra work to fetch a complete set of attributes for this entity . For more information , see ` Bugzilla # 1381129 < https : / / bugzilla . redhat . com / show _ bug . cgi ? id = 1381129 > ` _ ."""
return type ( self ) ( self . _server_config , id = self . create_json ( create_missing ) [ 'id' ] , ) . read ( )
def tensor_layout ( self , tensor_shape , mesh_shape ) : """Computes TensorLayout given a Tensor Shape and a Mesh Shape . Args : tensor _ shape : Shape . mesh _ shape : Shape . Returns : TensorLayout . Raises : ValueError : If two Tensor Dimensions map to the same Mesh Dimensions ."""
ret = [ self . tensor_dimension_to_mesh_axis ( d , mesh_shape ) for d in tensor_shape ] not_nones = [ a for a in ret if a is not None ] if len ( not_nones ) != len ( set ( not_nones ) ) : raise ValueError ( "Two Tensor Dimensions may not map to the same Mesh Dimension:" " layout=%s tensor_shape=%s mesh_shape=%s " %...
def _backward_sampling_ON2 ( self , M , idx ) : """O ( N ^ 2 ) version of backward sampling . not meant to be called directly , see backward _ sampling"""
for m in range ( M ) : for t in reversed ( range ( self . T - 1 ) ) : lwm = ( self . wgt [ t ] . lw + self . model . logpt ( t + 1 , self . X [ t ] , self . X [ t + 1 ] [ idx [ t + 1 , m ] ] ) ) idx [ t , m ] = rs . multinomial_once ( rs . exp_and_normalise ( lwm ) )
def parameterized_send ( self , request , parameter_list ) : """Send batched requests for a list of parameters Args : request ( str ) : Request to send , like " % s . * ? \n " parameter _ list ( list ) : parameters to format with , like [ " TTLIN " , " TTLOUT " ] Returns : dict : { parameter : response ...
response_queues = OrderedDict ( ) for parameter in parameter_list : response_queues [ parameter ] = self . send ( request % parameter ) return response_queues
def geocode ( self , query , exactly_one = True , timeout = DEFAULT_SENTINEL , limit = None , typeahead = False , language = None , ) : """Return a location point by address . : param str query : The address or query you wish to geocode . : param bool exactly _ one : Return one result or a list of results , if ...
query = self . format_string % query params = self . _geocode_params ( query ) params [ 'typeahead' ] = self . _boolean_value ( typeahead ) if limit : params [ 'limit' ] = str ( int ( limit ) ) if exactly_one : params [ 'limit' ] = '1' if language : params [ 'language' ] = language quoted_query = quote ( qu...
def run_model ( t_output_every , output_dir = None , m = None , force_resume = True , ** iterate_args ) : """Convenience function to combine making a Runner object , and running it for some time . Parameters m : Model Model to run . iterate _ args : Arguments to pass to : meth : ` Runner . iterate ` . ...
r = runner . Runner ( output_dir , m , force_resume ) print ( r ) r . iterate ( t_output_every = t_output_every , ** iterate_args ) return r
def merge ( self ) : """Perform merge of head and update starting from root ."""
if isinstance ( self . head , dict ) and isinstance ( self . update , dict ) : if not isinstance ( self . root , dict ) : self . root = { } self . _merge_dicts ( ) else : self . _merge_base_values ( ) if self . conflict_set : raise MergeError ( 'Dictdiffer Errors' , self . conflicts )
def get_failing_line ( xml_string , exc_msg ) : """Extract the failing line from the XML string , as indicated by the line / column information in the exception message . Returns a tuple ( lineno , colno , new _ pos , line ) , where lineno and colno and marker _ pos may be None ."""
max_before = 500 # max characters before reported position max_after = 500 # max characters after reported position max_unknown = 1000 # max characters when position cannot be determined assert isinstance ( xml_string , six . binary_type ) m = re . search ( r':(\d+):(\d+):' , exc_msg ) if not m : xml_string , _ = t...
def node_insert_after ( self , node , new_node ) : """Insert the new node after node ."""
assert ( not self . node_is_on_list ( new_node ) ) assert ( node is not new_node ) next = self . node_next ( node ) assert ( next is not None ) self . node_set_next ( node , new_node ) self . node_set_prev ( new_node , node ) self . node_set_next ( new_node , next ) self . node_set_prev ( next , new_node )
def interpolate_string ( self , testString , section ) : """Take a string and replace all example of ExtendedInterpolation formatting within the string with the exact value . For values like $ { example } this is replaced with the value that corresponds to the option called example * * * in the same section *...
# First check if any interpolation is needed and abort if not reObj = re . search ( r"\$\{.*?\}" , testString ) while reObj : # Not really sure how this works , but this will obtain the first # instance of a string contained within $ { . . . . } repString = ( reObj ) . group ( 0 ) [ 2 : - 1 ] # Need to test whi...
def unlink ( self , request , uuid = None ) : """Unlink all related resources , service project link and service itself ."""
service = self . get_object ( ) service . unlink_descendants ( ) self . perform_destroy ( service ) return Response ( status = status . HTTP_204_NO_CONTENT )
def get_update_service ( self ) : """Return a HPEUpdateService object : returns : The UpdateService object"""
update_service_url = utils . get_subresource_path_by ( self , 'UpdateService' ) return ( update_service . HPEUpdateService ( self . _conn , update_service_url , redfish_version = self . redfish_version ) )
def get ( cls , database , conditions = "" ) : """Get all data from system . parts table : param database : A database object to fetch data from . : param conditions : WHERE clause conditions . Database condition is added automatically : return : A list of SystemPart objects"""
assert isinstance ( database , Database ) , "database must be database.Database class instance" assert isinstance ( conditions , string_types ) , "conditions must be a string" if conditions : conditions += " AND" field_names = ',' . join ( cls . fields ( ) ) return database . select ( "SELECT %s FROM %s WHERE %s da...
def list_settings ( self ) : """Get list of all appropriate settings and their default values ."""
result = super ( ) . list_settings ( ) result . append ( ( self . SETTING_TEXT_HIGHLIGHT , None ) ) return result
def download ( self , itemID , savePath ) : """downloads an item to local disk Inputs : itemID - unique id of item to download savePath - folder to save the file in"""
if os . path . isdir ( savePath ) == False : os . makedirs ( savePath ) url = self . _url + "/%s/download" % itemID params = { } if len ( params . keys ( ) ) : url = url + "?%s" % urlencode ( params ) return self . _get ( url = url , param_dict = params , out_folder = savePath , securityHandler = self . _securi...
def close ( self , clear = True ) : """Closes the editor , stops the backend and removes any installed mode / panel . This is also where we cache the cursor position . : param clear : True to clear the editor content before closing ."""
if self . _tooltips_runner : self . _tooltips_runner . cancel_requests ( ) self . _tooltips_runner = None self . decorations . clear ( ) self . modes . clear ( ) self . panels . clear ( ) self . backend . stop ( ) Cache ( ) . set_cursor_position ( self . file . path , self . textCursor ( ) . position ( ) ) supe...
def get_traffic ( self , subreddit ) : """Return the json dictionary containing traffic stats for a subreddit . : param subreddit : The subreddit whose / about / traffic page we will collect ."""
url = self . config [ 'subreddit_traffic' ] . format ( subreddit = six . text_type ( subreddit ) ) return self . request_json ( url )
def master_then_spare ( data ) : """Return the provided satellites list sorted as : - alive first , - then spare - then dead satellites . : param data : the SatelliteLink list : type data : list : return : sorted list : rtype : list"""
master = [ ] spare = [ ] for sdata in data : if sdata . spare : spare . append ( sdata ) else : master . append ( sdata ) rdata = [ ] rdata . extend ( master ) rdata . extend ( spare ) return rdata
def get_cart_coords ( self ) : """Return the cartesian coordinates of the molecule"""
def to_s ( x ) : return "%0.6f" % x outs = [ ] for i , site in enumerate ( self . _mol ) : outs . append ( " " . join ( [ site . species_string , " " . join ( [ to_s ( j ) for j in site . coords ] ) ] ) ) return "\n" . join ( outs )
def policy_net ( rng_key , batch_observations_shape , num_actions , bottom_layers = None ) : """A policy net function ."""
# Use the bottom _ layers as the bottom part of the network and just add the # required layers on top of it . if bottom_layers is None : bottom_layers = [ ] # NOTE : The LogSoftmax instead of the Softmax . bottom_layers . extend ( [ layers . Dense ( num_actions ) , layers . LogSoftmax ( ) ] ) net = layers . Serial ...
def set_title ( self , title = None ) : """This method is used to change an entry title . A new title string is needed ."""
if title is None or type ( title ) is not str : raise KPError ( "Need a new title." ) else : self . title = title self . last_mod = datetime . now ( ) . replace ( microsecond = 0 ) return True
def int_global_to_local_start ( self , index , axis = 0 ) : """Calculate local index from global index from start _ index : param index : global index as integer : param axis : current axis to process : return :"""
if index >= self . __mask [ axis ] . stop - self . __halos [ 1 ] [ axis ] : return None if index < self . __mask [ axis ] . start : return 0 return index - self . __mask [ axis ] . start
def good_classmethod_decorator ( decorator ) : """This decorator makes class method decorators behave well wrt to decorated class method names , doc , etc ."""
def new_decorator ( cls , f ) : g = decorator ( cls , f ) g . __name__ = f . __name__ g . __doc__ = f . __doc__ g . __dict__ . update ( f . __dict__ ) return g new_decorator . __name__ = decorator . __name__ new_decorator . __doc__ = decorator . __doc__ new_decorator . __dict__ . update ( decorator ...
def main ( ) : """main The standard entry point to this script . This script will exit with a numeric error statement . The following are possible : errno . < POSIX > - Please look to the debugging messages and the meaning to The standard UNIX / LINUX POSIX meanings -1 - An unpredictable error has occur...
flagged_args = get_flagged_args ( ) working = os . getcwd ( ) config = load_json ( ) errnum = 0 error = _preliminary_construct ( config ) if not error and flagged_args : error = handle_flagged_args ( flagged_args , config ) elif not error : get_args ( ) error = build_packages ( config ) error = test_package...
def cee_map_priority_table_map_cos6_pgid ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) cee_map = ET . SubElement ( config , "cee-map" , xmlns = "urn:brocade.com:mgmt:brocade-cee-map" ) name_key = ET . SubElement ( cee_map , "name" ) name_key . text = kwargs . pop ( 'name' ) priority_table = ET . SubElement ( cee_map , "priority-table" ) map_cos6_pgid = ET . SubElement (...
def _isConfigFile ( self , filename ) : """If this is a config file or meta file return true"""
ext = os . path . splitext ( filename ) [ 1 ] . lower ( ) if filename in self . FB_CONFIG_FILES : return True elif ext in self . FB_META_EXTENSIONS : return True return False
def truncate_too_long_number ( numobj ) : """Truncate a number object that is too long . Attempts to extract a valid number from a phone number that is too long to be valid , and resets the PhoneNumber object passed in to that valid version . If no valid number could be extracted , the PhoneNumber object pa...
if is_valid_number ( numobj ) : return True numobj_copy = PhoneNumber ( ) numobj_copy . merge_from ( numobj ) national_number = numobj . national_number while not is_valid_number ( numobj_copy ) : # Strip a digit off the RHS national_number = national_number // 10 numobj_copy . national_number = national_nu...
def __save ( self , b ) : '''saves the given data to the buffer : param b :'''
newbufferidx = ( self . __bufferidx + len ( b ) ) self . __buffer [ self . __bufferidx : newbufferidx ] = b # update buffer index self . __bufferidx = newbufferidx
def internal_change_variable ( dbg , seq , thread_id , frame_id , scope , attr , value ) : '''Changes the value of a variable'''
try : frame = dbg . find_frame ( thread_id , frame_id ) if frame is not None : result = pydevd_vars . change_attr_expression ( frame , attr , value , dbg ) else : result = None xml = "<xml>" xml += pydevd_xml . var_to_xml ( result , "" ) xml += "</xml>" cmd = dbg . cmd_factor...
def show_popup_menu ( self , pos ) : '''show a popup menu'''
self . popup_pos = self . image_coordinates ( pos ) self . frame . PopupMenu ( self . wx_popup_menu , pos )
def __create_file_name ( self , message_no ) : """Create the filename to save to"""
cwd = os . getcwd ( ) filename = '{0}_{1}.xml' . format ( self . output_prefix , message_no ) return os . path . join ( cwd , filename )
def cli ( env , ** args ) : """Order / create virtual servers ."""
vsi = SoftLayer . VSManager ( env . client ) _validate_args ( env , args ) create_args = _parse_create_args ( env . client , args ) test = args . get ( 'test' , False ) do_create = not ( args . get ( 'export' ) or test ) if do_create : if not ( env . skip_confirmations or formatting . confirm ( "This action will in...
def per_window ( sequence , n = 1 ) : """From http : / / stackoverflow . com / q / 42220614/610569 > > > list ( per _ window ( [ 1,2,3,4 ] , n = 2 ) ) [ ( 1 , 2 ) , ( 2 , 3 ) , ( 3 , 4 ) ] > > > list ( per _ window ( [ 1,2,3,4 ] , n = 3 ) ) [ ( 1 , 2 , 3 ) , ( 2 , 3 , 4 ) ]"""
start , stop = 0 , n seq = list ( sequence ) while stop <= len ( seq ) : yield tuple ( seq [ start : stop ] ) start += 1 stop += 1
def create_provider_directory ( provider , redirect_uri ) : """Helper function for creating a provider directory"""
dir = CLIENT . directories . create ( { 'name' : APPLICATION . name + '-' + provider , 'provider' : { 'client_id' : settings . STORMPATH_SOCIAL [ provider . upper ( ) ] [ 'client_id' ] , 'client_secret' : settings . STORMPATH_SOCIAL [ provider . upper ( ) ] [ 'client_secret' ] , 'redirect_uri' : redirect_uri , 'provide...
def tokenize ( self , s ) : """Splits a string into tokens ."""
s = tf . compat . as_text ( s ) if self . reserved_tokens : # First split out the reserved tokens substrs = self . _reserved_tokens_re . split ( s ) else : substrs = [ s ] toks = [ ] for substr in substrs : if substr in self . reserved_tokens : toks . append ( substr ) else : toks . exte...
def LogoOverlay ( sites , overlayfile , overlay , nperline , sitewidth , rmargin , logoheight , barheight , barspacing , fix_limits = { } , fixlongname = False , overlay_cmap = None , underlay = False , scalebar = False ) : """Makes overlay for * LogoPlot * . This function creates colored bars overlay bars showin...
if os . path . splitext ( overlayfile ) [ 1 ] != '.pdf' : raise ValueError ( "overlayfile must end in .pdf: %s" % overlayfile ) if not overlay_cmap : ( cmap , mapping_d , mapper ) = KyteDoolittleColorMapping ( ) else : mapper = pylab . cm . ScalarMappable ( cmap = overlay_cmap ) cmap = mapper . get_cmap...
def ui_search_clicked_image ( self , value ) : """Setter for * * self . _ _ ui _ search _ clicked _ image * * attribute . : param value : Attribute value . : type value : unicode"""
if value is not None : assert type ( value ) is unicode , "'{0}' attribute: '{1}' type is not 'unicode'!" . format ( "ui_search_clicked_image" , value ) assert os . path . exists ( value ) , "'{0}' attribute: '{1}' file doesn't exists!" . format ( "ui_search_clicked_image" , value ) self . __ui_search_clicked_i...
def conjugate_gradient_normal ( op , x , rhs , niter = 1 , callback = None ) : """Optimized implementation of CG for the normal equation . This method solves the inverse problem ( of the first kind ) : : A ( x ) = = rhs with a linear ` Operator ` ` ` A ` ` by looking at the normal equation : : A . adjoint (...
# TODO : add a book reference # TODO : update doc if x not in op . domain : raise TypeError ( '`x` {!r} is not in the domain of `op` {!r}' '' . format ( x , op . domain ) ) d = op ( x ) d . lincomb ( 1 , rhs , - 1 , d ) # d = rhs - A x p = op . derivative ( x ) . adjoint ( d ) s = p . copy ( ) q = op . range . elem...
def p_members ( self , p ) : """members : | members member VALUE _ SEPARATOR | members member"""
if len ( p ) == 1 : p [ 0 ] = list ( ) else : p [ 1 ] . append ( p [ 2 ] ) p [ 0 ] = p [ 1 ]
def html_clean ( html_code ) : """获取网页源代码并进行预处理 Keyword arguments : html _ code - - 网页源代码 , 字符串类型 Return : 清洗后的网页源代码 ( 只包含文本和换行符 \n )"""
temp = re . sub ( '<script([\s\S]*?)</script>' , '' , html_code ) temp = re . sub ( '<style([\s\S]*?)</style>' , '' , temp ) html_cleaned = re . sub ( '(?is)<.*?>' , '' , temp ) for item in html_character : html_cleaned = html_cleaned . replace ( item , html_character [ item ] ) log ( 'debug' , '网页源代码预处理完成:\n【{}】' ...
def work_cancel ( self , hash ) : """Stop generating * * work * * for block . . enable _ control required : param hash : Hash to stop generating work for : type hash : str : raises : : py : exc : ` nano . rpc . RPCException ` > > > rpc . work _ cancel ( . . . hash = " 718CC2121C3E641059BC1C2CFC45666C99E...
hash = self . _process_value ( hash , 'block' ) payload = { "hash" : hash } resp = self . call ( 'work_cancel' , payload ) return resp == { }
def create_objects_from_iterables ( obj , args : dict , iterables : Dict [ str , Any ] , formatting_options : Dict [ str , Any ] , key_index_name : str = "KeyIndex" ) -> Tuple [ Any , Dict [ str , Any ] , dict ] : """Create objects for each set of values based on the given arguments . The iterable values are avai...
# Setup objects = { } names = list ( iterables ) logger . debug ( f"iterables: {iterables}" ) # Create the key index object , where the name of each field is the name of each iterable . KeyIndex = create_key_index_object ( key_index_name = key_index_name , iterables = iterables , ) # ` ` itertools . product ` ` produce...
def find_prop_item ( self , prop_name , prop_key , prop_value ) : """Look for a list prop with an item where key = = value"""
# Image props are a sequence of dicts . We often need one of them . # Where one of the items has a dict key matching a value , and if # nothing matches , return None prop = getattr ( self . props , prop_name , None ) if prop : return next ( ( p for p in prop if getattr ( p , prop_key ) == prop_value ) , None ) retu...
def get_field ( self , field ) : """Return the dataset corresponds to the provided key . Example : : a = np . ones ( ( 2,2 ) ) b = np . zeros ( ( 2,2 ) ) np . savez ( ' data . npz ' , a = a , b = b ) dataset = NumpyDataset ( ' data . npz ' ) data _ a = dataset . get _ field ( ' a ' ) data _ b = datase...
idx = self . _keys . index ( field ) return self . _data [ idx ]
def selectMap ( name = None , excludeName = False , closestMatch = True , ** tags ) : """select a map by name and / or critiera"""
matches = filterMapAttrs ( ** tags ) if not matches : raise c . InvalidMapSelection ( "could not find any matching maps given criteria: %s" % tags ) if name : # if name is specified , consider only the best - matching names only matches = filterMapNames ( name , excludeRegex = excludeName , closestMatch = close...
def mark_sentence ( s , args ) : """Insert markers around relation arguments in word sequence : param s : list of tokens in sentence . : type s : list : param args : list of triples ( l , h , idx ) as per @ _ mark ( . . . ) corresponding to relation arguments : type args : list : return : The marked sen...
marks = sorted ( [ y for m in args for y in mark ( * m ) ] , reverse = True ) x = list ( s ) for k , v in marks : x . insert ( k , v ) return x
def breeding_male_location_type ( self ) : """This attribute defines whether a male ' s current location is the same as the breeding cage to which it belongs . This attribute is used to color breeding table entries such that male mice which are currently in a different cage can quickly be identified . The locat...
try : self . breeding_males . all ( ) [ 0 ] . Cage if int ( self . breeding_males . all ( ) [ 0 ] . Cage ) == int ( self . Cage ) : type = "resident-breeder" else : type = "non-resident-breeder" except IndexError : type = "unknown-breeder" except ValueError : type = "unknown-breeder"...
def get_seed ( self ) : """Collects the required information to generate a data estructure that can be used to recreate exactly the same geometry object via * \ * \ * kwargs * . : returns : Object ' s sufficient info to initialize it . : rtype : dict . . seealso : : * : func : ` get _ map ` * : func :...
self . seed = { 'places' : [ place . get_seed ( ) for place in self ] } return self . seed
def with_suffix ( self , suffix ) : """Return a new path with the file suffix changed ( or added , if none ) > > > Path ( ' / home / guido / python . tar . gz ' ) . with _ suffix ( " . foo " ) Path ( ' / home / guido / python . tar . foo ' ) > > > Path ( ' python ' ) . with _ suffix ( ' . zip ' ) Path ( ' p...
if not suffix . startswith ( '.' ) : raise ValueError ( "Invalid suffix {suffix!r}" . format ( ** locals ( ) ) ) return self . stripext ( ) + suffix
def shift ( txt , indent = ' ' , prepend = '' ) : """Return a list corresponding to the lines of text in the ` txt ` list indented by ` indent ` . Prepend instead the string given in ` prepend ` to the beginning of the first line . Note that if len ( prepend ) > len ( indent ) , then ` prepend ` will be tr...
if type ( indent ) is int : indent = indent * ' ' special_end = txt [ - 1 : ] == [ '' ] lines = '' . join ( txt ) . splitlines ( True ) for i in range ( 1 , len ( lines ) ) : if lines [ i ] . strip ( ) or indent . strip ( ) : lines [ i ] = indent + lines [ i ] if not lines : return prepend prepend =...
def rulejoin ( class_rule , method_rule ) : """Join class and method rules . Used internally by : class : ` ClassView ` to combine rules from the : func : ` route ` decorators on the class and on the individual view handler methods : : > > > rulejoin ( ' / ' , ' ' ) > > > rulejoin ( ' / ' , ' first ' ) ' ...
if method_rule . startswith ( '/' ) : return method_rule else : return class_rule + ( '' if class_rule . endswith ( '/' ) or not method_rule else '/' ) + method_rule
def size ( self ) : '''return tile size as ( width , height ) in meters'''
( lat1 , lon1 ) = self . coord ( ( 0 , 0 ) ) ( lat2 , lon2 ) = self . coord ( ( TILES_WIDTH , 0 ) ) width = mp_util . gps_distance ( lat1 , lon1 , lat2 , lon2 ) ( lat2 , lon2 ) = self . coord ( ( 0 , TILES_HEIGHT ) ) height = mp_util . gps_distance ( lat1 , lon1 , lat2 , lon2 ) return ( width , height )
def substitute_variables ( cls , configuration , value , ref ) : """Substitute variables in ` value ` from ` configuration ` where any path reference is relative to ` ref ` . Parameters configuration : dict configuration ( required to resolve intra - document references ) value : value to resolve substi...
if isinstance ( value , str ) : # Substitute all intra - document references while True : match = cls . REF_PATTERN . search ( value ) if match is None : break path = os . path . join ( os . path . dirname ( ref ) , match . group ( 'path' ) ) try : value = val...
def get_all_triggers ( bump , file_triggers ) : """Aggregated set of significant figures to bump"""
triggers = set ( ) if file_triggers : triggers = triggers . union ( detect_file_triggers ( config . trigger_patterns ) ) if bump : _LOG . debug ( "trigger: %s bump requested" , bump ) triggers . add ( bump ) return triggers
def _normalize_cmd_args ( cmd ) : """Normalize subprocess arguments to handle list commands , string and pipes . Piped commands set pipefail and require use of bash to help with debugging intermediate errors ."""
if isinstance ( cmd , six . string_types ) : # check for standard or anonymous named pipes if cmd . find ( " | " ) > 0 or cmd . find ( ">(" ) or cmd . find ( "<(" ) : return "set -o pipefail; " + cmd , True , find_bash ( ) else : return cmd , True , None else : return [ str ( x ) for x in cm...
def append_response_error_content ( response , ** kwargs ) : """Provides a helper to act as callback function for the response event hook and add a HTTP response error with reason message to ` ` response . reason ` ` . The ` ` response ` ` and ` ` * * kwargs ` ` are necessary for this function to properly ope...
if response . status_code >= 400 : try : resp_dict = response_to_json_dict ( response ) error = resp_dict . get ( 'error' , '' ) reason = resp_dict . get ( 'reason' , '' ) # Append to the existing response ' s reason response . reason += ' {0} {1}' . format ( error , reason )...
def main_with_metrics ( ) : """Runs main ( ) and reports success and failure metrics"""
try : main ( ) except Exception : report_metric ( "bus.lizzy-client.failed" , 1 ) raise except SystemExit as sys_exit : if sys_exit . code == 0 : report_metric ( "bus.lizzy-client.success" , 1 ) else : report_metric ( "bus.lizzy-client.failed" , 1 ) raise else : report_metric...
def get_symbol_size ( version , scale = 1 , border = None ) : """Returns the symbol size ( width x height ) with the provided border and scaling factor . : param int version : A version constant . : param scale : Indicates the size of a single module ( default : 1 ) . The size of a module depends on the use...
if border is None : border = get_default_border_size ( version ) # M4 = 0 , M3 = - 1 . . . dim = version * 4 + 17 if version > 0 else ( version + 4 ) * 2 + 9 dim += 2 * border dim *= scale return dim , dim
def spacings ( self ) : """Computes the distances between neighboring crystal planes"""
result_invsq = ( self . reciprocal ** 2 ) . sum ( axis = 0 ) result = np . zeros ( 3 , float ) for i in range ( 3 ) : if result_invsq [ i ] > 0 : result [ i ] = result_invsq [ i ] ** ( - 0.5 ) return result
def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_last_counters_cleared ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) fcoe_get_interface = ET . Element ( "fcoe_get_interface" ) config = fcoe_get_interface output = ET . SubElement ( fcoe_get_interface , "output" ) fcoe_intf_list = ET . SubElement ( output , "fcoe-intf-list" ) fcoe_intf_fcoe_port_id_key = ET . SubElement ( fcoe_intf_list , "fcoe-intf-f...
def strings ( self ) : """Write strings sheet ."""
sheet = self . result . add_sheet ( "strings" ) self . header ( sheet , "strings" ) n_row = 1 # row number for entry in self . po : row = sheet . row ( n_row ) row . write ( 0 , entry . msgid ) row . write ( 1 , entry . msgstr ) n_row += 1 sheet . flush_row_data ( )
def servo_config ( self , pin , min_pulse = 544 , max_pulse = 2400 , angle = 0 ) : """Configure a pin as servo with min _ pulse , max _ pulse and first angle . ` ` min _ pulse ` ` and ` ` max _ pulse ` ` default to the arduino defaults ."""
if pin > len ( self . digital ) or self . digital [ pin ] . mode == UNAVAILABLE : raise IOError ( "Pin {0} is not a valid servo pin" . format ( pin ) ) data = bytearray ( [ pin ] ) data += to_two_bytes ( min_pulse ) data += to_two_bytes ( max_pulse ) self . send_sysex ( SERVO_CONFIG , data ) # set pin . _ mode to S...
def decrypt_cbc_cts ( self , data , init_vector ) : """Return an iterator that decrypts ` data ` using the Cipher - Block Chaining with Ciphertext Stealing ( CBC - CTS ) mode of operation . CBC - CTS mode can only operate on ` data ` that is greater than 8 bytes in length . Each iteration , except the last ...
data_len = len ( data ) if data_len <= 8 : raise ValueError ( "data is not greater than 8 bytes in length" ) S1 , S2 , S3 , S4 = self . S P = self . P u4_1_pack = self . _u4_1_pack u1_4_unpack = self . _u1_4_unpack u4_2_pack = self . _u4_2_pack u4_2_unpack = self . _u4_2_unpack decrypt = self . _decrypt try : p...
def create ( cls , pid_type , pid_value , pid_provider = None , status = PIDStatus . NEW , object_type = None , object_uuid = None , ) : """Create a new persistent identifier with specific type and value . : param pid _ type : Persistent identifier type . : param pid _ value : Persistent identifier value . : ...
try : with db . session . begin_nested ( ) : obj = cls ( pid_type = pid_type , pid_value = pid_value , pid_provider = pid_provider , status = status ) if object_type and object_uuid : obj . assign ( object_type , object_uuid ) db . session . add ( obj ) logger . info ( "Creat...
def format_dap_from_dapi ( name , version = '' , full = False ) : '''Formats information about given DAP from DAPI in a human readable form to list of lines'''
lines = [ ] m , d = _get_metadap_dap ( name , version ) if d : # Determining label width labels = BASIC_LABELS + [ 'average_rank' ] # average _ rank comes from m , not d if full : labels . extend ( EXTRA_LABELS ) label_width = dapi . DapFormatter . calculate_offset ( labels ) # Metadata ...
def _update_subplot ( self , subplot , spec ) : """Updates existing subplots when the subplot has been assigned to plot an element that is not an exact match to the object it was initially assigned ."""
# See if the precise spec has already been assigned a cyclic # index otherwise generate a new one if spec in self . cyclic_index_lookup : cyclic_index = self . cyclic_index_lookup [ spec ] else : group_key = spec [ : self . style_grouping ] self . group_counter [ group_key ] += 1 cyclic_index = self . g...
def move_item_into_viewport ( self , item ) : """Causes the ` item ` to be moved into the viewport The zoom factor and the position of the viewport are updated to move the ` item ` into the viewport . If ` item ` is not a ` StateView ` , the parental ` StateView ` is moved into the viewport . : param StateVie...
if not item : return HORIZONTAL = 0 VERTICAL = 1 if not isinstance ( item , Item ) : state_v = item . parent elif not isinstance ( item , StateView ) : state_v = self . canvas . get_parent ( item ) else : state_v = item viewport_size = self . view . editor . get_allocation ( ) . width , self . view . ed...
def add_event ( self , key , event ) : """Add an event and its corresponding key to the store ."""
if self . key_exists ( key ) : # This check might actually also be done further up in the chain # ( read : SQLiteEventStore ) . Could potentially be removed if it # requires a lot of processor cycles . msg = "The key already existed: {0}" . format ( key ) raise EventStore . EventKeyAlreadyExistError ( msg ) sel...
def out_32 ( library , session , space , offset , data , extended = False ) : """Write in an 32 - bit value from the specified memory space and offset . Corresponds to viOut32 * functions of the VISA library . : param library : the visa library wrapped by ctypes . : param session : Unique logical identifier t...
if extended : return library . viOut32Ex ( session , space , offset , data ) else : return library . viOut32 ( session , space , offset , data )
def get_relations ( self , cursor , table_name ) : """Returns a dictionary of { field _ index : ( field _ index _ other _ table , other _ table ) } representing all relationships to the given table . Indexes are 0 - based ."""
# CONSTRAINT _ COLUMN _ USAGE : http : / / msdn2 . microsoft . com / en - us / library / ms174431 . aspx # CONSTRAINT _ TABLE _ USAGE : http : / / msdn2 . microsoft . com / en - us / library / ms179883 . aspx # REFERENTIAL _ CONSTRAINTS : http : / / msdn2 . microsoft . com / en - us / library / ms179987 . aspx # TABLE ...
def tabs_or_spaces ( physical_line , indent_char ) : r"""Never mix tabs and spaces . The most popular way of indenting Python is with spaces only . The second - most popular way is with tabs only . Code indented with a mixture of tabs and spaces should be converted to using spaces exclusively . When invokin...
indent = INDENT_REGEX . match ( physical_line ) . group ( 1 ) for offset , char in enumerate ( indent ) : if char != indent_char : return offset , "E101 indentation contains mixed spaces and tabs"
def save_to ( self , file ) : """Save data to file . Will copy by either writing out the data or using : func : ` shutil . copyfileobj ` . : param file : A file - like object ( with a ` ` write ` ` method ) or a filename ."""
dest = file if hasattr ( dest , 'write' ) : # writing to a file - like # only works when no unicode conversion is done if self . file is not None and getattr ( self . file , 'encoding' , None ) is None : copyfileobj ( self . file , dest ) elif self . filename is not None : with open ( self . fil...
def fit ( self , Xs = None , ys = None , Xt = None , yt = None ) : """Build a coupling matrix from source and target sets of samples ( Xs , ys ) and ( Xt , yt ) Parameters Xs : array - like , shape ( n _ source _ samples , n _ features ) The training input samples . ys : array - like , shape ( n _ source ...
super ( SinkhornTransport , self ) . fit ( Xs , ys , Xt , yt ) # coupling estimation returned_ = sinkhorn ( a = self . mu_s , b = self . mu_t , M = self . cost_ , reg = self . reg_e , numItermax = self . max_iter , stopThr = self . tol , verbose = self . verbose , log = self . log ) # deal with the value of log if self...
def send_digest_event ( self , trigger_id , title , link = '' ) : """handling of the signal of digest : param trigger _ id : : param title : : param link : : return :"""
if settings . DJANGO_TH . get ( 'digest_event' ) : t = TriggerService . objects . get ( id = trigger_id ) if t . provider . duration != 'n' : kwargs = { 'user' : t . user , 'title' : title , 'link' : link , 'duration' : t . provider . duration } signals . digest_event . send ( sender = t . provi...
def twisted_absolute_path ( path , request ) : """Hack to fix twisted not accepting absolute URIs"""
parsed = urlparse . urlparse ( request . uri ) if parsed . scheme != '' : path_parts = parsed . path . lstrip ( '/' ) . split ( '/' ) request . prepath = path_parts [ 0 : 1 ] request . postpath = path_parts [ 1 : ] path = request . prepath [ 0 ] return path , request
def ask_unicode_16 ( self , next_rva_ptr ) : """The next RVA is taken to be the one immediately following this one . Such RVA could indicate the natural end of the string and will be checked to see if there ' s a Unicode NULL character there ."""
if self . __get_word_value_at_rva ( next_rva_ptr - 2 ) == 0 : self . length = next_rva_ptr - self . rva_ptr return True return False
def get_disease_pathways ( self , disease_id = None , disease_name = None , pathway_id = None , pathway_name = None , disease_definition = None , limit = None , as_df = False ) : """Get disease pathway link : param bool as _ df : if set to True result returns as ` pandas . DataFrame ` : param disease _ id : :...
q = self . session . query ( models . DiseasePathway ) q = self . _join_disease ( query = q , disease_id = disease_id , disease_name = disease_name , disease_definition = disease_definition ) q = self . _join_pathway ( query = q , pathway_id = pathway_id , pathway_name = pathway_name ) return self . _limit_and_df ( q ,...
def linkify_sd_by_tp ( self , timeperiods ) : """Replace dependency _ period by a real object in service dependency : param timeperiods : list of timeperiod , used to look for a specific one : type timeperiods : alignak . objects . timeperiod . Timeperiods : return : None"""
for servicedep in self : try : tp_name = servicedep . dependency_period timeperiod = timeperiods . find_by_name ( tp_name ) if timeperiod : servicedep . dependency_period = timeperiod . uuid else : servicedep . dependency_period = '' except AttributeError ...
def transpose ( self ) : """Create a transpose of this matrix ."""
ma4 = Matrix4 ( self . get_col ( 0 ) , self . get_col ( 1 ) , self . get_col ( 2 ) , self . get_col ( 3 ) ) return ma4
def write ( name , values , tags = { } , timestamp = None , database = None ) : """Method to be called via threading module ."""
point = { 'measurement' : name , 'tags' : tags , 'fields' : values } if isinstance ( timestamp , datetime ) : timestamp = timestamp . strftime ( '%Y-%m-%dT%H:%M:%SZ' ) if timestamp : point [ 'time' ] = timestamp try : get_db ( ) . write ( { 'points' : [ point ] } , { 'db' : database or settings . INFLUXDB_D...