signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _send_unsigned_int ( self , value ) : """Convert a numerical value into an integer , then to a bytes object . Check bounds for unsigned int ."""
# Coerce to int . This will throw a ValueError if the value can ' t # actually be converted . if type ( value ) != int : new_value = int ( value ) if self . give_warnings : w = "Coercing {} into int ({})" . format ( value , new_value ) warnings . warn ( w , Warning ) value = new_value # ...
def run_algorithm ( start , end , initialize , capital_base , handle_data = None , before_trading_start = None , analyze = None , data_frequency = 'daily' , bundle = 'quantopian-quandl' , bundle_timestamp = None , trading_calendar = None , metrics_set = 'default' , benchmark_returns = None , default_extension = True , ...
load_extensions ( default_extension , extensions , strict_extensions , environ ) return _run ( handle_data = handle_data , initialize = initialize , before_trading_start = before_trading_start , analyze = analyze , algofile = None , algotext = None , defines = ( ) , data_frequency = data_frequency , capital_base = capi...
def parse_known_args ( self , args = None , namespace = None ) : """this method hijacks the normal argparse Namespace generation , shimming configman into the process . The return value will be a configman DotDict rather than an argparse Namespace ."""
# load the config _ manager within the scope of the method that uses it # so that we avoid circular references in the outer scope from configman . config_manager import ConfigurationManager configuration_manager = ConfigurationManager ( definition_source = [ self . get_required_config ( ) ] , values_source_list = self ...
def webui_url ( args ) : '''show the url of web ui'''
nni_config = Config ( get_config_filename ( args ) ) print_normal ( '{0} {1}' . format ( 'Web UI url:' , ' ' . join ( nni_config . get_config ( 'webuiUrl' ) ) ) )
def content_negotiation ( ids = None , format = "bibtex" , style = 'apa' , locale = "en-US" , url = None , ** kwargs ) : '''Get citations in various formats from CrossRef : param ids : [ str ] Search by a single DOI or many DOIs , each a string . If many passed in , do so in a list : param format : [ str ] Na...
if url is None : url = cn_base_url return CNRequest ( url , ids , format , style , locale , ** kwargs )
def _transientSchedule ( self , when , now ) : """If the service is currently running , schedule a tick to happen no later than C { when } . @ param when : The time at which to tick . @ type when : L { epsilon . extime . Time } @ param now : The current time . @ type now : L { epsilon . extime . Time }"""
if not self . running : return if self . timer is not None : if self . timer . getTime ( ) < when . asPOSIXTimestamp ( ) : return self . timer . cancel ( ) delay = when . asPOSIXTimestamp ( ) - now . asPOSIXTimestamp ( ) # reactor . callLater allows only positive delay values . The scheduler # may w...
def div ( txt , * args , ** kwargs ) : """Create & return an HTML < div > element by wrapping the passed text buffer . @ param txt ( basestring ) : the text buffer to use @ param * args ( list ) : if present , \ c txt is considered a Python format string , and the arguments are formatted into it @ param kwa...
if args : txt = txt . format ( * args ) css = kwargs . get ( 'css' , HTML_DIV_CLASS ) return u'<div class="{}">{!s}</div>' . format ( css , txt )
def insertTopLevelGroup ( self , groupName , position = None ) : """Inserts a top level group tree item . Used to group all config nodes of ( for instance ) the current inspector , Returns the newly created CTI"""
groupCti = GroupCti ( groupName ) return self . _invisibleRootItem . insertChild ( groupCti , position = position )
def cee_map_priority_table_map_cos3_pgid ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) cee_map = ET . SubElement ( config , "cee-map" , xmlns = "urn:brocade.com:mgmt:brocade-cee-map" ) name_key = ET . SubElement ( cee_map , "name" ) name_key . text = kwargs . pop ( 'name' ) priority_table = ET . SubElement ( cee_map , "priority-table" ) map_cos3_pgid = ET . SubElement (...
def has ( self , key ) : """See if a key is in the cache Returns CACHE _ DISABLED if the cache is disabled : param key : key to search for"""
if not self . options . enabled : return CACHE_DISABLED ret = key in self . _dict . keys ( ) and not self . _dict [ key ] . is_expired ( ) logger . debug ( 'has({}) == {}' . format ( repr ( key ) , ret ) ) return ret
def vtquery ( apikey , checksums ) : """Performs the query dealing with errors and throttling requests ."""
data = { 'apikey' : apikey , 'resource' : isinstance ( checksums , str ) and checksums or ', ' . join ( checksums ) } while 1 : response = requests . post ( VT_REPORT_URL , data = data ) response . raise_for_status ( ) if response . status_code == 200 : return response . json ( ) elif response ....
def doDailies ( usr , dailyList ) : """Does a list of dailies and yields each result Takes a list of valid dailies , initiates each one , and then proceeds to play each one and yield it ' s resulting message . Note that the names given in the list must be the same as the daily ' s class file . Parameters ...
# Load all supported dailies dailies = [ ] for daily in Daily . __subclasses__ ( ) : dailies . append ( daily . __name__ ) # Verify the list is accurate for daily in dailyList : if not daily in dailies : raise invalidDaily for daily in Daily . __subclasses__ ( ) : if not daily . __name__ in dailyLis...
def _logprob_obs ( self , data , mean_pat , var ) : """Log probability of observing each timepoint under each event model Computes the log probability of each observed timepoint being generated by the Gaussian distribution for each event pattern Parameters data : voxel by time ndarray fMRI data on which t...
n_vox = data . shape [ 0 ] t = data . shape [ 1 ] # z - score both data and mean patterns in space , so that Gaussians # are measuring Pearson correlations and are insensitive to overall # activity changes data_z = stats . zscore ( data , axis = 0 , ddof = 1 ) mean_pat_z = stats . zscore ( mean_pat , axis = 0 , ddof = ...
def forward ( self , x ) : """Transforms from the packed to unpacked representations ( numpy ) : param x : packed numpy array . Must have shape ` self . num _ matrices x triangular _ number : return : Reconstructed numpy array y of shape self . num _ matrices x N x N"""
fwd = np . zeros ( ( self . num_matrices , self . N , self . N ) , settings . float_type ) indices = np . tril_indices ( self . N , 0 ) z = np . zeros ( len ( indices [ 0 ] ) ) . astype ( int ) for i in range ( self . num_matrices ) : fwd [ ( z + i , ) + indices ] = x [ i , : ] return fwd . squeeze ( axis = 0 ) if ...
def _remove_node ( self , node_name ) : """Remove the given node from the continuum / ring . : param node _ name : the node name ."""
try : node_conf = self . _nodes . pop ( node_name ) except Exception : raise KeyError ( 'node \'{}\' not found, available nodes: {}' . format ( node_name , self . _nodes . keys ( ) ) ) else : self . _distribution . pop ( node_name ) for w in range ( 0 , node_conf [ 'vnodes' ] * node_conf [ 'weight' ] ) ...
def add_handler ( cls , level , fmt , colorful , ** kwargs ) : """Add a configured handler to the global logger ."""
global g_logger if isinstance ( level , str ) : level = getattr ( logging , level . upper ( ) , logging . DEBUG ) handler = cls ( ** kwargs ) handler . setLevel ( level ) if colorful : formatter = ColoredFormatter ( fmt , datefmt = '%Y-%m-%d %H:%M:%S' ) else : formatter = logging . Formatter ( fmt , datefmt...
def add_to_item_list_by_name ( self , item_urls , item_list_name ) : """Instruct the server to add the given items to the specified Item List ( which will be created if it does not already exist ) : type item _ urls : List or ItemGroup : param item _ urls : List of URLs for the items to add , or an ItemGrou...
url_name = urlencode ( ( ( 'name' , item_list_name ) , ) ) request_url = '/item_lists?' + url_name data = json . dumps ( { 'items' : list ( item_urls ) } ) resp = self . api_request ( request_url , method = 'POST' , data = data ) return self . __check_success ( resp )
def _is_string ( thing ) : """Check that * * thing * * is a string . The definition of the latter depends upon the Python version . : param thing : The thing to check if it ' s a string . : rtype : bool : returns : ` ` True ` ` if * * thing * * is string ( or unicode in Python2 ) ."""
if ( _py3k and isinstance ( thing , str ) ) : return True if ( not _py3k and isinstance ( thing , basestring ) ) : return True return False
def get_tracks ( self ) : """Retrieves all the tracks of the album if they haven ' t been retrieved yet : return : List . Tracks of the current album"""
if not self . _track_list : tracks = itunespy . lookup ( id = self . collection_id , entity = itunespy . entities [ 'song' ] ) [ 1 : ] for track in tracks : self . _track_list . append ( track ) return self . _track_list
def send_message ( self , body , to , quiet = False , html_body = None ) : """Send a message to a single member"""
if to . get ( 'MUTED' ) : to [ 'QUEUED_MESSAGES' ] . append ( body ) else : if not quiet : logger . info ( 'message on %s to %s: %s' % ( self . name , to [ 'JID' ] , body ) ) message = xmpp . protocol . Message ( to = to [ 'JID' ] , body = body , typ = 'chat' ) if html_body : html = xmpp...
def init ( cls , * args , ** kwargs ) : """Initialize the config like as you would a regular dict ."""
instance = cls ( ) instance . _values . update ( dict ( * args , ** kwargs ) ) return instance
def parse_expression ( self , expr ) : """split expression into prefix and expression tested with operator = = std : : rel _ ops : : operator ! = std : : atomic : : operator = std : : array : : operator [ ] std : : function : : operator ( ) std : : vector : : at std : : relational operators std : ...
m = re . match ( r'^(.*?(?:::)?(?:operator)?)((?:::[^:]*|[^:]*)?)$' , expr ) ; prefix = m . group ( 1 ) tail = m . group ( 2 ) return [ prefix , tail ]
def repeater ( pipe , how_many = 2 ) : '''this function repeats each value in the pipeline however many times you need'''
r = range ( how_many ) for i in pipe : for _ in r : yield i
def inertia_tensor ( self ) : """the intertia tensor of the molecule"""
result = np . zeros ( ( 3 , 3 ) , float ) for i in range ( self . size ) : r = self . coordinates [ i ] - self . com # the diagonal term result . ravel ( ) [ : : 4 ] += self . masses [ i ] * ( r ** 2 ) . sum ( ) # the outer product term result -= self . masses [ i ] * np . outer ( r , r ) return res...
def load_sound_font ( self , sf2 ) : """Load a sound font . Return True on success , False on failure . This function should be called before your audio can be played , since the instruments are kept in the sf2 file ."""
self . sfid = self . fs . sfload ( sf2 ) return not self . sfid == - 1
def ellipsoid_phantom ( space , ellipsoids , min_pt = None , max_pt = None ) : """Return a phantom given by ellipsoids . Parameters space : ` DiscreteLp ` Space in which the phantom should be created , must be 2 - or 3 - dimensional . If ` ` space . shape ` ` is 1 in an axis , a corresponding slice of the...
if space . ndim == 2 : _phantom = _ellipse_phantom_2d elif space . ndim == 3 : _phantom = _ellipsoid_phantom_3d else : raise ValueError ( 'dimension not 2 or 3, no phantom available' ) if min_pt is None and max_pt is None : return _phantom ( space , ellipsoids ) else : # Generate a temporary space with ...
def has_ssd ( self ) : """Return true if any of the drive is ssd"""
for member in self . _drives_list ( ) : if member . media_type == constants . MEDIA_TYPE_SSD : return True return False
def apply_signal ( signal_function , volume_signal , ) : """Combine the signal volume with its timecourse Apply the convolution of the HRF and stimulus time course to the volume . Parameters signal _ function : timepoint by timecourse array , float The timecourse of the signal over time . If there is only...
# How many timecourses are there within the signal _ function timepoints = signal_function . shape [ 0 ] timecourses = signal_function . shape [ 1 ] # Preset volume signal = np . zeros ( [ volume_signal . shape [ 0 ] , volume_signal . shape [ 1 ] , volume_signal . shape [ 2 ] , timepoints ] ) # Find all the non - zero ...
def write ( self , file_path , hoys = None , write_hours = False ) : """Write the wea file . WEA carries irradiance values from epw and is what gendaymtx uses to generate the sky ."""
if not file_path . lower ( ) . endswith ( '.wea' ) : file_path += '.wea' # generate hoys in wea file based on timestep full_wea = False if not hoys : hoys = self . hoys full_wea = True # write header lines = [ self . header ] if full_wea : # there is no user input for hoys , write it for all the hours f...
def get_target_state ( ) : """SDP target State . Returns the target state ; allowed target states and time updated"""
sdp_state = SDPState ( ) errval , errdict = _check_status ( sdp_state ) if errval == "error" : LOG . debug ( errdict [ 'reason' ] ) return dict ( current_target_state = "unknown" , last_updated = "unknown" , reason = errdict [ 'reason' ] ) LOG . debug ( 'Getting target state' ) target_state = sdp_state . target...
def update_release_resource ( self , release_update_metadata , project , release_id ) : """UpdateReleaseResource . [ Preview API ] Update few properties of a release . : param : class : ` < ReleaseUpdateMetadata > < azure . devops . v5_1 . release . models . ReleaseUpdateMetadata > ` release _ update _ metadata...
route_values = { } if project is not None : route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' ) if release_id is not None : route_values [ 'releaseId' ] = self . _serialize . url ( 'release_id' , release_id , 'int' ) content = self . _serialize . body ( release_update_metadata ,...
def assortativity_attributes ( user ) : """Computes the assortativity of the nominal attributes . This indicator measures the homophily of the current user with his correspondants , for each attributes . It returns a value between 0 ( no assortativity ) and 1 ( all the contacts share the same value ) : the ...
matrix = matrix_undirected_unweighted ( user ) neighbors = [ k for k in user . network . keys ( ) if k != user . name ] neighbors_attrbs = { } for i , u_name in enumerate ( matrix_index ( user ) ) : correspondent = user . network . get ( u_name , None ) if correspondent is None or u_name == user . name or matri...
def p_ParamList ( p ) : '''ParamList : | Param | ParamList COMMA Param'''
if len ( p ) == 1 : p [ 0 ] = ParamList ( None , None ) elif len ( p ) == 2 : p [ 0 ] = ParamList ( None , p [ 1 ] ) else : p [ 0 ] = ParamList ( p [ 1 ] , p [ 3 ] )
def replace_pattern ( name , pattern , repl , count = 0 , flags = 8 , bufsize = 1 , append_if_not_found = False , prepend_if_not_found = False , not_found_content = None , search_only = False , show_changes = True , backslash_literal = False , source = 'running' , path = None , test = False , replace = True , debug = F...
ret = salt . utils . napalm . default_ret ( name ) # the user can override the flags the equivalent CLI args # which have higher precedence test = __salt__ [ 'config.merge' ] ( 'test' , test ) debug = __salt__ [ 'config.merge' ] ( 'debug' , debug ) commit = __salt__ [ 'config.merge' ] ( 'commit' , commit ) replace = __...
def from_file ( cls , db_file = ALL_SETS_PATH ) : """Reads card data from a JSON - file . : param db _ file : A file - like object or a path . : return : A new : class : ` ~ mtgjson . CardDb ` instance ."""
if callable ( getattr ( db_file , 'read' , None ) ) : return cls ( json . load ( db_file ) ) with io . open ( db_file , encoding = 'utf8' ) as inp : return cls ( json . load ( inp ) )
def refresh_metrics ( self ) : """Refresh metrics based on the column metadata"""
metrics = self . get_metrics ( ) dbmetrics = ( db . session . query ( DruidMetric ) . filter ( DruidMetric . datasource_id == self . datasource_id ) . filter ( DruidMetric . metric_name . in_ ( metrics . keys ( ) ) ) ) dbmetrics = { metric . metric_name : metric for metric in dbmetrics } for metric in metrics . values ...
def use_comparative_assessment_part_bank_view ( self ) : """Pass through to provider AssessmentPartBankSession . use _ comparative _ assessment _ part _ bank _ view"""
self . _bank_view = COMPARATIVE # self . _ get _ provider _ session ( ' assessment _ part _ bank _ session ' ) # To make sure the session is tracked for session in self . _get_provider_sessions ( ) : try : session . use_comparative_bank_view ( ) except AttributeError : pass
def rename ( self , new_name , range = None ) : """Request a rename to the server ."""
self . log . debug ( 'rename: in' ) if not new_name : new_name = self . editor . ask_input ( "Rename to:" ) self . editor . write ( noautocmd = True ) b , e = self . editor . word_under_cursor_pos ( ) current_file = self . editor . path ( ) self . editor . raw_message ( current_file ) self . send_refactor_request (...
def pkg_name_to_path ( pkgname ) : """todo : Docstring for pkg _ name _ to _ path : param pkgname : arg description : type pkgname : type description : return : : rtype :"""
logger . debug ( "'%s'" , pkgname ) fp = os . path . join ( settings . upkg_destdir , pkgname ) if os . path . isdir ( fp ) : logger . debug ( "found %s" , fp ) return fp # Try to find the repo dir if just needs an extension for d in repo_dirlist ( ) : logger . debug ( "trying %s" , d ) if d [ 'base' ] ...
def clear_caches ( ) : # suppress ( unused - function ) """Clear all caches ."""
for _ , reader in _spellchecker_cache . values ( ) : reader . close ( ) _spellchecker_cache . clear ( ) _valid_words_cache . clear ( ) _user_dictionary_cache . clear ( )
def require_admin ( func ) : """Requires an admin user to access this resource ."""
@ wraps ( func ) @ require_login def decorated ( * args , ** kwargs ) : user = current_user ( ) if user and user . is_admin : return func ( * args , ** kwargs ) else : return Response ( 'Forbidden' , 403 ) return decorated
def class_param_names ( cls , hidden = True ) : """Return the names of all class parameters . : param hidden : if ` ` False ` ` , excludes parameters with a ` ` _ ` ` prefix . : type hidden : : class : ` bool ` : return : set of parameter names : rtype : : class : ` set `"""
param_names = set ( k for ( k , v ) in cls . __dict__ . items ( ) if isinstance ( v , Parameter ) ) for parent in cls . __bases__ : if hasattr ( parent , 'class_param_names' ) : param_names |= parent . class_param_names ( hidden = hidden ) if not hidden : param_names = set ( n for n in param_names if no...
def version ( self , calver : bool = False , pre_release : bool = False ) -> str : """Generate version number . : param calver : Calendar versioning . : param pre _ release : Pre - release . : return : Version . : Example : 0.2.1"""
# TODO : Optimize version = '{}.{}.{}' major , minor , patch = self . random . randints ( 3 , 0 , 10 ) if calver : if minor == 0 : minor += 1 if patch == 0 : patch += 1 major = self . random . randint ( 2016 , 2018 ) return version . format ( major , minor , patch ) version = '{}.{}.{}' ...
def _fetch ( queryset , model_objs , unique_fields , update_fields , returning , sync , ignore_duplicate_updates = True , return_untouched = False ) : """Perfom the upsert and do an optional sync operation"""
model = queryset . model if ( return_untouched or sync ) and returning is not True : returning = set ( returning ) if returning else set ( ) returning . add ( model . _meta . pk . name ) upserted = [ ] deleted = [ ] # We must return untouched rows when doing a sync operation return_untouched = True if sync else...
def clip ( self , x1 , y1 , x2 , y2 ) : """Activate a rectangular clip region , ( X1 , Y1 ) - ( X2 , Y2 ) . You must call endclip ( ) after you completed drawing . canvas . clip ( x , y , x2 , y2) draw something . . . canvas . endclip ( )"""
self . __clip_stack . append ( self . __clip_box ) self . __clip_box = _intersect_box ( self . __clip_box , ( x1 , y1 , x2 , y2 ) ) self . gsave ( ) self . newpath ( ) self . moveto ( xscale ( x1 ) , yscale ( y1 ) ) self . lineto ( xscale ( x1 ) , yscale ( y2 ) ) self . lineto ( xscale ( x2 ) , yscale ( y2 ) ) self . l...
def runlist_remove ( name , ** kwargs ) : """Remove runlist from the storage ."""
ctx = Context ( ** kwargs ) ctx . execute_action ( 'runlist:remove' , ** { 'storage' : ctx . repo . create_secure_service ( 'storage' ) , 'name' : name , } )
def ystep ( self ) : r"""Minimise Augmented Lagrangian with respect to : math : ` \ mathbf { y } ` ."""
AXU = self . AX + self . U Y0 = ( self . rho * ( self . block_sep0 ( AXU ) - self . S ) ) / ( self . W ** 2 + self . rho ) Y1 = self . Pcn ( self . block_sep1 ( AXU ) ) self . Y = self . block_cat ( Y0 , Y1 )
def set ( self , logicalId , resource ) : """Adds the resource to dictionary with given logical Id . It will overwrite , if the logicalId is already used . : param string logicalId : Logical Id to set to : param SamResource or dict resource : The actual resource data"""
resource_dict = resource if isinstance ( resource , SamResource ) : resource_dict = resource . to_dict ( ) self . resources [ logicalId ] = resource_dict
def addSettingsMenu ( menuName , parentMenuFunction = None ) : '''Adds a ' open settings . . . ' menu to the plugin menu . This method should be called from the initGui ( ) method of the plugin : param menuName : The name of the plugin menu in which the settings menu is to be added : param parentMenuFunction ...
parentMenuFunction = parentMenuFunction or iface . addPluginToMenu namespace = _callerName ( ) . split ( "." ) [ 0 ] settingsAction = QAction ( QgsApplication . getThemeIcon ( '/mActionOptions.svg' ) , "Plugin Settings..." , iface . mainWindow ( ) ) settingsAction . setObjectName ( namespace + "settings" ) settingsActi...
def get_functions_by_search ( self , function_query , function_search ) : """Pass through to provider FunctionSearchSession . get _ functions _ by _ search"""
# Implemented from azosid template for - # osid . resource . ResourceSearchSession . get _ resources _ by _ search _ template if not self . _can ( 'search' ) : raise PermissionDenied ( ) return self . _provider_session . get_functions_by_search ( function_query , function_search )
def os_details ( ) : """Returns a dictionary containing details about the operating system"""
# Compute architecture and linkage bits , linkage = platform . architecture ( ) results = { # Machine details "platform.arch.bits" : bits , "platform.arch.linkage" : linkage , "platform.machine" : platform . machine ( ) , "platform.process" : platform . processor ( ) , "sys.byteorder" : sys . byteorder , # OS details "...
def deploy_ray_func ( func , partition , kwargs ) : # pragma : no cover """Deploy a function to a partition in Ray . Note : Ray functions are not detected by codecov ( thus pragma : no cover ) Args : func : The function to apply . partition : The partition to apply the function to . kwargs : A dictionary ...
try : return func ( partition , ** kwargs ) # Sometimes Arrow forces us to make a copy of an object before we operate # on it . We don ' t want the error to propagate to the user , and we want to # avoid copying unless we absolutely have to . except ValueError : return func ( partition . copy ( ) , ** kwargs )
def _write_mosaic ( self , key , outfile ) : """Write out mosaic data ( or any new data generated within Ginga ) to single - extension FITS ."""
maxsize = self . settings . get ( 'max_mosaic_size' , 1e8 ) # Default 10k x 10k channel = self . fv . get_channel ( self . chname ) image = channel . datasrc [ key ] # Prevent writing very large mosaic if ( image . width * image . height ) > maxsize : s = 'Mosaic too large to be written {0}' . format ( image . shap...
def normalize_conf ( conf ) : '''Check , convert and adjust user passed config Given a user configuration it returns a verified configuration with all parameters converted to the types that are needed at runtime .'''
conf = conf . copy ( ) # check for type error check_config ( conf ) # convert some fileds into python suitable format from_json_format ( conf ) if 'dmode' not in conf : conf [ 'dmode' ] = calc_dir_mode ( conf [ 'fmode' ] ) return conf
def fit ( self , X , y ) : """Fits the given model to the data and labels provided . Parameters : X : matrix , shape ( n _ samples , n _ features ) The samples , the train data . y : vector , shape ( n _ samples , ) The target labels . Returns : self : instance of the model itself ( ` self ` )"""
X = np . array ( X , dtype = np . float32 ) y = np . array ( y , dtype = np . float32 ) assert X . shape [ 0 ] == y . shape [ 0 ] return X , y
def list_permissions ( self , group_name = None , resource = None ) : """List permission sets associated filtering by group and / or resource . Args : group _ name ( string ) : Name of group . resource ( intern . resource . boss . Resource ) : Identifies which data model object to operate on . Returns : ...
self . project_service . set_auth ( self . _token_project ) return self . project_service . list_permissions ( group_name , resource )
def choicebox ( msg = "Pick something." , title = " " , choices = ( ) ) : """Present the user with a list of choices . return the choice that he selects . return None if he cancels the selection selection . @ arg msg : the msg to be displayed . @ arg title : the window title @ arg choices : a list or tupl...
if len ( choices ) == 0 : choices = [ "Program logic error - no choices were specified." ] global __choiceboxMultipleSelect __choiceboxMultipleSelect = 0 return __choicebox ( msg , title , choices )
async def add_credential ( self , name = None , credential = None , cloud = None , owner = None , force = False ) : """Add or update a credential to the controller . : param str name : Name of new credential . If None , the default local credential is used . Name must be provided if a credential is given . ...
if not cloud : cloud = await self . get_cloud ( ) if not owner : owner = self . connection ( ) . info [ 'user-info' ] [ 'identity' ] if credential and not name : raise errors . JujuError ( 'Name must be provided for credential' ) if not credential : name , credential = self . _connector . jujudata . loa...
def parametrize_peaks ( self , intervals , max_peakwidth = 50 , min_peakwidth = 25 , symmetric_bounds = True ) : """Computes and stores the intonation profile of an audio recording . : param intervals : these will be the reference set of intervals to which peak positions correspond to . For each interval , the ...
assert isinstance ( self . pitch_obj . pitch , np . ndarray ) valid_pitch = self . pitch_obj . pitch valid_pitch = [ i for i in valid_pitch if i > - 10000 ] valid_pitch = np . array ( valid_pitch ) parameters = { } for i in xrange ( len ( self . histogram . peaks [ "peaks" ] [ 0 ] ) ) : peak_pos = self . histogram ...
def remove_child_log ( self , log_id , child_id ) : """Removes a child from a log . arg : log _ id ( osid . id . Id ) : the ` ` Id ` ` of a log arg : child _ id ( osid . id . Id ) : the ` ` Id ` ` of the new child raise : NotFound - ` ` log _ id ` ` not a parent of ` ` child _ id ` ` raise : NullArgument - ...
# Implemented from template for # osid . resource . BinHierarchyDesignSession . remove _ child _ bin _ template if self . _catalog_session is not None : return self . _catalog_session . remove_child_catalog ( catalog_id = log_id , child_id = child_id ) return self . _hierarchy_session . remove_child ( id_ = log_id ...
def as_data_frame ( self , ** kwargs ) : """Return information for all Files tracked in the Layout as a pandas DataFrame . Args : kwargs : Optional keyword arguments passed on to get ( ) . This allows one to easily select only a subset of files for export . Returns : A pandas DataFrame , where each row ...
try : import pandas as pd except ImportError : raise ImportError ( "What are you doing trying to export a Layout " "as a pandas DataFrame when you don't have " "pandas installed? Eh? Eh?" ) if kwargs : files = self . get ( return_type = 'obj' , ** kwargs ) else : files = self . files . values ( ) data =...
def _encode ( self , data : mx . sym . Symbol , data_length : mx . sym . Symbol , seq_len : int ) -> mx . sym . Symbol : """Bidirectionally encodes time - major data ."""
# ( seq _ len , batch _ size , num _ embed ) data_reverse = mx . sym . SequenceReverse ( data = data , sequence_length = data_length , use_sequence_length = True ) # ( seq _ length , batch , cell _ num _ hidden ) hidden_forward , _ , _ = self . forward_rnn . encode ( data , data_length , seq_len ) # ( seq _ length , ba...
def _restripe ( mountpoint , direction , * devices , ** kwargs ) : '''Restripe BTRFS : add or remove devices from the particular mounted filesystem .'''
fs_log = [ ] if salt . utils . fsutils . _is_device ( mountpoint ) : raise CommandExecutionError ( "Mountpount expected, while device \"{0}\" specified" . format ( mountpoint ) ) mounted = False for device , mntpoints in six . iteritems ( salt . utils . fsutils . _get_mounts ( "btrfs" ) ) : for mntdata in mntpo...
def log ( ltype , method , page , user_agent ) : """Writes to the log a message in the following format : : " < datetime > : < exception > method < HTTP method > page < path > user agent < user _ agent > " """
try : f = open ( settings . DJANGOSPAM_LOG , "a" ) f . write ( "%s: %s method %s page %s user agent %s\n" % ( datetime . datetime . now ( ) , ltype , method , page , user_agent ) ) f . close ( ) except : if settings . DJANGOSPAM_FAIL_ON_LOG : exc_type , exc_value = sys . exc_info ( ) [ : 2 ] ...
def get_card_prices ( ctx , currency ) : """Prints out lowest card prices for an application . Comma - separated list of application IDs is supported ."""
appid = ctx . obj [ 'appid' ] detailed = True appids = [ appid ] if ',' in appid : appids = [ appid . strip ( ) for appid in appid . split ( ',' ) ] detailed = False for appid in appids : print_card_prices ( appid , currency , detailed = detailed ) click . echo ( '' )
def create_alignment ( self , x_align = 0 , y_align = 0 , x_scale = 0 , y_scale = 0 ) : """Function creates an alignment"""
align = Gtk . Alignment ( ) align . set ( x_align , y_align , x_scale , y_scale ) return align
def mysql_batch_and_fetch ( mysql_config , * sql_queries ) : """Excute a series of SQL statements before the final Select query Parameters mysql _ config : dict The user credentials as defined in MySQLdb . connect , e . g . mysql _ conig = { ' user ' : ' myname ' , ' passwd ' : ' supersecret ' , ' host ' ...
# load modules import MySQLdb as mydb import sys import gc # ensure that ` sqlqueries ` is a list / tuple # split a string into a list if len ( sql_queries ) == 1 : if isinstance ( sql_queries [ 0 ] , str ) : sql_queries = sql_queries [ 0 ] . split ( ";" ) if isinstance ( sql_queries [ 0 ] , ( list , tu...
def disassemble ( bytecode ) : """Generator . Disassembles Java bytecode into a sequence of ( offset , code , args ) tuples : type bytecode : bytes"""
offset = 0 end = len ( bytecode ) while offset < end : orig_offset = offset code = bytecode [ offset ] if not isinstance ( code , int ) : # Py3 code = ord ( code ) offset += 1 args = tuple ( ) fmt = get_arg_format ( code ) if fmt : args , offset = fmt ( bytecode , offset ) ...
def _is_simple_query ( cls , query ) : """Inspect the internals of the Query and say if we think its WHERE clause can be used in a HANDLER statement"""
return ( not query . low_mark and not query . high_mark and not query . select and not query . group_by and not query . distinct and not query . order_by and len ( query . alias_map ) <= 1 )
def register_course ( self , course_id ) : """履修申請する"""
# 何モジュール開講か取得 kdb = twins . kdb . Kdb ( ) first_module = kdb . get_course_info ( course_id ) [ "modules" ] [ : 2 ] if not first_module . startswith ( "春" ) and not first_module . startswith ( "秋" ) : raise RequestError ( ) module_code , gakkiKbnCode = { "春A" : ( 1 , "A" ) , "春B" : ( 2 , "A" ) , "春C" : ( 3 , "A" ) ...
def create_sys_dsn ( driver : str , ** kw ) -> bool : """( Windows only . ) Create a system ODBC data source name ( DSN ) . Args : driver : ODBC driver name kw : Driver attributes Returns : bool : was the DSN created ?"""
attributes = [ ] # type : List [ str ] for attr in kw . keys ( ) : attributes . append ( "%s=%s" % ( attr , kw [ attr ] ) ) return bool ( ctypes . windll . ODBCCP32 . SQLConfigDataSource ( 0 , ODBC_ADD_SYS_DSN , driver , nul . join ( attributes ) ) )
def inspect_select_calculation ( self ) : """Inspect the result of the CifSelectCalculation , verifying that it produced a CifData output node ."""
try : node = self . ctx . cif_select self . ctx . cif = node . outputs . cif except exceptions . NotExistent : self . report ( 'aborting: CifSelectCalculation<{}> did not return the required cif output' . format ( node . uuid ) ) return self . exit_codes . ERROR_CIF_SELECT_FAILED
def find_handler ( self , request : httputil . HTTPServerRequest , ** kwargs : Any ) -> Optional [ httputil . HTTPMessageDelegate ] : """Must be implemented to return an appropriate instance of ` ~ . httputil . HTTPMessageDelegate ` that can serve the request . Routing implementations may pass additional kwargs...
raise NotImplementedError ( )
def rule_generator ( * funcs ) : """Constructor for creating multivariate quadrature generator . Args : funcs ( : py : data : typing . Callable ) : One dimensional integration rule where each rule returns ` ` abscissas ` ` and ` ` weights ` ` as one dimensional arrays . They must take one positional argum...
dim = len ( funcs ) tensprod_rule = create_tensorprod_function ( funcs ) assert hasattr ( tensprod_rule , "__call__" ) mv_rule = create_mv_rule ( tensprod_rule , dim ) assert hasattr ( mv_rule , "__call__" ) return mv_rule
def wait_for_read_result ( self ) : """This is a utility function to wait for return data call back @ return : Returns resultant data from callback"""
while not self . callback_data : self . board . sleep ( .001 ) rval = self . callback_data self . callback_data = [ ] return rval
def create_binary_security_token ( key_file ) : """Create the BinarySecurityToken node containing the x509 certificate ."""
node = etree . Element ( ns_id ( 'BinarySecurityToken' , ns . wssens ) , nsmap = { ns . wssens [ 0 ] : ns . wssens [ 1 ] } ) node . set ( ns_id ( 'Id' , ns . wsuns ) , get_unique_id ( ) ) node . set ( 'EncodingType' , ns . wssns [ 1 ] + 'Base64Binary' ) node . set ( 'ValueType' , BINARY_TOKEN_TYPE ) with open ( key_fil...
def subscribe ( self , * args , ** kwargs ) : """Subscribe to a publish port . Example : ` vexbot : ! subscribe tcp : / / 127.0.0.1:3000 `"""
for address in args : try : self . messaging . subscription_socket . connect ( address ) except Exception : raise RuntimeError ( 'addresses need to be in the form of: tcp://address_here:port_number' ' example: tcp://10.2.3.4:80' 'address tried {}' . format ( address ) )
def process_path_part ( part , parameters ) : """Given a part of a path either : - If it is a parameter : parse it to a regex group - Otherwise : escape any special regex characters"""
if PARAMETER_REGEX . match ( part ) : parameter_name = part . strip ( '{}' ) try : parameter = find_parameter ( parameters , name = parameter_name , in_ = PATH ) except ValueError : pass else : return construct_parameter_pattern ( parameter ) return escape_regex_special_chars ( p...
def is_tradetime_now ( ) : """判断目前是不是交易时间 , 同时考虑节假日 : return : bool"""
cal = Calendar ( 'china.sse' ) now_time = time . localtime ( ) today = Date ( now_time [ 0 ] , now_time [ 1 ] , now_time [ 2 ] ) if not cal . isBizDay ( today ) : return False now = ( now_time . tm_hour , now_time . tm_min , now_time . tm_sec ) if ( 9 , 15 , 0 ) <= now <= ( 11 , 30 , 0 ) or ( 13 , 0 , 0 ) <= now <=...
def conll_ner2json ( input_data , ** kwargs ) : """Convert files in the CoNLL - 2003 NER format into JSON format for use with train cli ."""
delimit_docs = "-DOCSTART- -X- O O" output_docs = [ ] for doc in input_data . strip ( ) . split ( delimit_docs ) : doc = doc . strip ( ) if not doc : continue output_doc = [ ] for sent in doc . split ( "\n\n" ) : sent = sent . strip ( ) if not sent : continue ...
def load_template ( name = None ) : """Loads a template of the specified name . Templates are placed in the < template _ dir > directory in YAML format with a . yaml extension . If no name is specified then the function will return the default template ( < template _ dir > / default . yaml ) if it exists . ...
if name is None : name = "default" logger . info ( "Loading template with name %s" , name ) try : template_file = open ( "%s/%s.yaml" % ( template_path , name ) ) except IOError : raise TemplateNotFoundError template = yaml . safe_load ( template_file ) template_file . close ( ) if "extends" in template : ...
def get_page ( self , url , * args , ** kwds ) : """Define our own get _ page method so that we can easily override the factory when we need to . This was copied from the following : * twisted . web . client . getPage * twisted . web . client . _ makeGetterFactory"""
contextFactory = None scheme , host , port , path = parse ( url ) data = kwds . get ( 'postdata' , None ) self . _method = method = kwds . get ( 'method' , 'GET' ) self . request_headers = self . _headers ( kwds . get ( 'headers' , { } ) ) if ( self . body_producer is None ) and ( data is not None ) : self . body_p...
def get_all_key_pairs ( self , keynames = None , filters = None ) : """Get all key pairs associated with your account . : type keynames : list : param keynames : A list of the names of keypairs to retrieve . If not provided , all key pairs will be returned . : type filters : dict : param filters : Optiona...
params = { } if keynames : self . build_list_params ( params , keynames , 'KeyName' ) if filters : self . build_filter_params ( params , filters ) return self . get_list ( 'DescribeKeyPairs' , params , [ ( 'item' , KeyPair ) ] , verb = 'POST' )
def __stopOpenThreadWpan ( self ) : """stop OpenThreadWpan Returns : True : successfully stop OpenThreadWpan False : failed to stop OpenThreadWpan"""
print 'call stopOpenThreadWpan' try : if self . __sendCommand ( WPANCTL_CMD + 'leave' ) [ 0 ] != 'Fail' and self . __sendCommand ( WPANCTL_CMD + 'dataset erase' ) [ 0 ] != 'Fail' : return True else : return False except Exception , e : ModuleHelper . WriteIntoDebugLogger ( 'stopOpenThreadWpa...
def update_models ( ctx , f = False ) : """Updates local django db projects models using salic database from MinC"""
if f : manage ( ctx , 'create_models_from_sql --force True' , env = { } ) else : manage ( ctx , 'create_models_from_sql' , env = { } )
def _create_patterns ( self , properties = None ) : """Return a list ( of length patterns _ per _ label ) of PatternGenerator instances . Should use pattern _ type and pattern _ parameters to create each pattern . properties is a dictionary , e . g . { ' pattern _ label ' : pattern _ label } , which can be ...
return [ self . pattern_type ( ** self . pattern_parameters ) for i in range ( self . patterns_per_label ) ]
def imshow ( self , * args , show_crosshair = True , show_mask = True , show_qscale = True , axes = None , invalid_color = 'black' , mask_opacity = 0.8 , show_colorbar = True , ** kwargs ) : """Plot the matrix ( imshow ) Keyword arguments [ and their default values ] : show _ crosshair [ True ] : if a cross - h...
if 'aspect' not in kwargs : kwargs [ 'aspect' ] = 'equal' if 'interpolation' not in kwargs : kwargs [ 'interpolation' ] = 'nearest' if 'origin' not in kwargs : kwargs [ 'origin' ] = 'upper' if show_qscale : ymin , xmin = self . pixel_to_q ( 0 , 0 ) ymax , xmax = self . pixel_to_q ( * self . shape ) ...
def queue_instances ( instances ) : '''Queue a set of instances to be provisioned later . Expects a list . Currently this only queries node data , and then places it in the cloud cache ( if configured ) . If the salt - cloud - reactor is being used , these instances will be automatically provisioned using tha...
for instance_id in instances : node = _get_node ( instance_id = instance_id ) __utils__ [ 'cloud.cache_node' ] ( node , __active_provider_name__ , __opts__ )
def update ( self ) : """Update processes stats using the input method ."""
# Init new stats stats = self . get_init_value ( ) if self . input_method == 'local' : # Update stats using the standard system lib # Here , update is call for processcount AND processlist glances_processes . update ( ) # Return the processes count stats = glances_processes . getcount ( ) elif self . input_...
def _smb3kdf ( self , ki , label , context ) : """See SMB 3 . x key derivation function https : / / blogs . msdn . microsoft . com / openspecification / 2017/05/26 / smb - 2 - and - smb - 3 - security - in - windows - 10 - the - anatomy - of - signing - and - cryptographic - keys / : param ki : The session key ...
kdf = KBKDFHMAC ( algorithm = hashes . SHA256 ( ) , mode = Mode . CounterMode , length = 16 , rlen = 4 , llen = 4 , location = CounterLocation . BeforeFixed , label = label , context = context , fixed = None , backend = default_backend ( ) ) return kdf . derive ( ki )
def stylesheet_url ( path , only_path = False , cache_buster = True ) : """Generates a path to an asset found relative to the project ' s css directory . Passing a true value as the second argument will cause the only the path to be returned instead of a ` url ( ) ` function"""
filepath = String . unquoted ( path ) . value if callable ( config . STATIC_ROOT ) : try : _file , _storage = list ( config . STATIC_ROOT ( filepath ) ) [ 0 ] except IndexError : filetime = None else : filetime = getmtime ( _file , _storage ) if filetime is None : filetim...
def find_by_filter ( self , filters , all_items ) : """Find items by filters : param filters : list of filters : type filters : list : param all _ items : monitoring items : type : dict : return : list of items : rtype : list"""
items = [ ] for i in self : failed = False if hasattr ( i , "host" ) : all_items [ "service" ] = i else : all_items [ "host" ] = i for filt in filters : if not filt ( all_items ) : failed = True break if failed is False : items . append ( i ) r...
def get_key_from_url ( self , url ) : """parses the url into a list of folder locations We take a URL like : http : / / rest . ensembl . org / sequence / id / ENST00000538324 ? type = genomic ; expand _ 3prime = 10 ; expand _ 5prime = 10 and turn it into ' sequence . id . ENST00000538324 . genomic ' Args : ...
key = url . split ( "/" ) [ 3 : ] # fix the final bit of the url , none of which uniquely define the data suffix = key . pop ( ) suffix = suffix . split ( ";" ) [ 0 ] # convert " LONG _ ID ? feature = transcript " to [ ' LONG _ ID ' , " transcript " ] etc id = suffix . split ( "?" , 1 ) suffix = id . pop ( ) if "=" in ...
def merge_webhooks_runset ( runset ) : """Make some statistics on the run set ."""
min_started_at = min ( [ w [ 'started_at' ] for w in runset ] ) max_ended_at = max ( [ w [ 'ended_at' ] for w in runset ] ) ellapse = max_ended_at - min_started_at errors_count = sum ( 1 for w in runset if 'error' in w ) total_count = len ( runset ) data = dict ( ellapse = ellapse , errors_count = errors_count , total_...
def extract_db_info ( self , obj , keys ) : """Extract metadata from serialized file"""
objl = self . convert ( obj ) result = super ( LinesCatalog , self ) . extract_db_info ( objl , keys ) result [ 'tags' ] = { } result [ 'type' ] = 'LinesCatalog' result [ 'uuid' ] = str ( uuid . uuid1 ( ) ) result [ 'observation_date' ] = datetime . datetime . utcnow ( ) result [ 'quality_control' ] = QC . GOOD result ...
def report ( mount ) : '''Report on quotas for a specific volume CLI Example : . . code - block : : bash salt ' * ' quota . report / media / data'''
ret = { mount : { } } ret [ mount ] [ 'User Quotas' ] = _parse_quota ( mount , '-u' ) ret [ mount ] [ 'Group Quotas' ] = _parse_quota ( mount , '-g' ) return ret
def find_two_letter_edits ( word_string ) : '''Finds all possible two letter edits of word _ string : - Splitting word _ string into two words at all character locations - Deleting one letter at all character locations - Switching neighbouring characters - Replacing a character with every alphabetical lette...
if word_string is None : return { } elif isinstance ( word_string , str ) : return ( e2 for e1 in find_one_letter_edits ( word_string ) for e2 in find_one_letter_edits ( e1 ) ) else : raise InputError ( "string or none type variable not passed as argument to find_two_letter_edits" )
def main ( self , args = None , prog_name = None , complete_var = None , standalone_mode = True , ** extra ) : """This is the way to invoke a script with all the bells and whistles as a command line application . This will always terminate the application after a call . If this is not wanted , ` ` SystemExit ` ...
# If we are in Python 3 , we will verify that the environment is # sane at this point or reject further execution to avoid a # broken script . if not PY2 : _verify_python3_env ( ) else : _check_for_unicode_literals ( ) if args is None : args = get_os_args ( ) else : args = list ( args ) if prog_name is ...
def lineWidth ( requestContext , seriesList , width ) : """Takes one metric or a wildcard seriesList , followed by a float F . Draw the selected metrics with a line width of F , overriding the default value of 1 , or the & lineWidth = X . X parameter . Useful for highlighting a single metric out of many , or ...
for series in seriesList : series . options [ 'lineWidth' ] = width return seriesList
def decode ( binary ) : """Decode ( gunzip ) binary data ."""
encoded = io . BytesIO ( binary ) with gzip . GzipFile ( mode = 'rb' , fileobj = encoded ) as file_ : decoded = file_ . read ( ) return decoded