signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def branches ( config , searchstring = "" ) : """List all branches . And if exactly 1 found , offer to check it out ."""
repo = config . repo branches_ = list ( find ( repo , searchstring ) ) if branches_ : merged = get_merged_branches ( repo ) info_out ( "Found existing branches..." ) print_list ( branches_ , merged ) if len ( branches_ ) == 1 and searchstring : # If the found branch is the current one , error ac...
def update_from_schema ( cfg , cfgin , schema ) : """Update configuration dictionary ` ` cfg ` ` with the contents of ` ` cfgin ` ` using the ` ` schema ` ` dictionary to determine the valid input keys . Parameters cfg : dict Configuration dictionary to be updated . cfgin : dict New configuration dict...
cfgout = copy . deepcopy ( cfg ) for k , v in schema . items ( ) : if k not in cfgin : continue if isinstance ( v , dict ) : cfgout . setdefault ( k , { } ) cfgout [ k ] = update_from_schema ( cfg [ k ] , cfgin [ k ] , v ) elif v [ 2 ] is dict : cfgout [ k ] = utils . merge_d...
def remove_task_db ( self , fs_id ) : '''将任务从数据库中删除'''
sql = 'DELETE FROM tasks WHERE fsid=?' self . cursor . execute ( sql , [ fs_id , ] ) self . check_commit ( )
def check_work_done ( self , grp ) : """Check for the existence of alignment and result files ."""
id_ = self . get_id ( grp ) concat_file = os . path . join ( self . cache_dir , '{}.phy' . format ( id_ ) ) result_file = os . path . join ( self . cache_dir , '{}.{}.json' . format ( id_ , self . task_interface . name ) ) return os . path . exists ( concat_file ) , os . path . exists ( result_file )
def printText ( self , stream = None ) : """Prints a text representation of this sequence to the given stream or standard output ."""
if stream is None : stream = sys . stdout stream . write ( '# seqid : %u\n' % self . seqid ) stream . write ( '# version : %u\n' % self . version ) stream . write ( '# crc32 : 0x%04x\n' % self . crc32 ) stream . write ( '# ncmds : %u\n' % len ( self . commands ) ) stream . write ( '# duration: %.3fs\n' % self...
def get_active_threads_involving_all_participants ( self , * participant_ids ) : """Gets the threads where the specified participants are active and no one has left ."""
query = Thread . objects . exclude ( participation__date_left__lte = now ( ) ) . annotate ( count_participants = Count ( 'participants' ) ) . filter ( count_participants = len ( participant_ids ) ) for participant_id in participant_ids : query = query . filter ( participants__id = participant_id ) return query . di...
def convert_file_to_upload_string ( i ) : """Input : { filename - file name to convert Output : { return - return code = 0 , if successful > 0 , if error ( error ) - error text if return > 0 file _ content _ base64 - string that can be transmitted through Internet"""
import base64 fn = i [ 'filename' ] if not os . path . isfile ( fn ) : return { 'return' : 1 , 'error' : 'file ' + fn + ' not found' } s = b'' try : f = open ( fn , 'rb' ) while True : x = f . read ( 32768 ) ; if not x : break s += x f . close ( ) except Exception as ...
def add_database_user ( self , new_username , new_password , permissions = None ) : """Add database user . : param permissions : A ` ` ( readFrom , writeTo ) ` ` tuple"""
url = "db/{0}/users" . format ( self . _database ) data = { 'name' : new_username , 'password' : new_password } if permissions : try : data [ 'readFrom' ] , data [ 'writeTo' ] = permissions except ( ValueError , TypeError ) : raise TypeError ( "'permissions' must be (readFrom, writeTo) tuple" ) ...
def bokeh_palette ( name , rawtext , text , lineno , inliner , options = None , content = None ) : '''Generate an inline visual representations of a single color palette . This function evaluates the expression ` ` " palette = % s " % text ` ` , in the context of a ` ` globals ` ` namespace that has previously ...
try : exec ( "palette = %s" % text , _globals ) except Exception as e : raise SphinxError ( "cannot evaluate palette expression '%r', reason: %s" % ( text , e ) ) p = _globals . get ( 'palette' , None ) if not isinstance ( p , ( list , tuple ) ) or not all ( isinstance ( x , str ) for x in p ) : raise Sphin...
def scroll_to_end_vertically ( self , steps = 10 , * args , ** selectors ) : """Scroll the object which has * selectors * attributes to * end * vertically . See ` Scroll Forward Vertically ` for more details ."""
return self . device ( ** selectors ) . scroll . vert . toEnd ( steps = steps )
def transliterate ( text , lang1_code , lang2_code ) : """convert the source language script ( lang1 ) to target language script ( lang2) text : text to transliterate lang1 _ code : language 1 code lang1 _ code : language 2 code"""
if ( lang1_code in langinfo . SCRIPT_RANGES ) and ( lang2_code in langinfo . SCRIPT_RANGES ) : # if Sinhala is source , do a mapping to Devanagari first if lang1_code == 'si' : text = sdt . sinhala_to_devanagari ( text ) lang1_code = 'hi' # if Sinhala is target , make Devanagiri the intermediate...
def rename_stream_kwargs ( stream , kwargs , reverse = False ) : """Given a stream and a kwargs dictionary of parameter values , map to the corresponding dictionary where the keys are substituted with the appropriately renamed string . If reverse , the output will be a dictionary using the original paramete...
mapped_kwargs = { } mapping = stream_name_mapping ( stream , reverse = reverse ) for k , v in kwargs . items ( ) : if k not in mapping : msg = 'Could not map key {key} {direction} renamed equivalent' direction = 'from' if reverse else 'to' raise KeyError ( msg . format ( key = repr ( k ) , d...
def fingerprint2keyid ( fingerprint ) : """Returns keyid from fingerprint for private keys"""
if gnupg is None : return gpg = gnupg . GPG ( ) private_keys = gpg . list_keys ( True ) keyid = None for private_key in private_keys : if private_key [ 'fingerprint' ] == config [ "gpg_key_fingerprint" ] : keyid = private_key [ 'keyid' ] break return keyid
def read_from_memory_region ( self , * , region_name : str ) : """Reads from a memory region named region _ name on the QAM . This is a shim over the eventual API and only can return memory from a region named " ro " of type ` ` BIT ` ` . : param region _ name : The string naming the declared memory region . ...
warnings . warn ( "pyquil.api._qam.QAM.read_from_memory_region is deprecated, please use " "pyquil.api._qam.QAM.read_memory instead." , DeprecationWarning ) assert self . status == 'done' if region_name != "ro" : raise QAMError ( "Currently only allowed to read measurement data from ro." ) if self . _bitstrings is ...
def check_house ( self , complex : str , house : str ) -> bool : """Check if given house exists in the rumetr database"""
self . check_complex ( complex ) if '%s__%s' % ( complex , house ) in self . _checked_houses : return True try : self . get ( 'developers/{developer}/complexes/{complex}/houses/{house}/' . format ( developer = self . developer , complex = complex , house = house , ) ) except exceptions . Rumetr404Exception : ...
def _to_dict ( self ) : """Return a json dictionary representing this model ."""
_dict = { } if hasattr ( self , 'language' ) and self . language is not None : _dict [ 'language' ] = self . language if hasattr ( self , 'name' ) and self . name is not None : _dict [ 'name' ] = self . name return _dict
def transient_change_detect ( self , * class_build_args , ** class_build_kwargs ) : """This should be called when we want to detect a change in the status of the system regarding the transient list This function also applies changes due to regex _ set updates if needed _ transient _ change _ detect - > _ transi...
transient_detected = set ( self . get_transients_available ( ) ) # TODO : unify that last _ got _ set with the * _ available . they are essentially the same tst_gone = self . last_transients_detected - transient_detected # print ( " INTERFACING + { transient _ detected } " . format ( * * locals ( ) ) ) # print ( " INTE...
def _get_update_fn ( strategy ) : """Select dict - like class based on merge strategy and orderness of keys . : param merge : Specify strategy from MERGE _ STRATEGIES of how to merge dicts . : return : Callable to update objects"""
if strategy is None : strategy = MS_DICTS try : return _MERGE_FNS [ strategy ] except KeyError : if callable ( strategy ) : return strategy raise ValueError ( "Wrong merge strategy: %r" % strategy )
def get_merge_bases ( self , repository_name_or_id , commit_id , other_commit_id , project = None , other_collection_id = None , other_repository_id = None ) : """GetMergeBases . [ Preview API ] Find the merge bases of two commits , optionally across forks . If otherRepositoryId is not specified , the merge bases...
route_values = { } if project is not None : route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' ) if repository_name_or_id is not None : route_values [ 'repositoryNameOrId' ] = self . _serialize . url ( 'repository_name_or_id' , repository_name_or_id , 'str' ) if commit_id is not ...
def render_image ( self , rgbobj , dst_x , dst_y ) : """Render the image represented by ( rgbobj ) at dst _ x , dst _ y in the offscreen pixmap ."""
self . logger . debug ( "redraw pixmap=%s" % ( self . pixmap ) ) if self . pixmap is None : return self . logger . debug ( "drawing to pixmap" ) # Prepare array for rendering arr = rgbobj . get_array ( self . rgb_order , dtype = np . uint8 ) ( height , width ) = arr . shape [ : 2 ] return self . _render_offscreen (...
def acquire ( self , blocking = True ) : """Use Redis to hold a shared , distributed lock named ` ` name ` ` . Returns True once the lock is acquired . If ` ` blocking ` ` is False , always return immediately . If the lock was acquired , return True , otherwise return False ."""
sleep = self . sleep timeout = self . timeout while 1 : unixtime = time . time ( ) if timeout : timeout_at = unixtime + timeout else : timeout_at = Lock . LOCK_FOREVER timeout_at = float ( timeout_at ) if self . redis . setnx ( self . name , timeout_at ) : self . acquired_unt...
def get_meta_rdf ( self , fmt = 'n3' ) : """Get the metadata for this Thing in rdf fmt Advanced users who want to manipulate the RDF for this Thing directly without the [ ThingMeta ] ( ThingMeta . m . html # IoticAgent . IOT . ThingMeta . ThingMeta ) helper object Returns the RDF in the format you specify . -...
evt = self . _client . _request_entity_meta_get ( self . __lid , fmt = fmt ) self . _client . _wait_and_except_if_failed ( evt ) return evt . payload [ 'meta' ]
def tracksplot ( adata , var_names , groupby , use_raw = None , log = False , dendrogram = False , gene_symbols = None , var_group_positions = None , var_group_labels = None , layer = None , show = None , save = None , figsize = None , ** kwds ) : """In this type of plot each var _ name is plotted as a filled line ...
if groupby not in adata . obs_keys ( ) or adata . obs [ groupby ] . dtype . name != 'category' : raise ValueError ( 'groupby has to be a valid categorical observation. Given value: {}, ' 'valid categorical observations: {}' . format ( groupby , [ x for x in adata . obs_keys ( ) if adata . obs [ x ] . dtype . name =...
def AddEventHandler ( self , classId = None , managedObject = None , prop = None , successValue = [ ] , failureValue = [ ] , transientValue = [ ] , pollSec = None , timeoutSec = None , callBack = None ) : """Adds an event handler . An event handler can be added using this method where an user can subscribe for th...
from UcsBase import WriteObject , _GenericMO , UcsUtils , WriteUcsWarning , UcsValidationException if ( self . _transactionInProgress ) : raise UcsValidationException ( "UCS transaction in progress. Cannot execute WatchUcs. Complete or Undo UCS transaction." ) # WriteUcsWarning ( " UCS transaction in progress . Can...
def colinear_pairs ( segments , radius = .01 , angle = .01 , length = None ) : """Find pairs of segments which are colinear . Parameters segments : ( n , 2 , ( 2 , 3 ) ) float Two or three dimensional line segments radius : float Maximum radius line origins can differ and be considered colinear angle ...
from scipy import spatial # convert segments to parameterized origins # which are the closest point on the line to # the actual zero - origin origins , vectors , param = segments_to_parameters ( segments ) # create a kdtree for origins tree = spatial . cKDTree ( origins ) # find origins closer than specified radius pai...
def ensure_data ( ) : '''Ensure that the Garuda directory and files'''
if not os . path . exists ( GARUDA_DIR ) : os . makedirs ( GARUDA_DIR ) Path ( f'{GARUDA_DIR}/__init__.py' ) . touch ( )
def is_extracted ( self , file_path ) : """Check if the data file is already extracted ."""
if os . path . isdir ( file_path ) : self . chatbot . logger . info ( 'File is already extracted' ) return True return False
def serialize_ndarray_b64 ( o ) : """Serializes a : obj : ` numpy . ndarray ` in a format where the datatype and shape are human - readable , but the array data itself is binary64 encoded . Args : o ( : obj : ` numpy . ndarray ` ) : : obj : ` ndarray ` to be serialized . Returns : A dictionary that can be...
if o . flags [ 'C_CONTIGUOUS' ] : o_data = o . data else : o_data = np . ascontiguousarray ( o ) . data data_b64 = base64 . b64encode ( o_data ) return dict ( _type = 'np.ndarray' , data = data_b64 . decode ( 'utf-8' ) , dtype = o . dtype , shape = o . shape )
def make_message ( self , data ) : """Create a Message instance from data , data will be loaded via munge according to the codec specified in the transport _ content _ type attribute Returns : Message : message object"""
data = self . codec . loads ( data ) msg = Message ( data . get ( "data" ) , * data . get ( "args" , [ ] ) , ** data . get ( "kwargs" , { } ) ) msg . meta . update ( data . get ( "meta" ) ) self . trigger ( "make_message" , data , msg ) return msg
def send_music ( self , user_id , url , hq_url , thumb_media_id , title = None , description = None , account = None ) : """发送音乐消息 详情请参考 http : / / mp . weixin . qq . com / wiki / 7/12a5a320ae96fecdf0e15cb06123de9f . html : param user _ id : 用户 ID 。 就是你收到的 ` Message ` 的 source : param url : 音乐链接 : param h...
music_data = { 'musicurl' : url , 'hqmusicurl' : hq_url , 'thumb_media_id' : thumb_media_id } if title : music_data [ 'title' ] = title if description : music_data [ 'description' ] = description data = { 'touser' : user_id , 'msgtype' : 'music' , 'music' : music_data } return self . _send_custom_message ( data...
def save ( self , filename , addnormalised = False ) : """Save a frequency list to file , can be loaded later using the load method"""
f = io . open ( filename , 'w' , encoding = 'utf-8' ) for line in self . output ( "\t" , addnormalised ) : f . write ( line + '\n' ) f . close ( )
def loadProfile ( self , profile , inspectorFullName = None ) : """Reads the persistent program settings for the current profile . If inspectorFullName is given , a window with this inspector will be created if it wasn ' t already created in the profile . All windows with this inspector will be raised ."""
settings = QtCore . QSettings ( ) logger . info ( "Reading profile {!r} from: {}" . format ( profile , settings . fileName ( ) ) ) self . _profile = profile profGroupName = self . profileGroupName ( profile ) # Instantiate windows from groups settings . beginGroup ( profGroupName ) try : for windowGroupName in sett...
def download ( self , attachment_id , destination ) : """Download an attachment from Zendesk . : param attachment _ id : id of the attachment to download : param destination : destination path . If a directory , the file will be placed in the directory with the filename from the Attachment object . : return...
attachment = self ( id = attachment_id ) if os . path . isdir ( destination ) : destination = os . path . join ( destination , attachment . file_name ) return self . _download_file ( attachment . content_url , destination )
def save ( self , checkpoint_dir = None ) : """Saves the current model state to a checkpoint . Subclasses should override ` ` _ save ( ) ` ` instead to save state . This method dumps additional metadata alongside the saved path . Args : checkpoint _ dir ( str ) : Optional dir to place the checkpoint . Ret...
checkpoint_dir = os . path . join ( checkpoint_dir or self . logdir , "checkpoint_{}" . format ( self . _iteration ) ) if not os . path . exists ( checkpoint_dir ) : os . makedirs ( checkpoint_dir ) checkpoint = self . _save ( checkpoint_dir ) saved_as_dict = False if isinstance ( checkpoint , string_types ) : ...
def format_stack_frame ( stack_frame , project : 'projects.Project' ) -> dict : """Formats a raw stack frame into a dictionary formatted for render templating and enriched with information from the currently open project . : param stack _ frame : A raw stack frame to turn into an enriched version for templati...
filename = stack_frame . filename if filename . startswith ( project . source_directory ) : filename = filename [ len ( project . source_directory ) + 1 : ] location = stack_frame . name if location == '<module>' : location = None return dict ( filename = filename , location = location , line_number = stack_fra...
def get_accounts ( self , fetch = False ) : """Return this Wallet ' s accounts object , populating it if fetch is True ."""
return Accounts ( self . resource . accounts , self . client , wallet = self , populate = fetch )
def get_file_suffix ( self , path , prefix ) : """Gets a valid filename"""
parent = self . _ensure_folder_path ( path ) file_list = self . drive . ListFile ( { 'q' : "'{}' in parents and trashed=false and title contains '{}'" . format ( parent [ 'id' ] , prefix ) } ) . GetList ( ) try : number_of_files = len ( file_list ) except : number_of_files = 0 return '{0:04}' . format ( number_...
def iter_comments ( self , number = - 1 , etag = None ) : """Iterate over the comments on this pull request . : param int number : ( optional ) , number of comments to return . Default : -1 returns all available comments . : param str etag : ( optional ) , ETag from a previous request to the same endpoint ...
url = self . _build_url ( 'comments' , base_url = self . _api ) return self . _iter ( int ( number ) , url , ReviewComment , etag = etag )
def extract_name_value_type ( self , name , value , limit_size = False ) : """Extracts value of any object , eventually reduces it ' s size and returns name , truncated value and type ( for str with size appended )"""
MAX_STRING_LEN_TO_RETURN = 487 try : t_value = repr ( value ) except : t_value = "Error while extracting value" # convert all var names to string if isinstance ( name , str ) : r_name = name else : r_name = repr ( name ) # truncate value to limit data flow between ikpdb and client if len ( t_value ) > M...
def vline ( self , x : int , y : int , height : int , bg_blend : int = tcod . constants . BKGND_DEFAULT , ) -> None : """Draw a vertical line on the console . This always uses ord ( ' │ ' ) , the vertical line character . Args : x ( int ) : The x coordinate from the left . y ( int ) : The y coordinate from ...
self . __deprecate_defaults ( "draw_rect" , bg_blend ) lib . TCOD_console_vline ( self . console_c , x , y , height , bg_blend )
def get ( args ) : """Retrieve records . Argument : args : arguments object"""
password = get_password ( args ) token = connect . get_token ( args . username , password , args . server ) if args . __dict__ . get ( 'search' ) : # When using ' - - search ' option keyword = args . search else : keyword = '' if args . __dict__ . get ( 'raw_flag' ) : raw_flag = True else : raw_flag = F...
def stack_clip ( s_orig , extent , out_stack_fn = None , copy = True , save = False ) : """Create a new stack object with limited extent from an exising stack object"""
# Should check for valid extent # This is not memory efficient , but is much simpler # To be safe , if we are saving out , create a copy to avoid overwriting if copy or save : from copy import deepcopy print ( "Copying original DEMStack" ) s = deepcopy ( s_orig ) else : # Want to be very careful here , as w...
def get_code ( results ) : """Determines the exit status code to be returned from a script by inspecting the results returned from validating file ( s ) . Status codes are binary OR ' d together , so exit codes can communicate multiple error conditions ."""
status = EXIT_SUCCESS for file_result in results : error = any ( object_result . errors for object_result in file_result . object_results ) fatal = file_result . fatal if error : status |= EXIT_SCHEMA_INVALID if fatal : status |= EXIT_VALIDATION_ERROR return status
def read_json ( fn ) : """Convenience method to read pyquil . operator _ estimation objects from a JSON file . See : py : func : ` to _ json ` ."""
with open ( fn ) as f : return json . load ( f , object_hook = _operator_object_hook )
def update_extent ( self , operation ) : """Updates the extent of the * module * and its elements using the specified operation which has already been executed ."""
# Operations represent continuous lines of code . # The last operation to be executed is still the current one . line , col = operation . start operation . context . module . update_elements ( line , col , operation . length , operation . docdelta )
def computeFeedForwardActivity ( self , feedForwardInput ) : """Activate trnCells according to the l6Input . These in turn will impact bursting mode in relay cells that are connected to these trnCells . Given the feedForwardInput , compute which cells will be silent , tonic , or bursting . : param feedForwa...
ff = feedForwardInput . copy ( ) # For each relay cell , see if any of its FF inputs are active . for x in range ( self . relayWidth ) : for y in range ( self . relayHeight ) : inputCells = self . _preSynapticFFCells ( x , y ) for idx in inputCells : if feedForwardInput [ idx ] != 0 : ...
def _send_file ( self , method , path , data , filename ) : """Make a multipart / form - encoded request . Args : ` method ` : The method of the request ( POST or PUT ) . ` path ` : The path to the resource . ` data ` : The JSON - encoded data . ` filename ` : The filename of the file to send . Returns ...
with open ( filename , 'r' ) as f : return self . _make_request ( method , path , data = data , files = [ f , ] )
def jsend_output ( fail_exception_classes = None ) : """Format task result to json output in jsend specification format . See : https : / / github . com / omniti - labs . Task return value must be dict or None . @ param fail _ exception _ classes : exceptions which will produce ' fail ' response status ."""
fail_exception_classes = fail_exception_classes if fail_exception_classes else ( ) def decorator_fn ( f ) : @ wraps ( f ) @ json_output def jsend_output_decorator ( * args , ** kwargs ) : try : rv = f ( * args , ** kwargs ) except fail_exception_classes as e : return ...
def subscribe ( self , topics = ( ) , pattern = None , listener = None ) : """Subscribe to a list of topics , or a topic regex pattern . Partitions will be dynamically assigned via a group coordinator . Topic subscriptions are not incremental : this list will replace the current assignment ( if there is one )...
if self . _user_assignment or ( topics and pattern ) : raise IllegalStateError ( self . _SUBSCRIPTION_EXCEPTION_MESSAGE ) assert topics or pattern , 'Must provide topics or pattern' if pattern : log . info ( 'Subscribing to pattern: /%s/' , pattern ) self . subscription = set ( ) self . subscribed_patte...
def _handle_configspec ( self , configspec ) : """Parse the configspec ."""
# FIXME : Should we check that the configspec was created with the # correct settings ? ( i . e . ` ` list _ values = False ` ` ) if not isinstance ( configspec , ConfigObj ) : try : configspec = ConfigObj ( configspec , raise_errors = True , file_error = True , _inspec = True ) except ConfigObjError as...
def main ( ) : """Runs a datagenerator from the command - line . Calls JVM start / stop automatically . Use - h to see all options ."""
parser = argparse . ArgumentParser ( description = 'Executes a data generator from the command-line. Calls JVM start/stop automatically.' ) parser . add_argument ( "-j" , metavar = "classpath" , dest = "classpath" , help = "additional classpath, jars/directories" ) parser . add_argument ( "-X" , metavar = "heap" , dest...
def _finish_connection_action ( self , action ) : """Finish a connection attempt Args : action ( ConnectionAction ) : the action object describing what we are connecting to and what the result of the operation was"""
success = action . data [ 'success' ] conn_key = action . data [ 'id' ] if self . _get_connection_state ( conn_key ) != self . Connecting : print ( "Invalid finish_connection action on a connection whose state is not Connecting, conn_key=%s" % str ( conn_key ) ) return # Cannot be None since we checked above to...
def get ( self , key , default = None , cast = None , fresh = False , dotted_lookup = True ) : """Get a value from settings store , this is the prefered way to access : : > > > from dynaconf import settings > > > settings . get ( ' KEY ' ) : param key : The name of the setting value , will always be upper cas...
key = key . upper ( ) if "." in key and dotted_lookup : return self . _dotted_get ( dotted_key = key , default = default , cast = cast , fresh = fresh ) if key in self . _deleted : return default if ( fresh or self . _fresh or key in getattr ( self , "FRESH_VARS_FOR_DYNACONF" , ( ) ) ) and key not in dir ( defa...
def demo_err ( ) : """This demo shows how the error in the estimate varies depending on how many data points are included in the interpolation ( m parameter in this function ) ."""
max_order = 7 n = 20 l = 0.25 fmt1 = '{0: <5s}\t{1: <21s}\t{2: >21s}\t{3: >21s}\t{4: >21s}' fmt2 = '{0: <5d}\t{1:20.18f}\t{2: >21.18f}\t{3: >21.18f}\t{4: >21.18f}' x = np . cumsum ( np . random . rand ( n ) * l ) x = np . concatenate ( ( x [ : : - 1 ] * - 1 , x ) ) lst = [ ] derivs = np . zeros ( n ) for order in range...
def process_request ( self , request ) : """Process a Django request and authenticate users . If a JWT authentication header is detected and it is determined to be valid , the user is set as ` ` request . user ` ` and CSRF protection is disabled ( ` ` request . _ dont _ enforce _ csrf _ checks = True ` ` ) on ...
if 'HTTP_AUTHORIZATION' not in request . META : return try : method , claim = request . META [ 'HTTP_AUTHORIZATION' ] . split ( ' ' , 1 ) except ValueError : return if method . upper ( ) != AUTH_METHOD : return username = token . get_claimed_username ( claim ) if not username : return User = get_use...
def username_password_authn ( environ , start_response , reference , key , redirect_uri ) : """Display the login form"""
logger . info ( "The login page" ) headers = [ ] resp = Response ( mako_template = "login.mako" , template_lookup = LOOKUP , headers = headers ) argv = { "action" : "/verify" , "login" : "" , "password" : "" , "key" : key , "authn_reference" : reference , "redirect_uri" : redirect_uri } logger . info ( "do_authenticati...
def get_crumb_list_by_selector ( self , crumb_selector ) : """Return a list of crumbs ."""
return [ self . parsedpage . get_text_from_node ( crumb ) for crumb in self . parsedpage . get_nodes_by_selector ( crumb_selector ) ]
def dump ( config ) : """Returns the entire content of the config object in a way that can be easily examined , compared or dumped to a string or file . : param config : The configuration object to dump : rtype : dict"""
def _dump ( element ) : if not isinstance ( element , config . __class__ ) : return element section = dict ( ) for key , subsection in element . _subsections . items ( ) : section [ key ] = _dump ( subsection ) for key in element : section [ key ] = getattr ( element , key ) ...
def upload_video ( self , media_id , title , description ) : """群发视频消息时获取视频 media _ id 详情请参考 http : / / mp . weixin . qq . com / wiki / 15/5380a4e6f02f2ffdc7981a8ed7a40753 . html : param media _ id : 需通过基础支持中的上传下载多媒体文件 : func : ` upload ` 来得到 : param title : 视频标题 : param description : 视频描述 : return : 返回...
return self . _post ( url = 'media/uploadvideo' , data = { 'media_id' : media_id , 'title' : title , 'description' : description } )
def get_object ( self , group , key = None ) : """get object"""
return self . get_queryset_by_group_and_key ( group = group , key = key ) . first ( )
def rand_ssn ( ) : """Random SSN . ( 9 digits ) Example : : > > > rand _ ssn ( ) 295-50-0178"""
return "%s-%s-%s" % ( rand_str ( 3 , string . digits ) , rand_str ( 2 , string . digits ) , rand_str ( 4 , string . digits ) )
def get_all_lexers ( ) : """Return a generator of tuples in the form ` ` ( name , aliases , filenames , mimetypes ) ` ` of all know lexers ."""
for item in itervalues ( LEXERS ) : yield item [ 1 : ] for lexer in find_plugin_lexers ( ) : yield lexer . name , lexer . aliases , lexer . filenames , lexer . mimetypes
def send_hostinfo ( config ) : '''Register this host on OpenSubmit test machine .'''
info = all_host_infos ( ) logger . debug ( "Sending host information: " + str ( info ) ) post_data = [ ( "Config" , json . dumps ( info ) ) , ( "Action" , "get_config" ) , ( "UUID" , config . get ( "Server" , "uuid" ) ) , ( "Address" , ipaddress ( ) ) , ( "Secret" , config . get ( "Server" , "secret" ) ) ] send_post ( ...
def get_redirect_url ( self , ** kwargs ) : """Return the authorization / authentication URL signed with the request token ."""
params = { 'oauth_token' : self . get_request_token ( ) . key , } return '%s?%s' % ( self . auth_url , urllib . urlencode ( params ) )
def quoteattrs ( data ) : '''Takes dict of attributes and returns their HTML representation'''
items = [ ] for key , value in data . items ( ) : items . append ( '{}={}' . format ( key , quoteattr ( value ) ) ) return ' ' . join ( items )
def was_modified_since ( header = None , mtime = 0 , size = 0 ) : '''Check if an item was modified since the user last downloaded it : param header : the value of the ` ` If - Modified - Since ` ` header . If this is ` ` None ` ` , simply return ` ` True ` ` : param mtime : the modification time of the item i...
header_mtime = modified_since ( header , size ) if header_mtime and header_mtime <= mtime : return False return True
def on_selection_changed ( self ) : """Callback invoked one the selection has changed ."""
d = self . declaration selection = self . scene . selectedItems ( ) self . _guards |= 0x01 try : d . selected_items = [ item . ref ( ) . declaration for item in selection if item . ref ( ) ] finally : self . _guards &= ~ 0x01
def _link_or_update_vars ( self ) : """Creates or updates the symlink to group _ vars and returns None . : returns : None"""
for d , source in self . links . items ( ) : target = os . path . join ( self . inventory_directory , d ) source = os . path . join ( self . _config . scenario . directory , source ) if not os . path . exists ( source ) : msg = "The source path '{}' does not exist." . format ( source ) util ...
def norm ( self , x ) : """Return the norm of ` ` x ` ` . Parameters x : ` LinearSpaceElement ` Element whose norm to compute . Returns norm : float Norm of ` ` x ` ` ."""
if x not in self : raise LinearSpaceTypeError ( '`x` {!r} is not an element of ' '{!r}' . format ( x , self ) ) return float ( self . _norm ( x ) )
def has_permission ( self ) : """Permission checking for " normal " Django ."""
objs = [ None ] if hasattr ( self , 'get_perms_objects' ) : objs = self . get_perms_objects ( ) else : if hasattr ( self , 'get_object' ) : try : objs = [ self . get_object ( ) ] except Http404 : raise except : pass if objs == [ None ] : ob...
def _ParseRecord ( self , parser_mediator , record_index , evtx_record , recovered = False ) : """Extract data from a Windows XML EventLog ( EVTX ) record . Args : parser _ mediator ( ParserMediator ) : mediates interactions between parsers and other components , such as storage and dfvfs . record _ index (...
event_data = self . _GetEventData ( parser_mediator , record_index , evtx_record , recovered = recovered ) try : written_time = evtx_record . get_written_time_as_integer ( ) except OverflowError as exception : parser_mediator . ProduceExtractionWarning ( ( 'unable to read written time from event record: {0:d} '...
def _convert_nest_to_flat ( self , params , _result = None , _prefix = None ) : """Convert a data structure that looks like : : { " foo " : { " bar " : " baz " , " shimmy " : " sham " } } to : : { " foo . bar " : " baz " , " foo . shimmy " : " sham " } This is the inverse of L { _ convert _ flat _ to _ ne...
if _result is None : _result = { } for k , v in params . iteritems ( ) : if _prefix is None : path = k else : path = _prefix + '.' + k if isinstance ( v , dict ) : self . _convert_nest_to_flat ( v , _result = _result , _prefix = path ) else : _result [ path ] = v retu...
def main ( ) : '''main program loop'''
conn = symphony . Config ( 'example-bot.cfg' ) # connect to pod agent , pod , symphony_sid = conn . connect ( ) agent . test_echo ( 'test' ) # main loop msgFormat = 'MESSAGEML' message = '<messageML> hello world. </messageML>' # send message agent . send_message ( symphony_sid , msgFormat , message )
def split_sections ( s ) : """Split a string or iterable thereof into ( section , content ) pairs Each ` ` section ` ` is a stripped version of the section header ( " [ section ] " ) and each ` ` content ` ` is a list of stripped lines excluding blank lines and comment - only lines . If there are any such lin...
section = None content = [ ] for line in yield_lines ( s ) : if line . startswith ( "[" ) : if line . endswith ( "]" ) : if section or content : yield section , content section = line [ 1 : - 1 ] . strip ( ) content = [ ] else : raise V...
def cli ( ctx , ** kwargs ) : """DragonPy is a Open source ( GPL v3 or later ) emulator for the 30 years old homecomputer Dragon 32 and Tandy TRS - 80 Color Computer ( CoCo ) . . . Homepage : https : / / github . com / jedie / DragonPy"""
log . critical ( "cli kwargs: %s" , repr ( kwargs ) ) ctx . obj = CliConfig ( ** kwargs )
def build ( self , builder ) : """Build XML by appending to builder"""
params = dict ( LocationOID = self . oid ) # mixins self . mixin ( ) self . mixin_params ( params ) builder . start ( "SiteRef" , params ) builder . end ( "SiteRef" )
def binomial_coefficient ( n , k ) : """Calculate the binomial coefficient indexed by n and k . Args : n ( int ) : positive integer k ( int ) : positive integer Returns : The binomial coefficient indexed by n and k Raises : TypeError : If either n or k is not an integer ValueError : If either n or k...
if not isinstance ( k , int ) or not isinstance ( n , int ) : raise TypeError ( "Expecting positive integers" ) if k > n : raise ValueError ( "k must be lower or equal than n" ) if k < 0 or n < 0 : raise ValueError ( "Expecting positive integers" ) return factorial ( n ) // ( factorial ( k ) * factorial ( n...
def get_cluster_name ( self ) : """Name identifying this RabbitMQ cluster ."""
return self . _get ( url = self . url + '/api/cluster-name' , headers = self . headers , auth = self . auth )
def find_abbreviations ( self , kwargs ) : """Find the abbreviations for the given function and kwargs . Return ( name , abbrev , default ) tuples ."""
new_kwargs = [ ] try : sig = self . signature ( ) except ( ValueError , TypeError ) : # can ' t inspect , no info from function ; only use kwargs return [ ( key , value , value ) for key , value in kwargs . items ( ) ] for param in sig . parameters . values ( ) : for name , value , default in _yield_abbrevi...
def _validate_logical ( self , rule , field , value ) : """{ ' allowed ' : ( ' allof ' , ' anyof ' , ' noneof ' , ' oneof ' ) }"""
if not isinstance ( value , Sequence ) : self . _error ( field , errors . BAD_TYPE ) return validator = self . _get_child_validator ( document_crumb = rule , allow_unknown = False , schema = self . target_validator . validation_rules ) for constraints in value : _hash = ( mapping_hash ( { 'turing' : constra...
def _set_from_whole_string ( rop , s , base , rnd ) : """Helper function for set _ str2 : accept a string , set rop , and return the appropriate ternary value . Raise ValueError if ` ` s ` ` doesn ' t represent a valid string in the given base ."""
s = s . strip ( ) ternary , endindex = mpfr . mpfr_strtofr ( rop , s , base , rnd ) if len ( s ) != endindex : raise ValueError ( "not a valid numeric string" ) return ternary
def on_add_rows ( self , event ) : """add rows to grid"""
num_rows = self . rows_spin_ctrl . GetValue ( ) # last _ row = self . grid . GetNumberRows ( ) for row in range ( num_rows ) : self . grid . add_row ( ) # if not self . grid . changes : # self . grid . changes = set ( [ ] ) # self . grid . changes . add ( last _ row ) # last _ row + = 1 self . main_...
def _recurse ( coreml_tree , scikit_tree , tree_id , node_id , scaling = 1.0 , mode = 'regressor' , n_classes = 2 , tree_index = 0 ) : """Traverse through the tree and append to the tree spec ."""
if not ( HAS_SKLEARN ) : raise RuntimeError ( 'scikit-learn not found. scikit-learn conversion API is disabled.' ) # # Recursion should not be called on the leaf node . if node_id == _tree . TREE_LEAF : raise ValueError ( "Invalid node_id %s" % _tree . TREE_LEAF ) # Add a branch node to the tree if scikit_tree ...
def create_notification_rule ( self , data , ** kwargs ) : """Create a notification rule for this user ."""
data = { 'notification_rule' : data , } endpoint = '{0}/{1}/notification_rules' . format ( self . endpoint , self [ 'id' ] , ) result = self . request ( 'POST' , endpoint = endpoint , data = data , query_params = kwargs ) self . _data [ 'notification_rules' ] . append ( result [ 'notification_rule' ] ) return result
def grok_state ( self , obj ) : """Determine the desired state of this resource based on data present"""
if 'state' in obj : my_state = obj [ 'state' ] . lower ( ) if my_state != 'absent' and my_state != 'present' : raise aomi_excep . Validation ( 'state must be either "absent" or "present"' ) self . present = obj . get ( 'state' , 'present' ) . lower ( ) == 'present'
def parts ( self ) : """Split the path into parts like Pathlib > > > expected = [ ' / ' , ' path ' , ' to ' , ' there ' ] > > > assert DotPath ( ' / path / to / there ' ) . parts ( ) = = expected"""
parts = self . split ( os . path . sep ) parts [ 0 ] = parts [ 0 ] and parts [ 0 ] or '/' return parts
def index_to_coordinates ( self , index ) : """Return a set of 2D ` ` ( x , y ) ` ` coordinates from a linear index ."""
self . validate_index ( index ) x = int ( index % self . length ) y = int ( ( index - x ) / self . length ) return x , y
def main ( ) : """NAME plot _ map _ pts . py DESCRIPTION plots points on map SYNTAX plot _ map _ pts . py [ command line options ] OPTIONS - h prints help and quits - sym [ ro , bs , g ^ , r . , b - , etc . ] [ 1,5,10 ] symbol and size for points colors are r = red , b = blue , g = green , etc . ...
dir_path = '.' plot = 0 ocean = 0 res = 'c' proj = 'moll' Lats , Lons = [ ] , [ ] fmt = 'pdf' sym = 'ro' symsize = 5 fancy = 0 rivers , boundaries , ocean = 1 , 1 , 0 latmin , latmax , lonmin , lonmax , lat_0 , lon_0 = - 90 , 90 , 0. , 360. , 0. , 0. padlat , padlon , gridspace = 0 , 0 , 30 lat_0 , lon_0 = "" , "" base...
def create_run_config ( model_name , master = "" , model_dir = None , iterations_per_loop = 1000 , num_shards = 8 , log_device_placement = False , save_checkpoints_steps = 1000 , save_checkpoints_secs = None , keep_checkpoint_max = 20 , keep_checkpoint_every_n_hours = 10000 , num_gpus = 1 , gpu_order = "" , num_async_r...
session_config = create_session_config ( log_device_placement = log_device_placement , enable_graph_rewriter = enable_graph_rewriter , gpu_mem_fraction = gpu_mem_fraction , use_tpu = use_tpu , xla_jit_level = xla_jit_level , inter_op_parallelism_threads = inter_op_parallelism_threads , intra_op_parallelism_threads = in...
def _get_groups ( self , data ) : """Get all groups defined"""
groups = [ ] for attribute in SOURCE_KEYS : for k , v in data [ attribute ] . items ( ) : if k == None : k = 'Sources' if k not in groups : groups . append ( k ) for k , v in data [ 'include_files' ] . items ( ) : if k == None : k = 'Includes' if k not in grou...
def perform ( self ) : """Perform the version upgrade on the database ."""
db_versions = self . table . versions ( ) version = self . version if ( version . is_processed ( db_versions ) and not self . config . force_version == self . version . number ) : self . log ( u'version {} is already installed' . format ( version . number ) ) return self . start ( ) try : self . _perform_ve...
def verify_honeypot_value ( request , field_name ) : """Verify that request . POST [ field _ name ] is a valid honeypot . Ensures that the field exists and passes verification according to HONEYPOT _ VERIFIER ."""
verifier = getattr ( settings , 'HONEYPOT_VERIFIER' , honeypot_equals ) if request . method == 'POST' : field = field_name or settings . HONEYPOT_FIELD_NAME if field not in request . POST or not verifier ( request . POST [ field ] ) : resp = render_to_string ( 'honeypot/honeypot_error.html' , { 'fieldna...
def submit ( self , __fun , * args , ** kwargs ) : """Creates a new future and enqueues it . Returns the future ."""
future = Future ( ) . bind ( __fun , * args , ** kwargs ) self . enqueue ( future ) return future
def get_first_field_values_as_list ( self , field ) : ''': param str field : The name of the field for lookup . Goes through all documents returned looking for specified field . At first encounter will return the field ' s value .'''
for doc in self . docs : if field in doc . keys ( ) : return doc [ field ] raise SolrResponseError ( "No field in result set" )
def apply_magnitude_interpolation ( self , mag , iml_table ) : """Interpolates the tables to the required magnitude level : param float mag : Magnitude : param iml _ table : Intensity measure level table"""
# do not allow " mag " to exceed maximum table magnitude if mag > self . m_w [ - 1 ] : mag = self . m_w [ - 1 ] # Get magnitude values if mag < self . m_w [ 0 ] or mag > self . m_w [ - 1 ] : raise ValueError ( "Magnitude %.2f outside of supported range " "(%.2f to %.2f)" % ( mag , self . m_w [ 0 ] , self . m_w ...
def register_connection ( name , hosts = None , consistency = None , lazy_connect = False , retry_connect = False , cluster_options = None , default = False , session = None ) : """Add a connection to the connection registry . ` ` hosts ` ` and ` ` session ` ` are mutually exclusive , and ` ` consistency ` ` , ` ...
if name in _connections : log . warning ( "Registering connection '{0}' when it already exists." . format ( name ) ) if session is not None : invalid_config_args = ( hosts is not None or consistency is not None or lazy_connect is not False or retry_connect is not False or cluster_options is not None ) if in...
async def remove ( self , * , node_id : str , force : bool = False ) -> Mapping [ str , Any ] : """Remove a node from a swarm . Args : node _ id : The ID or name of the node"""
params = { "force" : force } response = await self . docker . _query_json ( "nodes/{node_id}" . format ( node_id = node_id ) , method = "DELETE" , params = params ) return response
def add_substitution ( self , substitution ) : """Add a substitution to the email : param value : Add a substitution to the email : type value : Substitution"""
if substitution . personalization : try : personalization = self . _personalizations [ substitution . personalization ] has_internal_personalization = True except IndexError : personalization = Personalization ( ) has_internal_personalization = False personalization . add_sub...
def printCols ( strlist , cols = 5 , width = 80 ) : """Print elements of list in cols columns"""
# This may exist somewhere in the Python standard libraries ? # Should probably rewrite this , it is pretty crude . nlines = ( len ( strlist ) + cols - 1 ) // cols line = nlines * [ "" ] for i in range ( len ( strlist ) ) : c , r = divmod ( i , nlines ) nwid = c * width // cols - len ( line [ r ] ) if nwid ...
def get_lyrics_letssingit ( song_name ) : '''Scrapes the lyrics of a song since spotify does not provide lyrics takes song title as arguement'''
lyrics = "" url = "http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=" + quote ( song_name . encode ( 'utf-8' ) ) html = urlopen ( url ) . read ( ) soup = BeautifulSoup ( html , "html.parser" ) link = soup . find ( 'a' , { 'class' : 'high_profile' } ) try : link = link . get ( 'href' ) ...