signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def delete_column ( self , id_or_name ) : """Deletes a Column by its id or name : param id _ or _ name : the id or name of the column : return bool : Success or Failure"""
url = self . build_url ( self . _endpoints . get ( 'delete_column' ) . format ( id = quote ( id_or_name ) ) ) return bool ( self . session . post ( url ) )
def get ( self ) : """Get a JSON - ready representation of this TrackingSettings . : returns : This TrackingSettings , ready for use in a request body . : rtype : dict"""
tracking_settings = { } if self . click_tracking is not None : tracking_settings [ "click_tracking" ] = self . click_tracking . get ( ) if self . open_tracking is not None : tracking_settings [ "open_tracking" ] = self . open_tracking . get ( ) if self . subscription_tracking is not None : tracking_settings...
def gen_pager ( self , kind , cat_slug , page_num , current ) : '''cat _ slug 分类 page _ num 页面总数 current 当前页面'''
if page_num == 1 : return '' pager_shouye = '''<li class="{0}"> <a href="/label/{1}/{2}">&lt;&lt; 首页</a> </li>''' . format ( 'hidden' if current <= 1 else '' , kind , cat_slug ) pager_pre = '''<li class="{0}"><a href="/label/{1}/{2}/{3}">&lt; 前页</a> </li>''' . format ( 'hidden' if current <= 1 els...
def run ( self , input_fname , ids_per_job , stagger = 0 , ** wait_params ) : """Run this submission all the way . This method will run both ` submit _ reading ` and ` watch _ and _ wait ` , blocking on the latter ."""
submit_thread = Thread ( target = self . submit_reading , args = ( input_fname , 0 , None , ids_per_job ) , kwargs = { 'stagger' : stagger } , daemon = True ) submit_thread . start ( ) self . watch_and_wait ( ** wait_params ) submit_thread . join ( 0 ) if submit_thread . is_alive ( ) : logger . warning ( "Submit th...
def findFrequentSequentialPatterns ( self , dataset ) : """. . note : : Experimental Finds the complete set of frequent sequential patterns in the input sequences of itemsets . : param dataset : A dataframe containing a sequence column which is ` ArrayType ( ArrayType ( T ) ) ` type , T is the item type for t...
self . _transfer_params_to_java ( ) jdf = self . _java_obj . findFrequentSequentialPatterns ( dataset . _jdf ) return DataFrame ( jdf , dataset . sql_ctx )
def _get_access_token ( self , verifier = None ) : """Fetch an access token from ` self . access _ token _ url ` ."""
response , content = self . client ( verifier ) . request ( self . access_token_url , "POST" ) content = smart_unicode ( content ) if not response [ 'status' ] == '200' : raise OAuthError ( _ ( u"Invalid status code %s while obtaining access token from %s: %s" ) % ( response [ 'status' ] , self . access_token_url ,...
def _get_column_by_db_name ( cls , name ) : """Returns the column , mapped by db _ field name"""
return cls . _columns . get ( cls . _db_map . get ( name , name ) )
def normalize_cert_dir ( ) : '''Put old cerfificate form to new one'''
current_cn = get_crt_common_name ( ) if not os . path . isdir ( COZY_CONFIG_PATH ) : print 'Need to create {}' . format ( COZY_CONFIG_PATH ) os . mkdir ( COZY_CONFIG_PATH , 0755 ) if not os . path . isdir ( CERTIFICATES_PATH ) : print 'Need to create {}' . format ( CERTIFICATES_PATH ) os . mkdir ( CERTI...
def receiver ( self , func = None , json = False ) : """Registers a receiver function"""
self . receivers . append ( ( func , json ) )
def _parse_target ( target ) : """Parse a binary targeting information structure . This function only supports extracting the slot number or controller from the target and will raise an ArgumentError if more complicated targeting is desired . Args : target ( bytes ) : The binary targeting data blob . Re...
if len ( target ) != 8 : raise ArgumentError ( "Invalid targeting data length" , expected = 8 , length = len ( target ) ) slot , match_op = struct . unpack ( "<B6xB" , target ) if match_op == _MATCH_CONTROLLER : return { 'controller' : True , 'slot' : 0 } elif match_op == _MATCH_SLOT : return { 'controller'...
def run_spyder ( app , options , args ) : """Create and show Spyder ' s main window Start QApplication event loop"""
# TODO : insert here # Main window main = MainWindow ( options ) try : main . setup ( ) except BaseException : if main . console is not None : try : main . console . shell . exit_interpreter ( ) except BaseException : pass raise main . show ( ) main . post_visible_set...
def save_if_changed ( self , cancelable = False , index = None ) : """Ask user to save file if modified . Args : cancelable : Show Cancel button . index : File to check for modification . Returns : False when save ( ) fails or is cancelled . True when save ( ) is successful , there are no modifications ...
if index is None : indexes = list ( range ( self . get_stack_count ( ) ) ) else : indexes = [ index ] buttons = QMessageBox . Yes | QMessageBox . No if cancelable : buttons |= QMessageBox . Cancel unsaved_nb = 0 for index in indexes : if self . data [ index ] . editor . document ( ) . isModified ( ) : ...
def create ( cls , name , datacenter , backends , vhosts , algorithm , ssl_enable , zone_alter ) : """Create a webaccelerator"""
datacenter_id_ = int ( Datacenter . usable_id ( datacenter ) ) params = { 'datacenter_id' : datacenter_id_ , 'name' : name , 'lb' : { 'algorithm' : algorithm } , 'override' : True , 'ssl_enable' : ssl_enable , 'zone_alter' : zone_alter } if vhosts : params [ 'vhosts' ] = vhosts if backends : params [ 'servers' ...
def _parse_output ( self , output_xml ) : """Parses an output , which is generally a switch controlling a set of lights / outlets , etc ."""
output = Output ( self . _lutron , name = output_xml . get ( 'Name' ) , watts = int ( output_xml . get ( 'Wattage' ) ) , output_type = output_xml . get ( 'OutputType' ) , integration_id = int ( output_xml . get ( 'IntegrationID' ) ) ) return output
def _resolve_looppart ( parts , assign_path , context ) : """recursive function to resolve multiple assignments on loops"""
assign_path = assign_path [ : ] index = assign_path . pop ( 0 ) for part in parts : if part is util . Uninferable : continue if not hasattr ( part , "itered" ) : continue try : itered = part . itered ( ) except TypeError : continue for stmt in itered : index_n...
def kill_given_tasks ( self , task_ids , scale = False , force = None ) : """Kill a list of given tasks . : param list [ str ] task _ ids : tasks to kill : param bool scale : if true , scale down the app by the number of tasks killed : param bool force : if true , ignore any current running deployments : re...
params = { 'scale' : scale } if force is not None : params [ 'force' ] = force data = json . dumps ( { "ids" : task_ids } ) response = self . _do_request ( 'POST' , '/v2/tasks/delete' , params = params , data = data ) return response == 200
def return_item_count_on_subpage ( self , subpage = 1 , total_items = 1 ) : """Return the number of items on page . Args : * page = The Page to test for * total _ items = the total item count Returns : * Integer - Which represents the calculated number of items on page ."""
up_to_subpage = ( ( subpage - 1 ) * self . subpage_items ) # Number of items up to the page in question if total_items > up_to_subpage : # Remove all the items up to the page in question count = total_items - up_to_subpage else : count = total_items if count >= self . subpage_items : # The remaining items are g...
def weave ( * iterables ) : r"""weave ( seq1 [ , seq2 ] [ . . . ] ) - > iter ( [ seq1[0 ] , seq2[0 ] . . . ] ) . > > > list ( weave ( [ 1,2,3 ] , [ 4,5,6 , ' A ' ] , [ 6,7,8 , ' B ' , ' C ' ] ) ) [1 , 4 , 6 , 2 , 5 , 7 , 3 , 6 , 8] Any iterable will work . The first exhausted iterable determines when to sto...
iterables = map ( iter , iterables ) while True : for it in iterables : yield it . next ( )
def create_collection ( cls , collection , ** kwargs ) : """Create Collection Create a new Collection This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async = True > > > thread = api . create _ collection ( collection , async = True ) > > > resul...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async' ) : return cls . _create_collection_with_http_info ( collection , ** kwargs ) else : ( data ) = cls . _create_collection_with_http_info ( collection , ** kwargs ) return data
def filter_significance ( diff , significance ) : """Prune any changes in the patch which are due to numeric changes less than this level of significance ."""
changed = diff [ 'changed' ] # remove individual field changes that are significant reduced = [ { 'key' : delta [ 'key' ] , 'fields' : { k : v for k , v in delta [ 'fields' ] . items ( ) if _is_significant ( v , significance ) } } for delta in changed ] # call a key changed only if it still has significant changes filt...
def build_input ( data , batch_size , dataset , train ) : """Build CIFAR image and labels . Args : data _ path : Filename for cifar10 data . batch _ size : Input batch size . train : True if we are training and false if we are testing . Returns : images : Batches of images of size [ batch _ size , ima...
image_size = 32 depth = 3 num_classes = 10 if dataset == "cifar10" else 100 images , labels = data num_samples = images . shape [ 0 ] - images . shape [ 0 ] % batch_size dataset = tf . contrib . data . Dataset . from_tensor_slices ( ( images [ : num_samples ] , labels [ : num_samples ] ) ) def map_train ( image , label...
def get_metadata ( main_file ) : """Get metadata about the package / module . Positional arguments : main _ file - - python file path within ` HERE ` which has _ _ author _ _ and the others defined as global variables . Returns : Dictionary to be passed into setuptools . setup ( ) ."""
with open ( os . path . join ( HERE , 'README.md' ) , encoding = 'utf-8' ) as f : long_description = f . read ( ) with open ( os . path . join ( HERE , main_file ) , encoding = 'utf-8' ) as f : lines = [ l . strip ( ) for l in f if l . startswith ( '__' ) ] metadata = ast . literal_eval ( "{'" + ", '" . join ( ...
def _generate_event_doc ( event ) : '''Create a object that will be saved into the database based in options .'''
# Create a copy of the object that we will return . eventc = event . copy ( ) # Set the ID of the document to be the JID . eventc [ "_id" ] = '{}-{}' . format ( event . get ( 'tag' , '' ) . split ( '/' ) [ 2 ] , event . get ( 'tag' , '' ) . split ( '/' ) [ 3 ] ) # Add a timestamp field to the document eventc [ "timesta...
def fail ( self , message = None , force_exit = False ) : """Marks the job as failed , saves the given error message and force exists the process when force _ exit = True ."""
global last_exit_code if not last_exit_code : last_exit_code = 1 with self . git . batch_commit ( 'FAILED' ) : self . set_status ( 'FAILED' , add_section = False ) self . git . commit_json_file ( 'FAIL_MESSAGE' , 'aetros/job/crash/error' , str ( message ) if message else '' ) if isinstance ( sys . stder...
def build_tree ( self ) : """Build chaid tree"""
self . _tree_store = [ ] self . node ( np . arange ( 0 , self . data_size , dtype = np . int ) , self . vectorised_array , self . observed )
def with_user_roles ( roles ) : """with _ user _ roles ( roles ) It allows to check if a user has access to a view by adding the decorator with _ user _ roles ( [ ] ) Requires flask - login In your model , you must have a property ' role ' , which will be invoked to be compared to the roles provided . I...
def wrapper ( f ) : @ functools . wraps ( f ) def wrapped ( * args , ** kwargs ) : if current_user . is_authenticated ( ) : if not hasattr ( current_user , "role" ) : raise AttributeError ( "<'role'> doesn't exist in login 'current_user'" ) if current_user . role ...
def border ( self , L ) : """Append to L the border of the subtree ."""
if self . shape == L_shape : L . append ( self . value ) else : for x in self . sons : x . border ( L )
def get_transcript ( self , exon_bounds = 'max' ) : """Return a representative transcript object"""
out = Transcript ( ) out . junctions = [ x . get_junction ( ) for x in self . junction_groups ] # check for single exon transcript if len ( out . junctions ) == 0 : leftcoord = min ( [ x . exons [ 0 ] . range . start for x in self . transcripts ] ) rightcoord = max ( [ x . exons [ - 1 ] . range . end for x in s...
def _write_adminfile ( kwargs ) : '''Create a temporary adminfile based on the keyword arguments passed to pkg . install .'''
# Set the adminfile default variables email = kwargs . get ( 'email' , '' ) instance = kwargs . get ( 'instance' , 'quit' ) partial = kwargs . get ( 'partial' , 'nocheck' ) runlevel = kwargs . get ( 'runlevel' , 'nocheck' ) idepend = kwargs . get ( 'idepend' , 'nocheck' ) rdepend = kwargs . get ( 'rdepend' , 'nocheck' ...
def deserialize_bitarray ( ser ) : # type : ( str ) - > bitarray """Deserialize a base 64 encoded string to a bitarray ( bloomfilter )"""
ba = bitarray ( ) ba . frombytes ( base64 . b64decode ( ser . encode ( encoding = 'UTF-8' , errors = 'strict' ) ) ) return ba
def detect_cloud ( ) -> str : '''Detect the cloud provider where I am running on .'''
# NOTE : Contributions are welcome ! # Please add other cloud providers such as Rackspace , IBM BlueMix , etc . if sys . platform . startswith ( 'linux' ) : # Google Cloud Platform or Amazon AWS ( hvm ) try : # AWS Nitro - based instances mb = Path ( '/sys/devices/virtual/dmi/id/board_vendor' ) . read_text ...
def valid_totp ( token , secret , digest_method = hashlib . sha1 , token_length = 6 , interval_length = 30 , clock = None , window = 0 , ) : """Check if given token is valid time - based one - time password for given secret . : param token : token which is being checked : type token : int or str : param sec...
if _is_possible_token ( token , token_length = token_length ) : if clock is None : clock = time . time ( ) for w in range ( - window , window + 1 ) : if int ( token ) == get_totp ( secret , digest_method = digest_method , token_length = token_length , interval_length = interval_length , clock = ...
def pbf ( self , bbox , geo_col = None , scale = 4096 ) : """Returns tranlated and scaled geometries suitable for Mapbox vector tiles ."""
col = geo_col or self . geo_field . name w , s , e , n = bbox . extent trans = self . _trans_scale ( col , - w , - s , scale / ( e - w ) , scale / ( n - s ) ) g = AsText ( trans ) return self . annotate ( pbf = g )
def _get_parsimonious_model ( models ) : """Return the most parsimonious model of all available models . The most parsimonious model is defined as the model with the fewest number of parameters ."""
params = [ len ( model . output [ "parameters" ] ) for model in models ] idx = params . index ( min ( params ) ) return models [ idx ]
def always_fails ( self , work_dict ) : """always _ fails : param work _ dict : dictionary for key / values"""
label = "always_fails" log . info ( ( "task - {} - start " "work_dict={}" ) . format ( label , work_dict ) ) raise Exception ( work_dict . get ( "test_failure" , "simulating a failure" ) ) log . info ( ( "task - {} - done" ) . format ( label ) ) return True
def send ( self , obj , encoding = 'utf-8' ) : """Sends a python object to the backend . The object * * must be JSON serialisable * * . : param obj : object to send : param encoding : encoding used to encode the json message into a bytes array , this should match CodeEdit . file . encoding ."""
comm ( 'sending request: %r' , obj ) msg = json . dumps ( obj ) msg = msg . encode ( encoding ) header = struct . pack ( '=I' , len ( msg ) ) self . write ( header ) self . write ( msg )
def print_extended_help ( ) : """Prints an extended help message ."""
# initiate TextWrapper class , which will handle all of the string formatting w = textwrap . TextWrapper ( ) w . expand_tabs = False w . width = 110 w . initial_indent = ' ' w . subsequent_indent = ' ' print ( '' ) print ( textwrap . fill ( "<split> Complete parameter list:" , initial_indent = '' ) ) print ( ''...
def refresh ( self ) : """Update this ItemList by re - downloading it from the server : rtype : ItemList : returns : this ItemList , after the refresh : raises : APIError if the API request is not successful"""
refreshed = self . client . get_item_list ( self . url ( ) ) self . item_urls = refreshed . urls ( ) self . list_name = refreshed . name ( ) return self
def _parse_packet ( rawdata ) : """Returns a tupel ( opcode , minusconf - data ) . opcode is None if this isn ' t a - conf packet ."""
if ( len ( rawdata ) < len ( _MAGIC ) + 1 ) or ( _MAGIC != rawdata [ : len ( _MAGIC ) ] ) : # Wrong protocol return ( None , None ) opcode = rawdata [ len ( _MAGIC ) : len ( _MAGIC ) + 1 ] payload = rawdata [ len ( _MAGIC ) + 1 : ] return ( opcode , payload )
def _create_rule ( rule , index , backtrack ) : # type : ( Rule , int , Dict [ Type [ Nonterminal ] , Type [ Rule ] ] ) - > Type [ EpsilonRemovedRule ] """Create EpsilonRemovedRule . This rule will skip symbol at the ` index ` . : param rule : Original rule . : param index : Index of symbol that is rewritable t...
# remove old rules from the dictionary old_dict = rule . __dict__ . copy ( ) if 'rules' in old_dict : del old_dict [ 'rules' ] if 'rule' in old_dict : del old_dict [ 'rule' ] if 'left' in old_dict : del old_dict [ 'left' ] if 'right' in old_dict : del old_dict [ 'right' ] if 'fromSymbol' in old_dict : ...
def choose_path ( ) : """Invoke a folder selection dialog here : return :"""
dirs = webview . create_file_dialog ( webview . FOLDER_DIALOG ) if dirs and len ( dirs ) > 0 : directory = dirs [ 0 ] if isinstance ( directory , bytes ) : directory = directory . decode ( "utf-8" ) response = { "status" : "ok" , "directory" : directory } else : response = { "status" : "cancel" ...
def filter ( self , value = None , model = None , context = None ) : """Sequentially applies all the filters to provided value : param value : a value to filter : param model : parent entity : param context : filtering context , usually parent entity : return : filtered value"""
if value is None : return value for filter_obj in self . filters : value = filter_obj . filter ( value = value , model = model , context = context if self . use_context else None ) return value
def auth ( username , password ) : '''REST authentication'''
url = rest_auth_setup ( ) data = { 'username' : username , 'password' : password } # Post to the API endpoint . If 200 is returned then the result will be the ACLs # for this user result = salt . utils . http . query ( url , method = 'POST' , data = data , status = True , decode = True ) if result [ 'status' ] == 200 :...
def get_execution_engine ( name ) : """Get the execution engine by name ."""
manager = driver . DriverManager ( namespace = 'cosmic_ray.execution_engines' , name = name , invoke_on_load = True , on_load_failure_callback = _log_extension_loading_failure , ) return manager . driver
def extract_command ( outputdir , domain_methods , text_domain , keywords , comment_tags , base_dir , project , version , msgid_bugs_address ) : """Extracts strings into . pot files : arg domain : domains to generate strings for or ' all ' for all domains : arg outputdir : output dir for . pot files ; usually ...
# Must monkeypatch first to fix i18n extensions stomping issues ! monkeypatch_i18n ( ) # Create the outputdir if it doesn ' t exist outputdir = os . path . abspath ( outputdir ) if not os . path . isdir ( outputdir ) : print ( 'Creating output dir %s ...' % outputdir ) os . makedirs ( outputdir ) domains = doma...
def _create_from_java_class ( cls , java_class , * args ) : """Construct this object from given Java classname and arguments"""
java_obj = JavaWrapper . _new_java_obj ( java_class , * args ) return cls ( java_obj )
def _transfer_result ( fut1 , fut2 ) : """Helper to transfer result or errors from one Future to another ."""
exc = fut1 . get_exception ( ) if exc is not None : tb = fut1 . get_traceback ( ) fut2 . set_exception ( exc , tb ) else : val = fut1 . get_result ( ) fut2 . set_result ( val )
def dot ( self , y , t = None , A = None , U = None , V = None , kernel = None , check_sorted = True ) : """Dot the covariance matrix into a vector or matrix Compute ` ` K . y ` ` where ` ` K ` ` is the covariance matrix of the GP without the white noise or ` ` yerr ` ` values on the diagonal . Args : y ( a...
if kernel is None : kernel = self . kernel if t is not None : t = np . atleast_1d ( t ) if check_sorted and np . any ( np . diff ( t ) < 0.0 ) : raise ValueError ( "the input coordinates must be sorted" ) if check_sorted and len ( t . shape ) > 1 : raise ValueError ( "dimension mismatch"...
def resume_service ( name ) : """Resume the service given by name . @ warn : This method requires UAC elevation in Windows Vista and above . @ note : Not all services support this . @ see : L { get _ services } , L { get _ active _ services } , L { start _ service } , L { stop _ service } , L { pause _ serv...
with win32 . OpenSCManager ( dwDesiredAccess = win32 . SC_MANAGER_CONNECT ) as hSCManager : with win32 . OpenService ( hSCManager , name , dwDesiredAccess = win32 . SERVICE_PAUSE_CONTINUE ) as hService : win32 . ControlService ( hService , win32 . SERVICE_CONTROL_CONTINUE )
def run_job ( key , node ) : """Run a job . This applies the function node , and returns a | ResultMessage | when complete . If an exception is raised in the job , the | ResultMessage | will have ` ` ' error ' ` ` status . . . | run _ job | replace : : : py : func : ` run _ job `"""
try : result = node . apply ( ) return ResultMessage ( key , 'done' , result , None ) except Exception as exc : return ResultMessage ( key , 'error' , None , exc )
def message_search ( self , text , on_success , peer = None , min_date = None , max_date = None , max_id = None , offset = 0 , limit = 255 ) : """Unsupported in the Bot API"""
raise TWXUnsupportedMethod ( )
def email ( self ) : """User email ( s )"""
try : return self . parser . get ( "general" , "email" ) except NoSectionError as error : log . debug ( error ) raise ConfigFileError ( "No general section found in the config file." ) except NoOptionError as error : log . debug ( error ) raise ConfigFileError ( "No email address defined in the conf...
def parameter_present ( name , db_parameter_group_family , description , parameters = None , apply_method = "pending-reboot" , tags = None , region = None , key = None , keyid = None , profile = None ) : '''Ensure DB parameter group exists and update parameters . name The name for the parameter group . db _ p...
ret = { 'name' : name , 'result' : True , 'comment' : '' , 'changes' : { } } res = __salt__ [ 'boto_rds.parameter_group_exists' ] ( name = name , tags = tags , region = region , key = key , keyid = keyid , profile = profile ) if not res . get ( 'exists' ) : if __opts__ [ 'test' ] : ret [ 'comment' ] = 'Para...
def minizinc ( mzn , * dzn_files , args = None , data = None , include = None , stdlib_dir = None , globals_dir = None , declare_enums = True , allow_multiple_assignments = False , keep = False , output_vars = None , output_base = None , output_mode = 'dict' , solver = None , timeout = None , two_pass = None , pre_pass...
mzn_file , dzn_files , data_file , data , keep , _output_mode , types = _minizinc_preliminaries ( mzn , * dzn_files , args = args , data = data , include = include , stdlib_dir = stdlib_dir , globals_dir = globals_dir , output_vars = output_vars , keep = keep , output_base = output_base , output_mode = output_mode , de...
def main ( start , end , out ) : """Scrape a MLBAM Data : param start : Start Day ( YYYYMMDD ) : param end : End Day ( YYYYMMDD ) : param out : Output directory ( default : " . . / output / mlb " )"""
try : logging . basicConfig ( level = logging . WARNING ) MlbAm . scrape ( start , end , out ) except MlbAmBadParameter as e : raise click . BadParameter ( e )
def must_contain ( self , value , q , strict = False ) : """if value must contain q"""
if value is not None : if value . find ( q ) != - 1 : return self . shout ( 'Value %r does not contain %r' , strict , value , q )
def success ( request , message , extra_tags = '' , fail_silently = False , async = False ) : """Adds a message with the ` ` SUCCESS ` ` level ."""
if ASYNC and async : messages . success ( _get_user ( request ) , message ) else : add_message ( request , constants . SUCCESS , message , extra_tags = extra_tags , fail_silently = fail_silently )
def create_index_table ( environ , envdir ) : '''create an html table Parameters : environ ( dict ) : A tree environment dictionary envdir ( str ) : The filepath for the env directory Returns : An html table definition string'''
table_header = """<table id="list" cellpadding="0.1em" cellspacing="0"> <colgroup><col width="55%"/><col width="20%"/><col width="25%"/></colgroup> <thead> <tr><th><a href="?C=N&O=A">File Name</a>&nbsp;<a href="?C=N&O=D">&nbsp;&darr;&nbsp;</a></th><th><a href="?C=S&O=A">File Size</a>&nbsp;<a href="?C=S&O=D">&nbsp;&...
def send_password_changed_email ( self , user ) : """Send the ' password has changed ' notification email ."""
# Verify config settings if not self . user_manager . USER_ENABLE_EMAIL : return if not self . user_manager . USER_SEND_PASSWORD_CHANGED_EMAIL : return # Notification emails are sent to the user ' s primary email address user_or_user_email_object = self . user_manager . db_manager . get_primary_user_email_objec...
def register_factory ( self , key , factory = _sentinel , scope = NoneScope , allow_overwrite = False ) : '''Creates and registers a provider using the given key , factory , and scope . Can also be used as a decorator . : param key : Provider key : type key : object : param factory : Factory callable : ty...
if factory is _sentinel : return functools . partial ( self . register_factory , key , scope = scope , allow_overwrite = allow_overwrite ) if not allow_overwrite and key in self . _providers : raise KeyError ( "Key %s already exists" % key ) provider = self . provider ( factory , scope ) self . _providers [ key...
def folder_create ( self , foldername = None , parent_key = None , action_on_duplicate = None , mtime = None ) : """folder / create http : / / www . mediafire . com / developers / core _ api / 1.3 / folder / # create"""
return self . request ( 'folder/create' , QueryParams ( { 'foldername' : foldername , 'parent_key' : parent_key , 'action_on_duplicate' : action_on_duplicate , 'mtime' : mtime } ) )
def find_frame_urls ( self , site , frametype , gpsstart , gpsend , match = None , urltype = None , on_gaps = "warn" ) : """Find the framefiles for the given type in the [ start , end ) interval frame @ param site : single - character name of site to match @ param frametype : name of frametype to match ...
if on_gaps not in ( "warn" , "error" , "ignore" ) : raise ValueError ( "on_gaps must be 'warn', 'error', or 'ignore'." ) url = ( "%s/gwf/%s/%s/%s,%s" % ( _url_prefix , site , frametype , gpsstart , gpsend ) ) # if a URL type is specified append it to the path if urltype : url += "/%s" % urltype # request JSON o...
def write_copy_button ( self , text , text_to_copy ) : """Writes a button with ' text ' which can be used to copy ' text _ to _ copy ' to clipboard when it ' s clicked ."""
self . write_copy_script = True self . write ( '<button onclick="cp(\'{}\');">{}</button>' . format ( text_to_copy , text ) )
def to_dict ( self , prefix = None ) : '''Converts recursively the Config object into a valid dictionary . : param prefix : A string to optionally prefix all key elements in the returned dictonary .'''
conf_obj = dict ( self ) return self . __dictify__ ( conf_obj , prefix )
def _set_cluster_id ( self , v , load = False ) : """Setter method for cluster _ id , mapped from YANG variable / routing _ system / router / router _ bgp / router _ bgp _ attributes / cluster _ id ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ cluster _ ...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = cluster_id . cluster_id , is_container = 'container' , presence = False , yang_name = "cluster-id" , rest_name = "cluster-id" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_pa...
def extractLocalParameters ( self , dna , bp , helical = False , frames = None ) : """Extract the local parameters for calculations . . currentmodule : : dnaMD Parameters dna : : class : ` dnaMD . DNA ` Input : class : ` dnaMD . DNA ` instance . bp : list List of two base - steps forming the DNA segment...
frames = self . _validateFrames ( frames ) if frames [ 1 ] == - 1 : frames [ 1 ] = None if ( len ( bp ) != 2 ) : raise ValueError ( "bp should be a list containing first and last bp of a segment. See, documentation!!!" ) if bp [ 0 ] > bp [ 1 ] : raise ValueError ( "bp should be a list containing first and l...
def resolve_solar ( self , year : int ) -> date : """Return the date object in a solar year . : param year : : return :"""
if self . date_class == date : return self . resolve ( year ) else : solar_date = LCalendars . cast_date ( self . resolve ( year ) , date ) offset = solar_date . year - year if offset : solar_date = LCalendars . cast_date ( self . resolve ( year - offset ) , date ) return solar_date
def ldap_server_host_retries ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) ldap_server = ET . SubElement ( config , "ldap-server" , xmlns = "urn:brocade.com:mgmt:brocade-aaa" ) host = ET . SubElement ( ldap_server , "host" ) hostname_key = ET . SubElement ( host , "hostname" ) hostname_key . text = kwargs . pop ( 'hostname' ) use_vrf_key = ET . SubElement ( ...
def _connect ( self ) : """Connect to JLigier"""
log . debug ( "Connecting to JLigier" ) self . socket = socket . socket ( ) self . socket . connect ( ( self . host , self . port ) )
def putf ( self , path , format , * args ) : """Equivalent to zconfig _ put , accepting a format specifier and variable argument list , instead of a single string value ."""
return lib . zconfig_putf ( self . _as_parameter_ , path , format , * args )
def _fix_file ( parameters ) : """Helper function for optionally running fix _ file ( ) in parallel ."""
if parameters [ 1 ] . verbose : print ( '[file:{0}]' . format ( parameters [ 0 ] ) , file = sys . stderr ) try : fix_file ( * parameters ) except IOError as error : print ( unicode ( error ) , file = sys . stderr )
def array ( self ) : """Data as a [ ` numpy . ndarray ` ] [ 1 ] in the form # ! python [ x1 , x2 , x3 , . . . ] , [ y1 , y2 , y3 , . . . ] By default , if unset , this will be set on first access by calling ` scipy _ data _ fitting . Data . load _ data ` . When loaded from file , the x and y values will...
if not hasattr ( self , '_array' ) : self . _array = self . load_data ( ) return self . _array
def parse ( self , data ) : # type : ( bytes ) - > None '''Parse the passed in data into a UDF Partition Header Descriptor . Parameters : data - The data to parse . Returns : Nothing .'''
if self . _initialized : raise pycdlibexception . PyCdlibInternalError ( 'UDF Partition Header Descriptor already initialized' ) ( unalloc_table_length , unalloc_table_pos , unalloc_bitmap_length , unalloc_bitmap_pos , part_integrity_table_length , part_integrity_table_pos , freed_table_length , freed_table_pos , f...
def transform ( self , data = None ) : """Return transformed data , or transform new data using the same model parameters Parameters data : numpy array , pandas dataframe or list of arrays / dfs The data to transform . If no data is passed , the xform _ data from the DataGeometry object will be returned ....
# if no new data passed , if data is None : return self . xform_data else : formatted = format_data ( data , semantic = self . semantic , vectorizer = self . vectorizer , corpus = self . corpus , ppca = True ) norm = normalizer ( formatted , normalize = self . normalize ) reduction = reducer ( norm , re...
def close ( self , nonce : Nonce , balance_hash : BalanceHash , additional_hash : AdditionalHash , signature : Signature , block_identifier : BlockSpecification , ) : """Closes the channel using the provided balance proof ."""
self . token_network . close ( channel_identifier = self . channel_identifier , partner = self . participant2 , balance_hash = balance_hash , nonce = nonce , additional_hash = additional_hash , signature = signature , given_block_identifier = block_identifier , )
def transform ( self , tfms : Optional [ Tuple [ TfmList , TfmList ] ] = ( None , None ) , ** kwargs ) : "Set ` tfms ` to be applied to the xs of the train and validation set ."
if not tfms : tfms = ( None , None ) assert is_listy ( tfms ) and len ( tfms ) == 2 , "Please pass a list of two lists of transforms (train and valid)." self . train . transform ( tfms [ 0 ] , ** kwargs ) self . valid . transform ( tfms [ 1 ] , ** kwargs ) if self . test : self . test . transform ( tfms [ 1 ] ,...
def replace_webhook ( self , scaling_group , policy , webhook , name , metadata = None ) : """Replace an existing webhook . All of the attributes must be specified . If you wish to delete any of the optional attributes , pass them in as None ."""
return self . _manager . replace_webhook ( scaling_group , policy , webhook , name , metadata = metadata )
def sample ( self , batch_info : BatchInfo , model : RlModel , number_of_steps : int ) -> Rollout : """Sample experience from replay buffer and return a batch"""
if self . forward_steps > 1 : transitions = self . replay_buffer . sample_forward_transitions ( batch_size = number_of_steps , batch_info = batch_info , forward_steps = self . forward_steps , discount_factor = self . discount_factor ) else : transitions = self . replay_buffer . sample_transitions ( batch_size =...
def normalize_signature ( func ) : """Decorator . Combine args and kwargs . Unpack single item tuples ."""
@ wraps ( func ) def wrapper ( * args , ** kwargs ) : if kwargs : args = args , kwargs if len ( args ) is 1 : args = args [ 0 ] return func ( args ) return wrapper
def report_entry_label ( self , entry_id ) : """Return the best label of the asked entry . Parameters entry _ id : int The index of the sample to ask . Returns label : object The best label of the given sample ."""
pruning = self . _find_root_pruning ( entry_id ) return self . classes [ self . _best_label ( pruning ) ]
def run_preassembly ( stmts_in , ** kwargs ) : """Run preassembly on a list of statements . Parameters stmts _ in : list [ indra . statements . Statement ] A list of statements to preassemble . return _ toplevel : Optional [ bool ] If True , only the top - level statements are returned . If False , all ...
dump_pkl_unique = kwargs . get ( 'save_unique' ) belief_scorer = kwargs . get ( 'belief_scorer' ) use_hierarchies = kwargs [ 'hierarchies' ] if 'hierarchies' in kwargs else hierarchies be = BeliefEngine ( scorer = belief_scorer ) pa = Preassembler ( hierarchies , stmts_in ) run_preassembly_duplicate ( pa , be , save = ...
def is_snake_case ( string , separator = '_' ) : """Checks if a string is formatted as snake case . A string is considered snake case when : * it ' s composed only by lowercase letters ( [ a - z ] ) , underscores ( or provided separator ) and optionally numbers ( [ 0-9 ] ) * it does not start / end with an un...
if is_full_string ( string ) : re_map = { '_' : SNAKE_CASE_TEST_RE , '-' : SNAKE_CASE_TEST_DASH_RE } re_template = '^[a-z]+([a-z\d]+{sign}|{sign}[a-z\d]+)+[a-z\d]+$' r = re_map . get ( separator , re . compile ( re_template . format ( sign = re . escape ( separator ) ) ) ) return bool ( r . search ( str...
def post ( self , request , format = None ) : """Add a new Channel ."""
data = request . data . copy ( ) # Get chat type record try : ct = ChatType . objects . get ( pk = data . pop ( "chat_type" ) ) data [ "chat_type" ] = ct except ChatType . DoesNotExist : return typeNotFound404 if not self . is_path_unique ( None , data [ "publish_path" ] , ct . publish_path ) : return n...
def _1_0set_screen_config ( self , size_id , rotation , config_timestamp , timestamp = X . CurrentTime ) : """Sets the screen to the specified size and rotation ."""
return _1_0SetScreenConfig ( display = self . display , opcode = self . display . get_extension_major ( extname ) , drawable = self , timestamp = timestamp , config_timestamp = config_timestamp , size_id = size_id , rotation = rotation , )
def column_names ( self ) : """Returns the column names . Returns out : list [ string ] Column names of the SFrame ."""
if self . _is_vertex_frame ( ) : return self . __graph__ . __proxy__ . get_vertex_fields ( ) elif self . _is_edge_frame ( ) : return self . __graph__ . __proxy__ . get_edge_fields ( )
def rebuildGrid ( self ) : """Rebuilds the ruler data ."""
vruler = self . verticalRuler ( ) hruler = self . horizontalRuler ( ) rect = self . _buildData [ 'grid_rect' ] # process the vertical ruler h_lines = [ ] h_alt = [ ] h_notches = [ ] vpstart = vruler . padStart ( ) vnotches = vruler . notches ( ) vpend = vruler . padEnd ( ) vcount = len ( vnotches ) + vpstart + vpend de...
def create_default_database ( reset : bool = False ) -> GraphDatabaseInterface : """Creates and returns a default SQLAlchemy database interface to use . Arguments : reset ( bool ) : Whether to reset the database if it happens to exist already ."""
import sqlalchemy from sqlalchemy . ext . declarative import declarative_base from sqlalchemy . orm import sessionmaker from sqlalchemy . pool import StaticPool Base = declarative_base ( ) engine = sqlalchemy . create_engine ( "sqlite:///SpotifyArtistGraph.db" , poolclass = StaticPool ) Session = sessionmaker ( bind = ...
def add_if_unique ( self , name ) : """Returns ` ` True ` ` on success . Returns ` ` False ` ` if the name already exists in the namespace ."""
with self . lock : if name not in self . names : self . names . append ( name ) return True return False
def compile_dir ( dfn , optimize_python = True ) : '''Compile * . py in directory ` dfn ` to * . pyo'''
if PYTHON is None : return if int ( PYTHON_VERSION [ 0 ] ) >= 3 : args = [ PYTHON , '-m' , 'compileall' , '-b' , '-f' , dfn ] else : args = [ PYTHON , '-m' , 'compileall' , '-f' , dfn ] if optimize_python : # - OO = strip docstrings args . insert ( 1 , '-OO' ) return_code = subprocess . call ( args ) if...
def get_src_builders ( self , env ) : """Returns the list of source Builders for this Builder . This exists mainly to look up Builders referenced as strings in the ' BUILDER ' variable of the construction environment and cache the result ."""
memo_key = id ( env ) try : memo_dict = self . _memo [ 'get_src_builders' ] except KeyError : memo_dict = { } self . _memo [ 'get_src_builders' ] = memo_dict else : try : return memo_dict [ memo_key ] except KeyError : pass builders = [ ] for bld in self . src_builder : if SCons ...
def add_clock ( self , timezone , color = 'lightgreen' , show_seconds = None ) : """Add a clock to the grid . ` timezone ` is a string representing a valid timezone ."""
if show_seconds is None : show_seconds = self . options . show_seconds clock = Clock ( self . app , self . logger , timezone , color = color , font = self . options . font , show_seconds = show_seconds ) clock . widget . cfg_expand ( 0x7 , 0x7 ) num_clocks = len ( self . clocks ) cols = self . settings . get ( 'col...
def _convert ( self , desired_type : Type [ T ] , obj : S , logger : Logger , options : Dict [ str , Dict [ str , Any ] ] ) -> T : """Apply the converters of the chain in order to produce the desired result . Only the last converter will see the ' desired type ' , the others will be asked to produce their declare...
for converter in self . _converters_list [ : - 1 ] : # convert into each converters destination type obj = converter . convert ( converter . to_type , obj , logger , options ) # the last converter in the chain should convert to desired type return self . _converters_list [ - 1 ] . convert ( desired_type , obj , log...
def parse_endnotes ( document , xmlcontent ) : """Parse endnotes document . Endnotes are defined in file ' endnotes . xml '"""
endnotes = etree . fromstring ( xmlcontent ) document . endnotes = { } for note in endnotes . xpath ( './/w:endnote' , namespaces = NAMESPACES ) : paragraphs = [ parse_paragraph ( document , para ) for para in note . xpath ( './/w:p' , namespaces = NAMESPACES ) ] document . endnotes [ note . attrib [ _name ( '{...
def normalize_datum ( self , datum ) : """Convert ` datum ` into something that umsgpack likes . : param datum : something that we want to process with umsgpack : return : a packable version of ` datum ` : raises TypeError : if ` datum ` cannot be packed This message is called by : meth : ` . packb ` to rec...
if datum is None : return datum if isinstance ( datum , self . PACKABLE_TYPES ) : return datum if isinstance ( datum , uuid . UUID ) : datum = str ( datum ) if isinstance ( datum , bytearray ) : datum = bytes ( datum ) if isinstance ( datum , memoryview ) : datum = datum . tobytes ( ) if hasattr ( d...
def modify ( self , ** kwargs ) : """Modify settings for a check . The provided settings will overwrite previous values . Settings not provided will stay the same as before the update . To clear an existing value , provide an empty value . Please note that you cannot change the type of a check once it has b...
# Warn user about unhandled parameters for key in kwargs : if key not in [ 'paused' , 'resolution' , 'contactids' , 'sendtoemail' , 'sendtosms' , 'sendtotwitter' , 'sendtoiphone' , 'sendnotificationwhendown' , 'notifyagainevery' , 'notifywhenbackup' , 'created' , 'type' , 'hostname' , 'status' , 'lasterrortime' , '...
def get_rmq_cluster_status ( self , sentry_unit ) : """Execute rabbitmq cluster status command on a unit and return the full output . : param unit : sentry unit : returns : String containing console output of cluster status command"""
cmd = 'rabbitmqctl cluster_status' output , _ = self . run_cmd_unit ( sentry_unit , cmd ) self . log . debug ( '{} cluster_status:\n{}' . format ( sentry_unit . info [ 'unit_name' ] , output ) ) return str ( output )
def commit ( func ) : '''Used as a decorator for automatically making session commits'''
def wrap ( ** kwarg ) : with session_withcommit ( ) as session : a = func ( ** kwarg ) session . add ( a ) return session . query ( songs ) . order_by ( songs . song_id . desc ( ) ) . first ( ) . song_id return wrap
def declare_dict ( self ) : """Return declared sections , terms and synonyms as a dict"""
# Run the parser , if it has not been run yet . if not self . root : for _ in self : pass return { 'sections' : self . _declared_sections , 'terms' : self . _declared_terms , 'synonyms' : self . synonyms }
def get_pyproject ( path ) : # type : ( Union [ STRING _ TYPE , Path ] ) - > Optional [ Tuple [ List [ STRING _ TYPE ] , STRING _ TYPE ] ] """Given a base path , look for the corresponding ` ` pyproject . toml ` ` file and return its build _ requires and build _ backend . : param AnyStr path : The root path of ...
if not path : return from vistir . compat import Path if not isinstance ( path , Path ) : path = Path ( path ) if not path . is_dir ( ) : path = path . parent pp_toml = path . joinpath ( "pyproject.toml" ) setup_py = path . joinpath ( "setup.py" ) if not pp_toml . exists ( ) : if not setup_py . exists (...
def diff_bisect ( self , text1 , text2 , deadline ) : """Find the ' middle snake ' of a diff , split the problem in two and return the recursively constructed diff . See Myers 1986 paper : An O ( ND ) Difference Algorithm and Its Variations . Args : text1 : Old string to be diffed . text2 : New string to ...
# Cache the text lengths to prevent multiple calls . text1_length = len ( text1 ) text2_length = len ( text2 ) max_d = ( text1_length + text2_length + 1 ) // 2 v_offset = max_d v_length = 2 * max_d v1 = [ - 1 ] * v_length v1 [ v_offset + 1 ] = 0 v2 = v1 [ : ] delta = text1_length - text2_length # If the total number of...