signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_movielens_item_metadata ( use_item_ids ) : """Build a matrix of genre features ( no _ items , no _ features ) . If use _ item _ ids is True , per - item features will also be used ."""
features = { } genre_set = set ( ) for line in _get_movie_raw_metadata ( ) : if not line : continue splt = line . split ( '|' ) item_id = int ( splt [ 0 ] ) genres = [ idx for idx , val in zip ( range ( len ( splt [ 5 : ] ) ) , splt [ 5 : ] ) if int ( val ) > 0 ] if use_item_ids : # Add item...
def resize ( self , width , height , ** kwargs ) : """Resizes the image to the supplied width / height . Returns the instance . Supports the following optional keyword arguments : mode - The resizing mode to use , see Image . MODES filter - The filter to use : see Image . FILTERS background - The hexadecima...
opts = Image . _normalize_options ( kwargs ) size = self . _get_size ( width , height ) if opts [ "mode" ] == "adapt" : self . _adapt ( size , opts ) elif opts [ "mode" ] == "clip" : self . _clip ( size , opts ) elif opts [ "mode" ] == "fill" : self . _fill ( size , opts ) elif opts [ "mode" ] == "scale" : ...
def embedding_plot ( ind , shap_values , feature_names = None , method = "pca" , alpha = 1.0 , show = True ) : """Use the SHAP values as an embedding which we project to 2D for visualization . Parameters ind : int or string If this is an int it is the index of the feature to use to color the embedding . If ...
if feature_names is None : feature_names = [ labels [ 'FEATURE' ] % str ( i ) for i in range ( shap_values . shape [ 1 ] ) ] ind = convert_name ( ind , shap_values , feature_names ) if ind == "sum()" : cvals = shap_values . sum ( 1 ) fname = "sum(SHAP values)" else : cvals = shap_values [ : , ind ] ...
def getSpecificAssociatedDeviceInfo ( self , macAddress , wifiInterfaceId = 1 , timeout = 1 ) : """Execute GetSpecificAssociatedDeviceInfo action to get detailed information about a Wifi client . : param str macAddress : MAC address in the form ` ` 38 : C9:86:26:7E : 38 ` ` ; be aware that the MAC address might ...
namespace = Wifi . getServiceType ( "getSpecificAssociatedDeviceInfo" ) + str ( wifiInterfaceId ) uri = self . getControlURL ( namespace ) results = self . execute ( uri , namespace , "GetSpecificAssociatedDeviceInfo" , timeout = timeout , NewAssociatedDeviceMACAddress = macAddress ) return WifiDeviceInfo ( results , m...
def is_following ( user , obj , flag = '' ) : """Checks if a " follow " relationship exists . Returns True if exists , False otherwise . Pass a string value to ` ` flag ` ` to determine which type of " follow " relationship you want to check . Example : : is _ following ( request . user , group ) is _ fol...
check ( obj ) qs = apps . get_model ( 'actstream' , 'follow' ) . objects . filter ( user = user , object_id = obj . pk , content_type = ContentType . objects . get_for_model ( obj ) ) if flag : qs = qs . filter ( flag = flag ) return qs . exists ( )
def _base_type ( self ) : """Return str like ' enum . numeric ' representing dimension type . This string is a ' type . subclass ' concatenation of the str keys used to identify the dimension type in the cube response JSON . The ' . subclass ' suffix only appears where a subtype is present ."""
type_class = self . _dimension_dict [ "type" ] [ "class" ] if type_class == "categorical" : return "categorical" if type_class == "enum" : subclass = self . _dimension_dict [ "type" ] [ "subtype" ] [ "class" ] return "enum.%s" % subclass raise NotImplementedError ( "unexpected dimension type class '%s'" % t...
def start ( self ) : '''Start the actual proxy minion . If sub - classed , don ' t * * ever * * forget to run : super ( YourSubClass , self ) . start ( ) NOTE : Run any required code before calling ` super ( ) ` .'''
super ( ProxyMinion , self ) . start ( ) try : if check_user ( self . config [ 'user' ] ) : self . action_log_info ( 'The Proxy Minion is starting up' ) self . verify_hash_type ( ) self . minion . tune_in ( ) if self . minion . restart : raise SaltClientError ( 'Proxy Min...
def normalize ( value ) : """Simple method to always have the same kind of value"""
if value and isinstance ( value , bytes ) : value = value . decode ( 'utf-8' ) return value
def serial_udb_extra_f13_send ( self , sue_week_no , sue_lat_origin , sue_lon_origin , sue_alt_origin , force_mavlink1 = False ) : '''Backwards compatible version of SERIAL _ UDB _ EXTRA F13 : format sue _ week _ no : Serial UDB Extra GPS Week Number ( int16 _ t ) sue _ lat _ origin : Serial UDB Extra MP Origin...
return self . send ( self . serial_udb_extra_f13_encode ( sue_week_no , sue_lat_origin , sue_lon_origin , sue_alt_origin ) , force_mavlink1 = force_mavlink1 )
def format_time ( seconds ) : """Formats a string from time given in seconds . For large times ( ` ` abs ( seconds ) > = 60 ` ` ) the format is : : dd : hh : mm : ss For small times ( ` ` abs ( seconds ) < 60 ` ` ) , the result is given in 3 significant figures , with units given in seconds and a suitable S...
if not isinstance ( seconds , ( int , float ) ) : return str ( seconds ) if math . isnan ( seconds ) : return "-" if abs ( seconds ) < 60 : return format_time_small ( seconds ) else : return format_time_large ( seconds )
def stdchannel_redirected ( stdchannel , dest_filename , fake = False ) : """A context manager to temporarily redirect stdout or stderr e . g . : with stdchannel _ redirected ( sys . stderr , os . devnull ) : if compiler . has _ function ( ' clock _ gettime ' , libraries = [ ' rt ' ] ) : libraries . append ...
if fake : yield return oldstdchannel = dest_file = None try : oldstdchannel = os . dup ( stdchannel . fileno ( ) ) dest_file = open ( dest_filename , 'w' ) os . dup2 ( dest_file . fileno ( ) , stdchannel . fileno ( ) ) yield finally : if oldstdchannel is not None : os . dup2 ( oldstd...
def _set_above ( self , v , load = False ) : """Setter method for above , mapped from YANG variable / rbridge _ id / threshold _ monitor / interface / policy / area / alert / above ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ above is considered as a pr...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = above . above , is_container = 'container' , presence = False , yang_name = "above" , rest_name = "above" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True , extensi...
def temp_file ( ) : """Create a temporary file for the duration of this context manager , deleting it afterwards . Yields : str - path to the file"""
fd , path = tempfile . mkstemp ( ) os . close ( fd ) try : yield path finally : os . remove ( path )
def get_services ( cls , request = None ) : """Get a list of services endpoints . " Oracle " : " / api / oracle / " , " OpenStack " : " / api / openstack / " , " GitLab " : " / api / gitlab / " , " DigitalOcean " : " / api / digitalocean / " """
return { service [ 'name' ] : reverse ( service [ 'list_view' ] , request = request ) for service in cls . _registry . values ( ) }
def make_command ( command , env = None , su_user = None , sudo = False , sudo_user = None , preserve_sudo_env = False , ) : '''Builds a shell command with various kwargs .'''
debug_meta = { } for key , value in ( ( 'sudo' , sudo ) , ( 'sudo_user' , sudo_user ) , ( 'su_user' , su_user ) , ( 'env' , env ) , ) : if value : debug_meta [ key ] = value logger . debug ( 'Building command ({0}): {1}' . format ( ' ' . join ( '{0}: {1}' . format ( key , value ) for key , value in six . it...
def get_composition ( self ) : '''Get composition of output structure Returns : String - Composition based on output structure'''
strc = self . get_output_structure ( ) counts = Counter ( strc . get_chemical_symbols ( ) ) return '' . join ( k if counts [ k ] == 1 else '%s%d' % ( k , counts [ k ] ) for k in sorted ( counts ) )
def _remove_hidden_parts ( projected_surface ) : """Removes parts of a projected surface that are not visible . Args : projected _ surface ( surface ) : the surface to use Returns : surface : A projected surface ."""
surface = np . copy ( projected_surface ) surface [ ~ _make_occlusion_mask ( projected_surface ) ] = np . nan return surface
def dispatch ( self ) : 'Perform dispatch , using request embedded within flask global state'
import flask body = flask . request . get_json ( ) return self . dispatch_with_args ( body , argMap = dict ( ) )
def add_scan_log ( self , scan_id , host = '' , name = '' , value = '' , port = '' , test_id = '' , qod = '' ) : """Adds a log result to scan _ id scan ."""
self . scan_collection . add_result ( scan_id , ResultType . LOG , host , name , value , port , test_id , 0.0 , qod )
def retrieve_utxos ( self , addresses ) : """Get current utxos for < address > ."""
addresses = deserialize . addresses ( self . testnet , addresses ) spendables = control . retrieve_utxos ( self . service , addresses ) return serialize . utxos ( spendables )
def append_offsetvector ( self , offsetvect , process ) : """Append rows describing an instrument - - > offset mapping to this table . offsetvect is a dictionary mapping instrument to offset . process should be the row in the process table on which the new time _ slide table rows will be blamed ( or any obj...
time_slide_id = self . get_next_id ( ) for instrument , offset in offsetvect . items ( ) : row = self . RowType ( ) row . process_id = process . process_id row . time_slide_id = time_slide_id row . instrument = instrument row . offset = offset self . append ( row ) return time_slide_id
def getUnitCost ( self , CorpNum ) : """휴폐업조회 단가 확인 . args CorpNum : 팝빌회원 사업자번호 return 발행단가 by float raise PopbillException"""
result = self . _httpget ( '/CloseDown/UnitCost' , CorpNum ) return float ( result . unitCost )
def drop_project ( project_name ) : """Deletes all the tables associated with a project and removes it from the main _ table : param project _ name : String , project to delete"""
conn , c = open_data_base_connection ( ) # Need to delete all the run _ tables before removing the project _ table and the entry from the main _ table run_table_name = project_name + '_run_table' c . execute ( "SELECT run_name FROM {}" . format ( run_table_name ) ) run_names = np . array ( c . fetchall ( ) ) . squeeze ...
def addPort ( n : LNode , intf : Interface ) : """Add LayoutExternalPort for interface"""
d = PortTypeFromDir ( intf . _direction ) ext_p = LayoutExternalPort ( n , name = intf . _name , direction = d , node2lnode = n . _node2lnode ) ext_p . originObj = originObjOfPort ( intf ) n . children . append ( ext_p ) addPortToLNode ( ext_p , intf , reverseDirection = True ) return ext_p
def from_address ( text ) : """Convert an IPv4 or IPv6 address in textual form into a Name object whose value is the reverse - map domain name of the address . @ param text : an IPv4 or IPv6 address in textual form ( e . g . ' 127.0.0.1 ' , @ type text : str @ rtype : dns . name . Name object"""
try : parts = list ( dns . ipv6 . inet_aton ( text ) . encode ( 'hex_codec' ) ) origin = ipv6_reverse_domain except Exception : parts = [ '%d' % ord ( byte ) for byte in dns . ipv4 . inet_aton ( text ) ] origin = ipv4_reverse_domain parts . reverse ( ) return dns . name . from_text ( '.' . join ( parts ...
def write ( self , s ) : """Write string s to the stream ."""
if self . comptype == "gz" : self . crc = self . zlib . crc32 ( s , self . crc ) self . pos += len ( s ) if self . comptype != "tar" : s = self . cmp . compress ( s ) self . __write ( s )
def publishPublicReport ( self ) : """Activate public report for this check . Returns status message"""
response = self . pingdom . request ( 'PUT' , 'reports.public/%s' % self . id ) return response . json ( ) [ 'message' ]
def update ( self , group_id , new_group_name , session ) : '''taobao . crm . group . update 修改一个已经存在的分组 修改一个已经存在的分组 , 接口返回分组的修改是否成功'''
request = TOPRequest ( 'taobao.crm.group.update' ) request [ 'group_id' ] = group_id request [ 'new_group_name' ] = new_group_name self . create ( self . execute ( request , session ) , fields = [ 'is_success' , ] ) return self . is_success
def listAcquisitionEras ( self , acq = '' ) : """Returns all acquistion eras in dbs"""
try : acq = str ( acq ) except : dbsExceptionHandler ( 'dbsException-invalid-input' , 'acquistion_era_name given is not valid : %s' % acq ) conn = self . dbi . connection ( ) try : result = self . acqlst . execute ( conn , acq ) return result finally : if conn : conn . close ( )
def character_ascii_value ( character : str ) -> int : """Calculates the ASCII value of a given character Examples : character _ ascii _ value ( ' A ' ) - > 65 character _ ascii _ value ( ' R ' ) - > 82 character _ ascii _ value ( ' S ' ) - > 83 Args : character : A single character string for which the...
return ord ( character )
def set_postmortem_debugger ( cls , cmdline , auto = None , hotkey = None , bits = None ) : """Sets the postmortem debugging settings in the Registry . @ warning : This method requires administrative rights . @ see : L { get _ postmortem _ debugger } @ type cmdline : str @ param cmdline : Command line to th...
if bits is None : bits = cls . bits elif bits not in ( 32 , 64 ) : raise NotImplementedError ( "Unknown architecture (%r bits)" % bits ) if bits == 32 and cls . bits == 64 : keyname = 'HKLM\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug' else : keyname = 'HKLM\\SOFTWARE\\Microsof...
def vlan_classifier_group_ruleid ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) vlan = ET . SubElement ( config , "vlan" , xmlns = "urn:brocade.com:mgmt:brocade-vlan" ) classifier = ET . SubElement ( vlan , "classifier" ) group = ET . SubElement ( classifier , "group" ) groupid_key = ET . SubElement ( group , "groupid" ) groupid_key . text = kwargs . pop ( 'group...
def create_tensorflow_extension ( nvcc_settings , device_info ) : """Create an extension that builds the custom tensorflow ops"""
import tensorflow as tf import glob use_cuda = ( bool ( nvcc_settings [ 'cuda_available' ] ) and tf . test . is_built_with_cuda ( ) ) # Source and includes source_path = os . path . join ( 'montblanc' , 'impl' , 'rime' , 'tensorflow' , 'rime_ops' ) sources = glob . glob ( os . path . join ( source_path , '*.cpp' ) ) # ...
def hide ( self ) : """Hide the window ."""
self . tk . withdraw ( ) self . _visible = False if self . _modal : self . tk . grab_release ( )
def set_local ( self , name , stmt ) : """Define that the given name is declared in the given statement node . . . seealso : : : meth : ` scope ` : param name : The name that is being defined . : type name : str : param stmt : The statement that defines the given name . : type stmt : NodeNG"""
# assert not stmt in self . locals . get ( name , ( ) ) , ( self , stmt ) self . locals . setdefault ( name , [ ] ) . append ( stmt )
def _add_tile ( self , new_tile , ijk ) : """Add a tile with a label indicating its tiling position ."""
tile_label = "{0}_{1}" . format ( self . name , '-' . join ( str ( d ) for d in ijk ) ) self . add ( new_tile , label = tile_label , inherit_periodicity = False )
def list_all_brands ( cls , ** kwargs ) : """List Brands Return a list of Brands This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async = True > > > thread = api . list _ all _ brands ( async = True ) > > > result = thread . get ( ) : param asy...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async' ) : return cls . _list_all_brands_with_http_info ( ** kwargs ) else : ( data ) = cls . _list_all_brands_with_http_info ( ** kwargs ) return data
def delete_connections ( self , ** kwargs ) : """Remove a single connection to a provider for the specified user ."""
rv = False for c in self . find_connections ( ** kwargs ) : self . delete ( c ) rv = True return rv
def intersection ( self , other ) : """Return a new set which is the intersection of I { self } and I { other } . @ param other : the other set @ type other : Set object @ rtype : the same type as I { self }"""
obj = self . _clone ( ) obj . intersection_update ( other ) return obj
def get_dupe_prob ( self , url ) : """A probability of given url being a duplicate of some content that has already been seem ."""
path , query = _parse_url ( url ) dupestats = [ ] extend_ds = lambda x : dupestats . extend ( filter ( None , ( ds_dict . get ( key ) for ds_dict , key in x ) ) ) if self . urls_by_path . get ( path ) : extend_ds ( [ ( self . path_dupstats , path ) ] ) # If param is in the query for param , value in query . items (...
def _verify ( self ) : """Verify the specified scenario was found and returns None . : return : None"""
scenario_names = [ c . scenario . name for c in self . _configs ] if self . _scenario_name not in scenario_names : msg = ( "Scenario '{}' not found. " 'Exiting.' ) . format ( self . _scenario_name ) util . sysexit_with_message ( msg )
def predict_compound_pairs ( reaction , compound_formula , solver , epsilon = 1e-5 , alt_elements = None , weight_func = default_weight ) : """Predict compound pairs of reaction using MapMaker . Yields all solutions as dictionaries with compound pairs as keys and formula objects as values . Args : reaction ...
elements = set ( ) for compound , value in reaction . compounds : if compound . name not in compound_formula : return f = compound_formula [ compound . name ] elements . update ( e for e , _ , _ in _weighted_formula ( f , weight_func ) ) if len ( elements ) == 0 : return p = solver . create_prob...
def tickUpdate ( self , tick_dict ) : '''consume ticks'''
assert self . symbols assert self . symbols [ 0 ] in tick_dict . keys ( ) symbol = self . symbols [ 0 ] tick = tick_dict [ symbol ] if self . increase_and_check_counter ( ) : self . place_order ( Order ( account = self . account , action = Action . BUY , is_market = True , symbol = symbol , price = tick . close , s...
def _srcprob_app ( self , xmlfile = None , overwrite = False , ** kwargs ) : """Run srcprob for an analysis component as an application"""
loglevel = kwargs . get ( 'loglevel' , self . loglevel ) self . logger . log ( loglevel , 'Computing src probability for component %s.' , self . name ) # set the srcmdl srcmdl_file = self . files [ 'srcmdl' ] if xmlfile is not None : srcmdl_file = self . get_model_path ( xmlfile ) # set the outfile # it ' s defined...
def POST_AUTH ( self , courseid ) : # pylint : disable = arguments - differ """GET request"""
course , __ = self . get_course_and_check_rights ( courseid , allow_all_staff = False ) user_input = web . input ( tasks = [ ] , aggregations = [ ] , users = [ ] ) if "submission" in user_input : # Replay a unique submission submission = self . database . submissions . find_one ( { "_id" : ObjectId ( user_input . s...
def _load_config_file ( self , fname = None ) : '''Load config from config file . If fname is not specified , config is loaded from the file named by InsightsConfig . conf'''
parsedconfig = ConfigParser . RawConfigParser ( ) try : parsedconfig . read ( fname or self . conf ) except ConfigParser . Error : if self . _print_errors : sys . stdout . write ( 'ERROR: Could not read configuration file, ' 'using defaults\n' ) return try : if parsedconfig . has_section ( const...
def dump ( self , out = sys . stdout , row_fn = repr , limit = - 1 , indent = 0 ) : """Dump out the contents of this table in a nested listing . @ param out : output stream to write to @ param row _ fn : function to call to display individual rows @ param limit : number of records to show at deepest level of ...
NL = '\n' if indent : out . write ( " " * indent + self . pivot_key_str ( ) ) else : out . write ( "Pivot: %s" % ',' . join ( self . _pivot_attrs ) ) out . write ( NL ) if self . has_subtables ( ) : do_all ( sub . dump ( out , row_fn , limit , indent + 1 ) for sub in self . subtables if sub ) else : if...
def get_available_gpus ( ) : """Returns a list of string names of all available GPUs"""
local_device_protos = device_lib . list_local_devices ( ) return [ x . name for x in local_device_protos if x . device_type == 'GPU' ]
def do_sticky ( self , arg ) : """sticky [ start end ] Toggle sticky mode . When in sticky mode , it clear the screen and longlist the current functions , making the source appearing always in the same position . Useful to follow the flow control of a function when doing step - by - step execution . If ` ...
if arg : try : start , end = map ( int , arg . split ( ) ) except ValueError : print ( '** Error when parsing argument: %s **' % arg , file = self . stdout ) return self . sticky = True self . sticky_ranges [ self . curframe ] = start , end + 1 else : self . sticky = not self...
def read_async ( self ) : '''Asynchronously read messages and invoke a callback when they are ready . : param callback : A callback with the received data'''
while not self . connected ( ) : try : yield self . connect ( timeout = 5 ) except tornado . iostream . StreamClosedError : log . trace ( 'Subscriber closed stream on IPC %s before connect' , self . socket_path ) yield tornado . gen . sleep ( 1 ) except Exception as exc : log...
def disconnect_all ( self ) : '''Disconnect all connections to this port .'''
with self . _mutex : for conn in self . connections : self . object . disconnect ( conn . id ) self . reparse_connections ( )
def WriteFlowRequests ( self , requests , cursor = None ) : """Writes a list of flow requests to the database ."""
args = [ ] templates = [ ] flow_keys = [ ] needs_processing = { } for r in requests : if r . needs_processing : needs_processing . setdefault ( ( r . client_id , r . flow_id ) , [ ] ) . append ( r ) flow_keys . append ( ( r . client_id , r . flow_id ) ) templates . append ( "(%s, %s, %s, %s, %s)" ) ...
def _format_id ( ns , id ) : """Format a namespace / ID pair for display and curation ."""
label = '%s:%s' % ( ns , id ) label = label . replace ( ' ' , '_' ) url = get_identifiers_url ( ns , id ) return ( label , url )
def _accept_as_blank ( self , url_info : URLInfo ) : '''Mark the URL as OK in the pool .'''
_logger . debug ( __ ( 'Got empty robots.txt for {0}.' , url_info . url ) ) self . _robots_txt_pool . load_robots_txt ( url_info , '' )
def getTamilWords ( tweet ) : """" word needs to all be in the same tamil language"""
tweet = TamilTweetParser . cleanupPunct ( tweet ) ; nonETwords = filter ( lambda x : len ( x ) > 0 , re . split ( r'\s+' , tweet ) ) ; tamilWords = filter ( TamilTweetParser . isTamilPredicate , nonETwords ) ; return tamilWords
def simulate_values ( cls , num_events , ** scheduler_kwargs ) : """Method to simulate scheduled values during num _ events events . Args : num _ events ( int ) : number of events during the simulation . * * scheduler _ kwargs : parameter scheduler configuration kwargs . Returns : list of pairs : [ event ...
keys_to_remove = [ 'optimizer' , 'save_history' ] for key in keys_to_remove : if key in scheduler_kwargs : del scheduler_kwargs [ key ] values = [ ] scheduler = cls ( optimizer = { } , save_history = False , ** scheduler_kwargs ) for i in range ( num_events ) : scheduler ( engine = None ) values . a...
def referenceframe ( self , event ) : """Handles navigational reference frame updates . These are necessary to assign geo coordinates to alerts and other misc things . : param event with incoming referenceframe message"""
self . log ( "Got a reference frame update! " , event , lvl = events ) self . reference_frame = event . data
def getcwd ( cls ) : """Provide a context dependent current working directory . This method will return the directory currently holding the lock ."""
if not hasattr ( cls . _tl , "cwd" ) : cls . _tl . cwd = os . getcwd ( ) return cls . _tl . cwd
def get_value ( prompt , default = None , hidden = False ) : '''Displays the provided prompt and returns the input from the user . If the user hits Enter and there is a default value provided , the default is returned .'''
_prompt = '%s : ' % prompt if default : _prompt = '%s [%s]: ' % ( prompt , default ) if hidden : ans = getpass ( _prompt ) else : ans = raw_input ( _prompt ) # If user hit Enter and there is a default value if not ans and default : ans = default return ans
def popitem ( self , last = True ) : '''od . popitem ( ) - > ( k , v ) , return and remove a ( key , value ) pair . Pairs are returned in LIFO order if last is true or FIFO order if false .'''
if not self : raise KeyError ( 'dictionary is empty' ) root = self . __root if last : link = root . prev link_prev = link . prev link_prev . next = root root . prev = link_prev else : link = root . next link_next = link . next root . next = link_next link_next . prev = root key = lin...
def get_key_section_header ( self , key , spaces ) : """Get the key of the section header : param key : the key name : param spaces : spaces to set at the beginning of the header"""
header = super ( GoogledocTools , self ) . get_key_section_header ( key , spaces ) header = spaces + header + ':' + '\n' return header
def requirement_spec ( package_name , * args ) : """Identifier used when specifying a requirement to pip or setuptools ."""
if not args or args == ( None , ) : return package_name version_specs = [ ] for version_spec in args : if isinstance ( version_spec , ( list , tuple ) ) : operator , version = version_spec else : assert isinstance ( version_spec , str ) operator = "==" version = version_spec ...
def xml2dict ( xml , sanitize = True , prefix = None ) : """Return XML as dict . > > > xml2dict ( ' < ? xml version = " 1.0 " ? > < root attr = " name " > < key > 1 < / key > < / root > ' ) { ' root ' : { ' key ' : 1 , ' attr ' : ' name ' } }"""
from xml . etree import cElementTree as etree # delayed import at = tx = '' if prefix : at , tx = prefix def astype ( value ) : # return value as int , float , bool , or str for t in ( int , float , asbool ) : try : return t ( value ) except Exception : pass return va...
def turn_on_nightlight ( self ) : """Turn on nightlight"""
body = helpers . req_body ( self . manager , 'devicestatus' ) body [ 'uuid' ] = self . uuid body [ 'mode' ] = 'auto' response , _ = helpers . call_api ( '/15a/v1/device/nightlightstatus' , 'put' , headers = helpers . req_headers ( self . manager ) , json = body ) return helpers . check_response ( response , '15a_ntligh...
def hscan_iter ( self , name , match = None , count = 10 ) : """Emulate hscan _ iter ."""
cursor = '0' while cursor != 0 : cursor , data = self . hscan ( name , cursor = cursor , match = match , count = count ) for item in data . items ( ) : yield item
def set_connection_state ( ) : """Create a new SET _ CONNECTION _ STATE ."""
message = create ( protobuf . ProtocolMessage . SET_CONNECTION_STATE_MESSAGE ) message . inner ( ) . state = protobuf . SetConnectionStateMessage . Connected return message
def missing_nodes ( self ) : """The set of targets known as dependencies but not yet defined ."""
missing = set ( ) for target_addr , target_attrs in self . graph . node . items ( ) : if 'target_obj' not in target_attrs : missing . add ( target_addr ) return missing
def check_and_consume ( self ) : """Returns True if there is currently at least one token , and reduces it by one ."""
if self . _count < 1.0 : self . _fill ( ) consumable = self . _count >= 1.0 if consumable : self . _count -= 1.0 self . throttle_count = 0 else : self . throttle_count += 1 return consumable
async def dispatch_websocket ( self , websocket_context : Optional [ WebsocketContext ] = None , ) -> None : """Dispatch the websocket to the view function . Arguments : websocket _ context : The websocket context , optional to match the Flask convention ."""
websocket_ = ( websocket_context or _websocket_ctx_stack . top ) . websocket if websocket_ . routing_exception is not None : raise websocket_ . routing_exception handler = self . view_functions [ websocket_ . url_rule . endpoint ] return await handler ( ** websocket_ . view_args )
def update_input_endpoint ( kwargs = None , conn = None , call = None , activity = 'update' ) : '''. . versionadded : : 2015.8.0 Update an input endpoint associated with the deployment . Please note that there may be a delay before the changes show up . CLI Example : . . code - block : : bash salt - cloud...
if call != 'function' : raise SaltCloudSystemExit ( 'The update_input_endpoint function must be called with -f or --function.' ) if kwargs is None : kwargs = { } if 'service' not in kwargs : raise SaltCloudSystemExit ( 'A service name must be specified as "service"' ) if 'deployment' not in kwargs : rai...
def resource_names ( self , repo_type ) : """Names of resources used to store the format on a given repository type . Defaults to the name of the name of the format"""
try : names = self . _resource_names [ repo_type ] except KeyError : names = [ self . name , self . name . upper ( ) ] return names
def _pcca_connected_isa ( evec , n_clusters ) : """PCCA + spectral clustering method using the inner simplex algorithm . Clusters the first n _ cluster eigenvectors of a transition matrix in order to cluster the states . This function assumes that the state space is fully connected , i . e . the transition matr...
( n , m ) = evec . shape # do we have enough eigenvectors ? if n_clusters > m : raise ValueError ( "Cannot cluster the (" + str ( n ) + " x " + str ( m ) + " eigenvector matrix to " + str ( n_clusters ) + " clusters." ) # check if the first , and only the first eigenvector is constant diffs = np . abs ( np . max ( ...
def active ( display_progress = False ) : '''Return a report on all actively running jobs from a job id centric perspective CLI Example : . . code - block : : bash salt - run jobs . active'''
ret = { } client = salt . client . get_local_client ( __opts__ [ 'conf_file' ] ) try : active_ = client . cmd ( '*' , 'saltutil.running' , timeout = __opts__ [ 'timeout' ] ) except SaltClientError as client_error : print ( client_error ) return ret if display_progress : __jid_event__ . fire_event ( { 'm...
def delete_area ( self , area_uuid ) : """Delete an Upload Area : param str area _ uuid : A RFC4122 - compliant ID for the upload area : return : True : rtype : bool : raises UploadApiException : if the an Upload Area was not deleted"""
self . _make_request ( 'delete' , path = "/area/{id}" . format ( id = area_uuid ) , headers = { 'Api-Key' : self . auth_token } ) return True
def add_request_handlers_object ( self , rh_obj ) : """Add fake request handlers from an object with request _ * method ( s ) See : meth : ` FakeInspectingClientManager . add _ request _ handlers _ dict ` for more detail ."""
rh_dict = { } for name in dir ( rh_obj ) : if not callable ( getattr ( rh_obj , name ) ) : continue if name . startswith ( "request_" ) : request_name = convert_method_name ( "request_" , name ) req_meth = getattr ( rh_obj , name ) rh_dict [ request_name ] = req_meth self . add_r...
def build_operation ( operation , ns , rule , func ) : """Build an operation definition ."""
swagger_operation = swagger . Operation ( operationId = operation_name ( operation , ns ) , parameters = swagger . ParametersList ( [ ] ) , responses = swagger . Responses ( ) , tags = [ ns . subject_name ] , ) # custom header parameter swagger_operation . parameters . append ( header_param ( "X-Response-Skip-Null" ) )...
def get_fwhm ( self , x , y , radius , data , medv = None , method_name = 'gaussian' ) : """Get the FWHM value of the object at the coordinates ( x , y ) using radius ."""
if medv is None : medv = get_median ( data ) # Get two cuts of the data , one in X and one in Y x0 , y0 , xarr , yarr = self . cut_cross ( x , y , radius , data ) # Calculate FWHM in each direction x_res = self . calc_fwhm ( xarr , medv = medv , method_name = method_name ) fwhm_x , cx = x_res . fwhm , x_res . mu y_...
def add_factors ( self , * factors ) : """Associate a factor to the graph . See factors class for the order of potential values Parameters * factor : pgmpy . factors . factors object A factor object on any subset of the variables of the model which is to be associated with the model . Returns None E...
for factor in factors : if set ( factor . variables ) - set ( factor . variables ) . intersection ( set ( self . nodes ( ) ) ) : raise ValueError ( "Factors defined on variable not in the model" , factor ) self . factors . append ( factor )
def _node_digest ( self ) -> Dict [ str , Any ] : """Return dictionary of receiver ' s properties suitable for clients ."""
res = { "kind" : self . _yang_class ( ) } if self . mandatory : res [ "mandatory" ] = True if self . description : res [ "description" ] = self . description return res
def create_url_adapter ( self , request : Optional [ BaseRequestWebsocket ] ) -> Optional [ MapAdapter ] : """Create and return a URL adapter . This will create the adapter based on the request if present otherwise the app configuration ."""
if request is not None : host = request . host return self . url_map . bind_to_request ( request . scheme , host , request . method , request . path , request . query_string , ) if self . config [ 'SERVER_NAME' ] is not None : return self . url_map . bind ( self . config [ 'PREFERRED_URL_SCHEME' ] , self . ...
def get_note ( self , noteid , version = None ) : """Method to get a specific note Arguments : - noteid ( string ) : ID of the note to get - version ( int ) : optional version of the note to get Returns : A tuple ` ( note , status ) ` - note ( dict ) : note object - status ( int ) : 0 on success and -...
# request note params_version = "" if version is not None : params_version = '/v/' + str ( version ) params = '/i/%s%s' % ( str ( noteid ) , params_version ) request = Request ( DATA_URL + params ) request . add_header ( self . header , self . get_token ( ) ) try : response = urllib2 . urlopen ( request ) excep...
def mark_nonreturning_calls_endpoints ( self ) : """Iterate through all call edges in transition graph . For each call a non - returning function , mark the source basic block as an endpoint . This method should only be executed once all functions are recovered and analyzed by CFG recovery , so we know whethe...
for src , dst , data in self . transition_graph . edges ( data = True ) : if 'type' in data and data [ 'type' ] == 'call' : func_addr = dst . addr if func_addr in self . _function_manager : function = self . _function_manager [ func_addr ] if function . returning is False : #...
def parse_dbus_address ( address ) : """Parse a D - BUS address string into a list of addresses ."""
if address == 'session' : address = os . environ . get ( 'DBUS_SESSION_BUS_ADDRESS' ) if not address : raise ValueError ( '$DBUS_SESSION_BUS_ADDRESS not set' ) elif address == 'system' : address = os . environ . get ( 'DBUS_SYSTEM_BUS_ADDRESS' , 'unix:path=/var/run/dbus/system_bus_socket' ) addresse...
def generate_stop_word_filter ( stop_words , language = None ) : """Builds a stopWordFilter function from the provided list of stop words . The built in ` stop _ word _ filter ` is built using this factory and can be used to generate custom ` stop _ word _ filter ` for applications or non English languages ."...
def stop_word_filter ( token , i = None , tokens = None ) : if token and str ( token ) not in stop_words : return token # camelCased for for compatibility with lunr . js label = ( "stopWordFilter-{}" . format ( language ) if language is not None else "stopWordFilter" ) Pipeline . register_function ( stop_wo...
def get_norm ( self ) : """Return square length : x * x + y * y ."""
return self . x * self . x + self . y * self . y
def encode_metadata_request ( cls , topics = ( ) , payloads = None ) : """Encode a MetadataRequest Arguments : topics : list of strings"""
if payloads is not None : topics = payloads return kafka . protocol . metadata . MetadataRequest [ 0 ] ( topics )
def add_node ( self , node_id , task , inputs ) : """Adds a node to the workflow . : param node _ id : A unique identifier for the new node . : param task : The task to run . : param inputs : A mapping of inputs from workflow inputs , or outputs from other nodes . The format should be ` { input _ name : ( s...
if node_id in self . nodes_by_id : raise ValueError ( 'The node {0} already exists in this workflow.' . format ( node_id ) ) node = WorkflowNode ( node_id , task , inputs ) self . nodes_by_id [ node_id ] = node for source , value in six . itervalues ( inputs ) : if source == 'dependency' : dependents = ...
def resample ( self , resampledWaveTab ) : """Resample the spectrum for the given wavelength set . Given wavelength array must be monotonically increasing or decreasing . Parameters resampledWaveTab : array _ like Wavelength set for resampling . Returns resampled : ` ArraySpectralElement ` Resampled s...
return ArraySpectralElement ( wave = resampledWaveTab . copy ( ) , waveunits = 'angstrom' , throughput = self ( resampledWaveTab ) . copy ( ) )
def avail_images ( call = None ) : '''Return a list of the images that are on the provider .'''
if call == 'action' : raise SaltCloudSystemExit ( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) items = query ( method = 'images' , root = 'marketplace_root' ) ret = { } for image in items [ 'images' ] : ret [ image [ 'id' ] ] = { } for item in image...
def register ( self , CorpNum , cashbill , UserID = None ) : """현금영수증 등록 args CorpNum : 팝빌회원 사업자번호 cashbill : 등록할 현금영수증 object . made with Cashbill ( . . . ) UserID : 팝빌회원 아이디 return 처리결과 . consist of code and message raise PopbillException"""
if cashbill == None : raise PopbillException ( - 99999999 , "현금영수증 정보가 입력되지 않았습니다." ) postData = self . _stringtify ( cashbill ) return self . _httppost ( '/Cashbill' , postData , CorpNum , UserID )
def principal_inertia_components ( self ) : """Return the principal components of inertia Ordering corresponds to mesh . principal _ inertia _ vectors Returns components : ( 3 , ) float Principal components of inertia"""
# both components and vectors from inertia matrix components , vectors = inertia . principal_axis ( self . moment_inertia ) # store vectors in cache for later self . _cache [ 'principal_inertia_vectors' ] = vectors return components
def checkOptions ( options , parser ) : """Check options , throw parser . error ( ) if something goes wrong"""
if options . jobStore == None : parser . error ( "Specify --jobStore" ) defaultCategories = [ "time" , "clock" , "wait" , "memory" ] if options . categories is None : options . categories = defaultCategories else : options . categories = [ x . lower ( ) for x in options . categories . split ( "," ) ] for c ...
def render_field ( self , obj , field_name , ** options ) : """Render field"""
try : field = obj . _meta . get_field ( field_name ) except FieldDoesNotExist : return getattr ( obj , field_name , '' ) if hasattr ( field , 'choices' ) and getattr ( field , 'choices' ) : return getattr ( obj , 'get_{}_display' . format ( field_name ) ) ( ) value = getattr ( obj , field_name , '' ) render...
def as_dict ( self ) : """Constructs query params compatible with : class : ` requests . Request ` : return : - Dictionary containing query parameters"""
sysparms = self . _sysparms sysparms . update ( self . _custom_params ) return sysparms
def dumps ( self , obj ) : '''Serialize and encrypt a python object'''
return self . encrypt ( self . PICKLE_PAD + self . serial . dumps ( obj ) )
def get_cookie ( self , * args ) : """Return the ( decoded ) value of a cookie ."""
value = self . COOKIES . get ( * args ) sec = self . app . config [ 'securecookie.key' ] dec = cookie_decode ( value , sec ) return dec or value
def renders ( col_name ) : """Use this decorator to map your custom Model properties to actual Model db properties . As an example : : class MyModel ( Model ) : id = Column ( Integer , primary _ key = True ) name = Column ( String ( 50 ) , unique = True , nullable = False ) custom = Column ( Integer ( 20 ...
def wrap ( f ) : if not hasattr ( f , '_col_name' ) : f . _col_name = col_name return f return wrap
def fail ( self , msg , shutit_pexpect_child = None , throw_exception = False ) : """Handles a failure , pausing if a pexpect child object is passed in . @ param shutit _ pexpect _ child : pexpect child to work on @ param throw _ exception : Whether to throw an exception . @ type throw _ exception : boolean""...
shutit_global . shutit_global_object . yield_to_draw ( ) # Note : we must not default to a child here if shutit_pexpect_child is not None : shutit_pexpect_session = self . get_shutit_pexpect_session_from_child ( shutit_pexpect_child ) shutit_util . print_debug ( sys . exc_info ( ) ) shutit_pexpect_session ....
def update_service_definitions ( self , service_definitions ) : """UpdateServiceDefinitions . [ Preview API ] : param : class : ` < VssJsonCollectionWrapper > < azure . devops . v5_0 . location . models . VssJsonCollectionWrapper > ` service _ definitions :"""
content = self . _serialize . body ( service_definitions , 'VssJsonCollectionWrapper' ) self . _send ( http_method = 'PATCH' , location_id = 'd810a47d-f4f4-4a62-a03f-fa1860585c4c' , version = '5.0-preview.1' , content = content )
def create_table ( unique_keys ) : """Save the table currently waiting to be created ."""
_State . new_transaction ( ) _State . table . create ( bind = _State . engine , checkfirst = True ) if unique_keys != [ ] : create_index ( unique_keys , unique = True ) _State . table_pending = False _State . reflect_metadata ( )