signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def set_min_string_length ( self , length = None ) : """stub"""
if self . get_min_string_length_metadata ( ) . is_read_only ( ) : raise NoAccess ( ) if not self . my_osid_object_form . _is_valid_cardinal ( length , self . get_min_string_length_metadata ( ) ) : raise InvalidArgument ( ) if self . my_osid_object_form . max_string_length is not None and length > self . my_osid...
def get_keys_for ( self , value ) : """Get keys for a given value . : param value : The value to look for : type value : object : return : The keys for the given value : rtype : list ( str )"""
if callable ( value ) : return value ( self ) hash_value = self . get_hash_for ( value ) return self . _index [ hash_value ] [ : ]
def _draw_ap_score ( self , score , label = None ) : """Helper function to draw the AP score annotation"""
label = label or "Avg Precision={:0.2f}" . format ( score ) if self . ap_score : self . ax . axhline ( y = score , color = "r" , ls = "--" , label = label )
async def connect ( self ) : """Create connection pool asynchronously ."""
self . pool = await aiomysql . create_pool ( loop = self . loop , db = self . database , connect_timeout = self . timeout , ** self . connect_params )
def get ( self , name , strict = True ) : """Get an attribute of the holder ( read - only access ) ."""
if not isinstance ( name , str ) or name . startswith ( '_' ) : raise AttributeError ( self . __class__ . __name__ , name ) elif strict and name not in self . _possible_attributes : raise AttributeError ( '%s is not a valid attribute of %r.' % ( name , self ) ) elif name in self . _attributes : return self ...
def register ( self , source_point_cloud , target_point_cloud , source_normal_cloud , target_normal_cloud , matcher , num_iterations = 1 , compute_total_cost = True , match_centroids = False , vis = False ) : """Iteratively register objects to one another . Parameters source _ point _ cloud : : obj : ` autolab ...
pass
def __getURL ( self , page = 1 , start_date = None , final_date = None , order = "asc" ) : """Get the API ' s URL to query to get data about users . : param page : number of the page . : param start _ date : start date of the range to search users ( Y - m - d ) . " param final _ date : final date of the ran...
if not start_date or not final_date : url = self . __server + "search/users?client_id=" + self . __githubID + "&client_secret=" + self . __githubSecret + "&order=desc&q=sort:joined+type:user" + self . __urlLocations + self . __urlFilters + "&sort=joined&order=asc&per_page=100&page=" + str ( page ) else : url = ...
def _response_item_to_object ( self , resp_item ) : """take json and make a resource out of it"""
item_cls = resources . get_model_class ( self . resource_type ) properties_dict = resp_item [ self . resource_type ] new_dict = helpers . remove_properties_containing_None ( properties_dict ) # raises exception if something goes wrong obj = item_cls ( new_dict ) return obj
def insert ( self , index , child , rel = None , type = None , media = None , condition = None , ** kwargs ) : '''Append a link to this container . : param child : a string indicating the location of the linked document : param rel : Specifies the relationship between the document and the linked document . ...
if child : srel = 'stylesheet' stype = 'text/css' minify = rel in ( None , srel ) and type in ( None , stype ) path = self . absolute_path ( child , minify = minify ) if path . endswith ( '.css' ) : rel = rel or srel type = type or stype value = Html ( 'link' , href = path , rel ...
def _toState ( self , state , * args , ** kwargs ) : """Transition to the next state . @ param state : Name of the next state ."""
try : method = getattr ( self , '_state_%s' % state ) except AttributeError : raise ValueError ( "No such state %r" % state ) log . msg ( "%s: to state %r" % ( self . __class__ . __name__ , state ) ) self . _state = state method ( * args , ** kwargs )
def find_discordant_snps ( self , individual1 , individual2 , individual3 = None , save_output = False ) : """Find discordant SNPs between two or three individuals . Parameters individual1 : Individual reference individual ( child if ` individual2 ` and ` individual3 ` are parents ) individual2 : Individual...
self . _remap_snps_to_GRCh37 ( [ individual1 , individual2 , individual3 ] ) df = individual1 . snps # remove nulls for reference individual df = df . loc [ df [ "genotype" ] . notnull ( ) ] # add SNPs shared with ` individual2 ` df = df . join ( individual2 . snps [ "genotype" ] , rsuffix = "2" ) genotype1 = "genotype...
def validate ( data = None , schema_id = None , filepath = None , root = None , definition = None , specs = None , validation_function = None , validation_error_handler = None ) : """This method is available to use YAML swagger definitions file or specs ( dict or object ) to validate data against its jsonschema ....
schema_id = schema_id or definition # for backwards compatibility with function signature if filepath is None and specs is None : abort ( Response ( 'Filepath or specs is needed to validate' , status = 500 ) ) if data is None : data = request . json # defaults elif callable ( data ) : # data = lambda : requ...
def get ( self , sid ) : """Constructs a AssignedAddOnExtensionContext : param sid : The unique string that identifies the resource : returns : twilio . rest . api . v2010 . account . incoming _ phone _ number . assigned _ add _ on . assigned _ add _ on _ extension . AssignedAddOnExtensionContext : rtype : tw...
return AssignedAddOnExtensionContext ( self . _version , account_sid = self . _solution [ 'account_sid' ] , resource_sid = self . _solution [ 'resource_sid' ] , assigned_add_on_sid = self . _solution [ 'assigned_add_on_sid' ] , sid = sid , )
def put ( self , key , data , ttl_secs = None ) : """Like : meth : ` ~ simplekv . KeyValueStore . put ` , but with an additional parameter : : param ttl _ secs : Number of seconds until the key expires . See above for valid values . : raises exceptions . ValueError : If ` ` ttl _ secs ` ` is invalid . : r...
self . _check_valid_key ( key ) if not isinstance ( data , bytes ) : raise IOError ( "Provided data is not of type bytes" ) return self . _put ( key , data , self . _valid_ttl ( ttl_secs ) )
def mutateString ( original , n , replacements = 'acgt' ) : """Mutate C { original } in C { n } places with chars chosen from C { replacements } . @ param original : The original C { str } to mutate . @ param n : The C { int } number of locations to mutate . @ param replacements : The C { str } of replacement...
if not original : raise ValueError ( 'Empty original string passed.' ) if n > len ( original ) : raise ValueError ( 'Cannot make %d mutations in a string of length %d' % ( n , len ( original ) ) ) if len ( replacements ) != len ( set ( replacements ) ) : raise ValueError ( 'Replacement string contains dupli...
async def send_message ( self , request : str , response_expected : bool , ** kwargs : Any ) -> Response : """Transport the message to the server and return the response . Args : request : The JSON - RPC request string . response _ expected : Whether the request expects a response . Returns : A Response o...
with async_timeout . timeout ( self . timeout ) : async with self . session . post ( self . endpoint , data = request , ssl = self . ssl ) as response : response_text = await response . text ( ) return Response ( response_text , raw = response )
def collect ( self ) : """Collects all metrics attached to this metricset , and returns it as a list , together with a timestamp in microsecond precision . The format of the return value should be " samples " : { " metric . name " : { " value " : some _ float } , . . . } , " timestamp " : unix epoch in micr...
samples = { } if self . _counters : samples . update ( { label : { "value" : c . val } for label , c in compat . iteritems ( self . _counters ) if c is not noop_metric } ) if self . _gauges : samples . update ( { label : { "value" : g . val } for label , g in compat . iteritems ( self . _gauges ) if g is not no...
def _set_id_field ( new_class ) : """Lookup the id field for this entity and assign"""
# FIXME What does it mean when there are no declared fields ? # Does it translate to an abstract entity ? if new_class . meta_ . declared_fields : try : new_class . meta_ . id_field = next ( field for _ , field in new_class . meta_ . declared_fields . items ( ) if field . identifier ) except StopIterati...
def delete ( self , commit = True ) : """Delete model from database"""
db . session . delete ( self ) return commit and db . session . commit ( )
def get_upload_form ( self ) : """Construct form for accepting file upload ."""
return self . form_class ( self . request . POST , self . request . FILES )
def old_encode_aes ( key , plaintext ) : """Utility method to encode some given plaintext with the given key . Important thing to note : This is not a general purpose encryption method - it has specific semantics ( see below for details ) . Takes the given key , pads it to 32 bytes . Then takes the given plai...
# generate 16 cryptographically secure random bytes for our IV ( initial value ) iv = os . urandom ( 16 ) # set up an AES cipher object cipher = AES . new ( ensure_bytes ( old_pad ( key ) ) , mode = AES . MODE_CBC , IV = iv ) # encrypte the plaintext after padding it ciphertext = cipher . encrypt ( ensure_bytes ( old_p...
def author_to_dict ( obj ) : """Who needs a switch / case statement when you can instead use this easy to comprehend drivel ?"""
def default ( ) : raise RuntimeError ( "unsupported type {t}" . format ( t = type ( obj ) . __name__ ) ) # a more pythonic way to handle this would be several try blocks to catch # missing attributes return { # GitAuthor has name , email , date properties 'GitAuthor' : lambda x : { 'name' : x . name , 'email' : x ....
def deltas ( last , now ) : """Return the change in counter values ( accounting for wrap - around ) ."""
return { xy : RouterDiagnostics ( * ( ( n - l ) & 0xFFFFFFFF for l , n in zip ( last [ xy ] , now [ xy ] ) ) ) for xy in last }
def remove_parameter ( self , name ) : """Remove the specified parameter from this query : param name : name of a parameter to remove : return : None"""
if name in self . __query : self . __query . pop ( name )
def CompleteTransaction ( self , dumpXml = None ) : """Completes a transaction . This method completes a transaction by sending the final configuration ( modification queries stored in configMap ) to UCS and returns the result ."""
from Ucs import ConfigMap , Pair from UcsBase import ManagedObject , WriteUcsWarning , WriteObject , UcsException self . _transactionInProgress = False ccm = self . ConfigConfMos ( self . _configMap , YesOrNo . FALSE , dumpXml ) self . _configMap = ConfigMap ( ) if ccm . errorCode == 0 : moList = [ ] for child ...
def set_block_entity_data ( self , pos_or_x , y = None , z = None , data = None ) : """Update block entity data . Returns : Old data if block entity data was already stored for that location , None otherwise ."""
if None not in ( y , z ) : # x y z supplied pos_or_x = pos_or_x , y , z coord_tuple = tuple ( int ( floor ( c ) ) for c in pos_or_x ) old_data = self . block_entities . get ( coord_tuple , None ) self . block_entities [ coord_tuple ] = data return old_data
def source ( uri , consts ) : '''read gl code'''
with open ( uri , 'r' ) as fp : content = fp . read ( ) # feed constant values for key , value in consts . items ( ) : content = content . replace ( f"%%{key}%%" , str ( value ) ) return content
def find_window ( className = None , windowName = None ) : """Find the first top - level window in the current desktop to match the given class name and / or window name . If neither are provided any top - level window will match . @ see : L { get _ window _ at } @ type className : str @ param className :...
# I ' d love to reverse the order of the parameters # but that might create some confusion . : ( hWnd = win32 . FindWindow ( className , windowName ) if hWnd : return Window ( hWnd )
def get_language_tabs ( self , request , obj , available_languages , css_class = None ) : """Determine the language tabs to show ."""
current_language = self . get_form_language ( request , obj ) return get_language_tabs ( request , current_language , available_languages , css_class = css_class )
def posterior_samples_f ( self , X , size = 10 , ** predict_kwargs ) : """Samples the posterior GP at the points X . : param X : The points at which to take the samples . : type X : np . ndarray ( Nnew x self . input _ dim ) : param size : the number of a posteriori samples . : type size : int . : returns...
predict_kwargs [ "full_cov" ] = True # Always use the full covariance for posterior samples . m , v = self . _raw_predict ( X , ** predict_kwargs ) if self . normalizer is not None : m , v = self . normalizer . inverse_mean ( m ) , self . normalizer . inverse_variance ( v ) def sim_one_dim ( m , v ) : return np...
def police_priority_map_exceed_map_pri6_exceed ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) police_priority_map = ET . SubElement ( config , "police-priority-map" , xmlns = "urn:brocade.com:mgmt:brocade-policer" ) name_key = ET . SubElement ( police_priority_map , "name" ) name_key . text = kwargs . pop ( 'name' ) exceed = ET . SubElement ( police_priority_map , "exceed" ) m...
def display_waypoints ( wploader , map ) : '''display the waypoints'''
mission_list = wploader . view_list ( ) polygons = wploader . polygon_list ( ) map . add_object ( mp_slipmap . SlipClearLayer ( 'Mission' ) ) for i in range ( len ( polygons ) ) : p = polygons [ i ] if len ( p ) > 1 : map . add_object ( mp_slipmap . SlipPolygon ( 'mission %u' % i , p , layer = 'Mission'...
def overlap_tokens ( doc , other_doc ) : """Get the tokens from the original Doc that are also in the comparison Doc ."""
overlap = [ ] other_tokens = [ token . text for token in other_doc ] for token in doc : if token . text in other_tokens : overlap . append ( token ) return overlap
def create ( self , request , project ) : """Add a new relation between a job and a bug ."""
job_id = int ( request . data [ 'job_id' ] ) bug_id = int ( request . data [ 'bug_id' ] ) try : BugJobMap . create ( job_id = job_id , bug_id = bug_id , user = request . user , ) message = "Bug job map saved" except IntegrityError : message = "Bug job map skipped: mapping already exists" return Response ( {...
def envelope ( self ) : """Returns the address of the envelope sender address ( SMTP from , if not set the sender , if this one isn ' t set too , the author ) ."""
if not self . sender and not self . author : raise ValueError ( "Unable to determine message sender; no author or sender defined." ) return self . sender or self . author [ 0 ]
def sub_dirs ( path , invisible = False ) : """Child directories ( non - recursive )"""
dirs = [ x for x in os . listdir ( path ) if os . path . isdir ( os . path . join ( path , x ) ) ] if not invisible : dirs = [ x for x in dirs if not x . startswith ( '.' ) ] return dirs
def _load_github_hooks ( github_url = 'https://api.github.com' ) : """Request GitHub ' s IP block from their API . Return the IP network . If we detect a rate - limit error , raise an error message stating when the rate limit will reset . If something else goes wrong , raise a generic 503."""
try : resp = requests . get ( github_url + '/meta' ) if resp . status_code == 200 : return resp . json ( ) [ 'hooks' ] else : if resp . headers . get ( 'X-RateLimit-Remaining' ) == '0' : reset_ts = int ( resp . headers [ 'X-RateLimit-Reset' ] ) reset_string = time . s...
def get_access_token ( self , code ) : """Gets the access token for the app given the code Parameters : - code - the response code"""
payload = { 'redirect_uri' : self . redirect_uri , 'code' : code , 'grant_type' : 'authorization_code' } headers = self . _make_authorization_headers ( ) response = requests . post ( self . OAUTH_TOKEN_URL , data = payload , headers = headers , verify = LOGIN_VERIFY_SSL_CERT ) if response . status_code is not 200 : ...
def export_true_table ( ) : """Export value , checker function output true table . Help to organize thought . klass . _ _ dict _ _ 指的是在类定义中定义的 , 从父类继承而来的不在此中 。"""
tester_list = [ ( "inspect.isroutine" , lambda v : inspect . isroutine ( v ) ) , ( "inspect.isfunction" , lambda v : inspect . isfunction ( v ) ) , ( "inspect.ismethod" , lambda v : inspect . ismethod ( v ) ) , ( "isinstance.property" , lambda v : isinstance ( v , property ) ) , ( "isinstance.staticmethod" , lambda v :...
def run ( self , sqlTail = '' , raw = False ) : """Compile filters and run the query and returns the entire result . You can use sqlTail to add things such as order by . If raw , returns the raw tuple data ( not wrapped into a raba object )"""
sql , sqlValues = self . getSQLQuery ( ) cur = self . con . execute ( '%s %s' % ( sql , sqlTail ) , sqlValues ) res = [ ] for v in cur : if not raw : res . append ( RabaPupa ( self . rabaClass , v [ 0 ] ) ) else : return v return res
def get_session ( ) : """Gets a session . If there ' s no yet , creates one . : returns : a session"""
if hasattr ( g , 'session' ) : return g . session sess = create_session ( bind = current_app . config [ 'DATABASE_ENGINE' ] ) try : g . session = sess except RuntimeError : pass return sess
def get_season_stats ( self , season_key ) : """Calling Season Stats API . Arg : season _ key : key of the season Return : json data"""
season_stats_url = self . api_path + "season/" + season_key + "/stats/" response = self . get_response ( season_stats_url ) return response
def list_endpoint_groups ( self , retrieve_all = True , ** _params ) : """Fetches a list of all VPN endpoint groups for a project ."""
return self . list ( 'endpoint_groups' , self . endpoint_groups_path , retrieve_all , ** _params )
def update_authoring_nodes ( self , editor ) : """Updates given editor Model authoring nodes . : param editor : Editor . : type editor : Editor : return : Method success . : rtype : bool"""
editor_node = foundations . common . get_first_item ( self . get_editor_nodes ( editor ) ) file_node = editor_node . parent file = editor . file file_node . name = editor_node . name = os . path . basename ( file ) file_node . path = editor_node . path = file self . node_changed ( file_node ) return True
def get_quality ( self , qual_idx = None ) : """Get the signal qualifier , using shortcuts or combobox ."""
if self . annot is None : # remove if buttons are disabled msg = 'No score file loaded' error_dialog = QErrorMessage ( ) error_dialog . setWindowTitle ( 'Error getting quality' ) error_dialog . showMessage ( msg ) error_dialog . exec ( ) lg . debug ( msg ) return window_start = self . parent...
def _extend_module_definitions ( self , graph ) : """Using collected module definitions extend linkages"""
for mod_id in self . _modules : mod_identity = self . _get_triplet_value ( graph , URIRef ( mod_id ) , SBOL . module ) modules = [ ] for mod in graph . triples ( ( mod_identity , SBOL . module , None ) ) : md = self . _get_rdf_identified ( graph , mod [ 2 ] ) definition_id = self . _get_trip...
def check_for_uncombined_files ( self ) : """Go through working directory and check for uncombined files . ( I . e . , location1 _ specimens . txt and location2 _ specimens . txt but no specimens . txt . ) Show a warning if uncombined files are found . Return True if no uncombined files are found OR user elec...
wd_files = os . listdir ( self . WD ) if self . data_model_num == 2 : ftypes = [ 'er_specimens.txt' , 'er_samples.txt' , 'er_sites.txt' , 'er_locations.txt' , 'pmag_specimens.txt' , 'pmag_samples.txt' , 'pmag_sites.txt' , 'rmag_specimens.txt' , 'rmag_results.txt' , 'rmag_anisotropy.txt' ] else : ftypes = [ 'spe...
def _gen_delta_depend ( self , path , derivative , multiplier , prettyname , device ) : """For some metrics we need to divide the delta for one metric with the delta of another . Publishes a metric if the convertion goes well ."""
primary_delta = derivative [ path ] shortpath = "." . join ( path . split ( "." ) [ : - 1 ] ) basename = path . split ( "." ) [ - 1 ] secondary_delta = None if basename in self . DIVIDERS . keys ( ) : mateKey = "." . join ( [ shortpath , self . DIVIDERS [ basename ] ] ) else : return if mateKey in derivative . ...
def cashdraw ( self , pin ) : """Send pulse to kick the cash drawer"""
if pin == 2 : self . _raw ( CD_KICK_2 ) elif pin == 5 : self . _raw ( CD_KICK_5 ) else : raise CashDrawerError ( )
def to_yaml ( cls , config , compact = False , indent = 2 , level = 0 ) : """Convert HOCON input into a YAML output : return : YAML string representation : type return : basestring"""
lines = "" if isinstance ( config , ConfigTree ) : if len ( config ) > 0 : if level > 0 : lines += '\n' bet_lines = [ ] for key , item in config . items ( ) : bet_lines . append ( '{indent}{key}: {value}' . format ( indent = '' . rjust ( level * indent , ' ' ) , key =...
def deserialize ( self , obj = None , ignore_non_existing = False ) : """: type obj dict | None : type ignore _ non _ existing bool"""
if not isinstance ( obj , dict ) : if ignore_non_existing : return raise TypeError ( "Wrong data '{}' passed for '{}' deserialization" . format ( obj , self . __class__ . __name__ ) ) definitions = { k : v for k , v in self . __class__ . __dict__ . items ( ) if k [ : 1 ] != "_" } def_property_keys = set...
def gen_checkbox_view ( sig_dic ) : '''for checkbox'''
view_zuoxiang = ''' <div class="col-sm-4"><span class="des">{0}</span></div> <div class="col-sm-8"> ''' . format ( sig_dic [ 'zh' ] ) dic_tmp = sig_dic [ 'dic' ] for key in dic_tmp . keys ( ) : tmp_str = ''' <span> {{% if "{0}" in postinfo.extinfo["{1}"] %}} {2} {{% e...
def stop ( self ) : """Stops playback"""
if self . isPlaying is True : self . _execute ( "stop" ) self . _changePlayingState ( False )
def to_sysbase ( self ) : """Convert model parameters to system base . This function calls the ` ` data _ to _ sys _ base ` ` function of the loaded models . Returns None"""
if self . config . base : for item in self . devman . devices : self . __dict__ [ item ] . data_to_sys_base ( )
def get_loss ( self , y_pred , y_true , X = None , training = False ) : """Return the loss for this batch . Parameters y _ pred : torch tensor Predicted target values y _ true : torch tensor True target values . X : input data , compatible with skorch . dataset . Dataset By default , you should be abl...
y_true = to_tensor ( y_true , device = self . device ) return self . criterion_ ( y_pred , y_true )
def get_attributes ( self , sids , flds , ** overrides ) : """Check cache first , then defer to data manager : param sids : security identifiers : param flds : fields to retrieve : param overrides : key - value pairs to pass to the mgr get _ attributes method : return : DataFrame with flds as columns and si...
# Unfortunately must be inefficient with request flds = _force_array ( flds ) sids = _force_array ( sids ) cached = self . _cache_get_attribute ( sids , flds , ** overrides ) if not cached : # build get df = self . dm . get_attributes ( sids , flds , ** overrides ) [ self . _cache_update_attribute ( sid , df . ...
def to_xml ( self , xmllint = False ) : """Serialize all properties as pretty - printed XML Args : xmllint ( boolean ) : Format with ` ` xmllint ` ` in addition to pretty - printing"""
root = self . _tree . getroot ( ) ret = ET . tostring ( ET . ElementTree ( root ) , pretty_print = True ) if xmllint : ret = xmllint_format ( ret ) return ret
def repeats ( seq , size ) : '''Count times that a sequence of a certain size is repeated . : param seq : Input sequence . : type seq : coral . DNA or coral . RNA : param size : Size of the repeat to count . : type size : int : returns : Occurrences of repeats and how many : rtype : tuple of the matched...
seq = str ( seq ) n_mers = [ seq [ i : i + size ] for i in range ( len ( seq ) - size + 1 ) ] counted = Counter ( n_mers ) # No one cares about patterns that appear once , so exclude them found_repeats = [ ( key , value ) for key , value in counted . iteritems ( ) if value > 1 ] return found_repeats
async def _start_payloads ( self ) : """Start all queued payloads"""
with self . _lock : for coroutine in self . _payloads : task = self . event_loop . create_task ( coroutine ( ) ) self . _tasks . add ( task ) self . _payloads . clear ( ) await asyncio . sleep ( 0 )
def undo ( self , i = - 1 ) : """Undo an item in the history logs : parameter int i : integer for indexing ( can be positive or negative ) . Defaults to - 1 if not provided ( the latest recorded history item ) : raises ValueError : if no history items have been recorded"""
_history_enabled = self . history_enabled param = self . get_history ( i ) self . disable_history ( ) param . undo ( ) # TODO : do we really want to remove this ? then what ' s the point of redo ? self . remove_parameter ( uniqueid = param . uniqueid ) if _history_enabled : self . enable_history ( )
def run ( self ) : """Main thread function to maintain connection and receive remote status ."""
_LOGGER . info ( "Started" ) while True : self . _maybe_reconnect ( ) line = '' try : # If someone is sending a command , we can lose our connection so grab a # copy beforehand . We don ' t need the lock because if the connection is # open , we are the only ones that will read from telnet ( the reco...
def create_instance ( credentials , project , zone , name , startup_script = None , startup_script_url = None , metadata = None , machine_type = 'f1-micro' , tags = None , disk_size_gb = 10 , wait_until_done = False ) : """Create instance with startup script . TODO : docstring"""
if startup_script is not None and startup_script_url is not None : raise ValueError ( 'Cannot specify a startup script string and URL ' 'at the same time!' ) access_token = credentials . get_access_token ( ) if metadata is None : metadata = { } meta_items = [ { 'key' : k , 'value' : v } for k , v in metadata . ...
def _pars_total_indexes ( names , dims , fnames , pars ) : """Obtain all the indexes for parameters ` pars ` in the sequence of names . ` names ` references variables that are in column - major order Parameters names : sequence of str All the parameter names . dim : sequence of list of int Dimensions , ...
starts = _calc_starts ( dims ) def par_total_indexes ( par ) : # if ` par ` is a scalar , it will match one of ` fnames ` if par in fnames : p = fnames . index ( par ) idx = tuple ( [ p ] ) return OrderedDict ( [ ( par , idx ) , ( par + '_rowmajor' , idx ) ] ) else : p = names . ...
def get_small_image ( self , page = 1 ) : """Downloads and returns the small sized image of a single page . The page kwarg specifies which page to return . One is the default ."""
url = self . get_small_image_url ( page = page ) return self . _get_url ( url )
def _install_interrupt_handler ( ) : """Suppress KeyboardInterrupt traceback display in specific situations If not running in dev mode , and if executed from the command line , then we raise SystemExit instead of KeyboardInterrupt . This provides a clean exit . : returns : None if no action is taken , origi...
# These would clutter the quilt . x namespace , so they ' re imported here instead . import os import sys import signal import pkg_resources from . tools import const # Check to see what entry points / scripts are configred to run quilt from the CLI # By doing this , we have these benefits : # * Avoid closing someone '...
def shift ( x , offset , dim , wrap , name = None ) : """Shift operation . Shift x right by + offset in dimension dim . Args : x : a Tensor offset : an integer . If negative , shift left instead of right . dim : a Dimension of x wrap : a boolean - whether to wrap ( True ) or pad with zeros ( False ) . ...
return ShiftOperation ( x , offset , dim , wrap , name = name ) . outputs [ 0 ]
def init_match_settings ( self ) : """Adds all items to the match settings comboboxes : return :"""
self . mode_type_combobox . addItems ( game_mode_types ) self . map_type_combobox . addItems ( map_types )
def lemma ( lemma_key ) : """Returns the Lemma object with the given key . Parameters lemma _ key : str Key of the returned lemma . Returns Lemma Lemma matching the ` lemma _ key ` ."""
if lemma_key in LEMMAS_DICT : return LEMMAS_DICT [ lemma_key ] split_lemma_key = lemma_key . split ( '.' ) synset_key = '.' . join ( split_lemma_key [ : 3 ] ) lemma_literal = split_lemma_key [ 3 ] lemma_obj = Lemma ( synset_key , lemma_literal ) LEMMAS_DICT [ lemma_key ] = lemma_obj return lemma_obj
def _dispatch_call_args ( cls = None , bound_call = None , unbound_call = None , attr = '_call' ) : """Check the arguments of ` ` _ call ( ) ` ` or similar for conformity . The ` ` _ call ( ) ` ` method of ` Operator ` is allowed to have the following signatures : Python 2 and 3: - ` ` _ call ( self , x ) `...
py3 = ( sys . version_info . major > 2 ) specs = [ '_call(self, x[, **kwargs])' , '_call(self, x, out[, **kwargs])' , '_call(self, x, out=None[, **kwargs])' ] if py3 : specs += [ '_call(self, x, *, out=None[, **kwargs])' ] spec_msg = "\nPossible signatures are ('[, **kwargs]' means optional):\n\n" spec_msg += '\n' ...
def ensure_dir_exists ( cls , filepath ) : """Ensure that a directory exists If it doesn ' t exist , try to create it and protect against a race condition if another process is doing the same ."""
directory = os . path . dirname ( filepath ) if directory != '' and not os . path . exists ( directory ) : try : os . makedirs ( directory ) except OSError as e : if e . errno != errno . EEXIST : raise
def resource_name ( cls ) : """Represents the resource name"""
if cls . __name__ == "NURESTRootObject" or cls . __name__ == "NURESTObject" : return "Not Implemented" if cls . __resource_name__ is None : raise NotImplementedError ( '%s has no defined resource name. Implement resource_name property first.' % cls ) return cls . __resource_name__
def get_push_command ( self , remote = None , revision = None ) : """Get the command to push changes from the local repository to a remote repository ."""
if revision : raise NotImplementedError ( compact ( """ Bazaar repository support doesn't include the ability to push specific revisions! """ ) ) command = [ 'bzr' , 'push' ] if remote : command . append ( remote ) return command
def history ( ctx , archive_name ) : '''Get archive history'''
_generate_api ( ctx ) var = ctx . obj . api . get_archive ( archive_name ) click . echo ( pprint . pformat ( var . get_history ( ) ) )
def exists_uda ( self , name , database = None ) : """Checks if a given UDAF exists within a specified database Parameters name : string , UDAF name database : string , database name Returns if _ exists : boolean"""
return len ( self . list_udas ( database = database , like = name ) ) > 0
def list_to_csv ( my_list , csv_file ) : """Save a matrix ( list of lists ) to a file as a CSV . . code : : python my _ list = [ [ " Name " , " Location " ] , [ " Chris " , " South Pole " ] , [ " Harry " , " Depth of Winter " ] , [ " Bob " , " Skull " ] ] reusables . list _ to _ csv ( my _ list , " exam...
if PY3 : csv_handler = open ( csv_file , 'w' , newline = '' ) else : csv_handler = open ( csv_file , 'wb' ) try : writer = csv . writer ( csv_handler , delimiter = ',' , quoting = csv . QUOTE_ALL ) writer . writerows ( my_list ) finally : csv_handler . close ( )
def analyze_log ( fp , configs , url_rules ) : """Analyze log file"""
url_classifier = URLClassifier ( url_rules ) analyzer = LogAnalyzer ( url_classifier = url_classifier , min_msecs = configs . min_msecs ) for line in fp : analyzer . analyze_line ( line ) return analyzer . get_data ( )
def find_octagonal_number ( n ) : """This function calculates the nth octagonal number . An Octagonal number is a figurate number that represents an octagon . The octagonal number for n is given by the formula : 3 * n ^ 2 - 2 * n . Examples : find _ octagonal _ number ( 5 ) - > 65 find _ octagonal _ numbe...
return 3 * n * n - 2 * n
def output_summary ( self , output_stream = sys . stdout ) : """outputs a usage tip and the list of acceptable commands . This is useful as the output of the ' help ' option . parameters : output _ stream - an open file - like object suitable for use as the target of a print function"""
if self . app_name or self . app_description : print ( 'Application: ' , end = '' , file = output_stream ) if self . app_name : print ( self . app_name , self . app_version , file = output_stream ) if self . app_description : print ( self . app_description , file = output_stream ) if self . app_name or self...
def validate_one_touch_signature ( self , signature , nonce , method , url , params ) : """Function to validate signature in X - Authy - Signature key of headers . : param string signature : X - Authy - Signature key of headers . : param string nonce : X - Authy - Signature - Nonce key of headers . : param st...
if not signature or not isinstance ( signature , str ) : raise AuthyFormatException ( "Invalid signature - should not be empty. It is required" ) if not nonce : raise AuthyFormatException ( "Invalid nonce - should not be empty. It is required" ) if not method or not ( 'get' == method . lower ( ) or 'post' == me...
def _docstring_getblocks ( self ) : """Gets the longest continuous block of docstrings from the buffer code string if any of those lines are docstring lines ."""
# If there are no lines to look at , we have nothing to do here . if self . ibuffer [ 0 ] == self . ibuffer [ 1 ] : return [ ] lines = self . context . bufferstr [ self . ibuffer [ 0 ] : self . ibuffer [ 1 ] ] docblock = [ ] result = [ ] self . _doclines = [ ] # We need to keep track of the line number for the star...
def _chimera_neighbors ( M , N , L , q ) : "Returns a list of neighbors of ( x , y , u , k ) in a perfect : math : ` C _ { M , N , L } `"
( x , y , u , k ) = q n = [ ( x , y , 1 - u , l ) for l in range ( L ) ] if u == 0 : if x : n . append ( ( x - 1 , y , u , k ) ) if x < M - 1 : n . append ( ( x + 1 , y , u , k ) ) else : if y : n . append ( ( x , y - 1 , u , k ) ) if y < N - 1 : n . append ( ( x , y + 1 ...
def project_texture ( texture_xy , texture_z , angle = DEFAULT_ANGLE ) : """Creates a texture by adding z - values to an existing texture and projecting . When working with surfaces there are two ways to accomplish the same thing : 1 . project the surface and map a texture to the projected surface 2 . map a t...
z_coef = np . sin ( np . radians ( angle ) ) y_coef = np . cos ( np . radians ( angle ) ) surface_x , surface_y = texture return ( surface_x , - surface_y * y_coef + surface_z * z_coef )
def as_colr ( self , label_args = None , type_args = None , value_args = None ) : """Like _ _ str _ _ , except it returns a colorized Colr instance ."""
label_args = label_args or { 'fore' : 'red' } type_args = type_args or { 'fore' : 'yellow' } value_args = value_args or { 'fore' : 'blue' , 'style' : 'bright' } return Colr ( self . default_format . format ( label = Colr ( ':\n ' ) . join ( Colr ( 'Expecting style value' , ** label_args ) , Colr ( ',\n ' ) . join...
def writeMibObjects ( self , * varBinds , ** context ) : """Create , destroy or modify Managed Objects Instances . Given one or more py : class : ` ~ pysnmp . smi . rfc1902 . ObjectType ` objects , create , destroy or modify all or none of the referenced Managed Objects Instances . If a non - existing Managed...
if 'cbFun' not in context : context [ 'cbFun' ] = self . _defaultErrorHandler self . flipFlopFsm ( self . FSM_WRITE_VAR , * varBinds , ** context )
def editRecord ( self , record , pos = None ) : """Prompts the user to edit using a preset editor defined in the setRecordEditors method . : param record | < orb . Table > : return < bool > | success"""
typ = type ( record ) editor = self . _recordEditors . get ( typ ) if not editor : return False if self . popupEditing ( ) : popup = self . popupWidget ( ) edit = popup . centralWidget ( ) # create a new editor if required if type ( edit ) != editor : if edit : edit . close ( ) ...
def extract_pp_helices ( in_pdb ) : """Uses DSSP to find polyproline helices in a pdb file . Returns a length 3 list with a helix id , the chain id and a dict containing the coordinates of each residues CA . Parameters in _ pdb : string Path to a PDB file ."""
t_phi = - 75.0 t_phi_d = 29.0 t_psi = 145.0 t_psi_d = 29.0 pph_dssp = subprocess . check_output ( [ global_settings [ 'dssp' ] [ 'path' ] , in_pdb ] ) dssp_residues = [ ] go = False for line in pph_dssp . splitlines ( ) : if go : res_num = int ( line [ : 5 ] . strip ( ) ) chain = line [ 11 : 13 ] . ...
def intersectingInterval ( self , start , end ) : """given an interval , get intervals in the tree that are intersected . : param start : start of the intersecting interval : param end : end of the intersecting interval : return : the list of intersected intervals"""
# find all intervals in this node that intersect start and end l = [ ] for x in self . data . starts : xStartsAfterInterval = ( x . start > end and not self . openEnded ) or ( x . start >= end and self . openEnded ) xEndsBeforeInterval = ( x . end < start and not self . openEnded ) or ( x . end <= start and sel...
def tag ( self , * tags ) : """Tags the job with one or more unique indentifiers . Tags must be hashable . Duplicate tags are discarded . : param tags : A unique list of ` ` Hashable ` ` tags . : return : The invoked job instance"""
if not all ( isinstance ( tag , collections . Hashable ) for tag in tags ) : raise TypeError ( 'Tags must be hashable' ) self . tags . update ( tags ) return self
def parse_command_line ( self , argv = None ) : """Parse the jhubctl command line arguments . This overwrites traitlets ' default ` parse _ command _ line ` method and tailors it to jhubctl ' s needs ."""
argv = sys . argv [ 1 : ] if argv is None else argv self . argv = [ py3compat . cast_unicode ( arg ) for arg in argv ] # Append Provider Class to the list of configurable items . ProviderClass = getattr ( providers , self . provider_type ) self . classes . append ( ProviderClass ) if any ( x in self . argv for x in ( '...
def _gatk4_cmd ( jvm_opts , params , data ) : """Retrieve unified command for GATK4 , using ' gatk ' . GATK3 is ' gatk3 ' ."""
gatk_cmd = utils . which ( os . path . join ( os . path . dirname ( os . path . realpath ( sys . executable ) ) , "gatk" ) ) return "%s && export PATH=%s:\"$PATH\" && gatk --java-options '%s' %s" % ( utils . clear_java_home ( ) , utils . get_java_binpath ( gatk_cmd ) , " " . join ( jvm_opts ) , " " . join ( [ str ( x )...
def remove ( self , ** kwargs ) : """Remove this container . Similar to the ` ` docker rm ` ` command . Args : v ( bool ) : Remove the volumes associated with the container link ( bool ) : Remove the specified link and not the underlying container force ( bool ) : Force the removal of a running container ...
return self . client . api . remove_container ( self . id , ** kwargs )
def sleep ( self , time ) : """Perform an asyncio sleep for the time specified in seconds . T his method should be used in place of time . sleep ( ) : param time : time in seconds : returns : No return value"""
try : task = asyncio . ensure_future ( self . core . sleep ( time ) ) self . loop . run_until_complete ( task ) except asyncio . CancelledError : pass except RuntimeError : pass
def _M2_const ( Xvar , mask_X , xvarsum , xconst , Yvar , mask_Y , yvarsum , yconst , weights = None ) : r"""Computes the unnormalized covariance matrix between X and Y , exploiting constant input columns Computes the unnormalized covariance matrix : math : ` C = X ^ \ top Y ` ( for symmetric = False ) or : mat...
C = np . zeros ( ( len ( mask_X ) , len ( mask_Y ) ) ) # Block 11 C [ np . ix_ ( mask_X , mask_Y ) ] = _M2_dense ( Xvar , Yvar , weights = weights ) # other blocks xsum_is_0 = _is_zero ( xvarsum ) ysum_is_0 = _is_zero ( yvarsum ) xconst_is_0 = _is_zero ( xconst ) yconst_is_0 = _is_zero ( yconst ) # TODO : maybe we don ...
def validate ( self , asset , amount , portfolio , algo_datetime , algo_current_data ) : """Fail if the algo has passed this Asset ' s end _ date , or before the Asset ' s start date ."""
# If the order is for 0 shares , then silently pass through . if amount == 0 : return normalized_algo_dt = pd . Timestamp ( algo_datetime ) . normalize ( ) # Fail if the algo is before this Asset ' s start _ date if asset . start_date : normalized_start = pd . Timestamp ( asset . start_date ) . normalize ( ) ...
def sync ( self ) : """Syncs the parent app changes with the current app instance . : return : Synced App object ."""
app = self . _api . post ( url = self . _URL [ 'sync' ] . format ( id = self . id ) ) . json ( ) return App ( api = self . _api , ** app )
def rdf_graph_from_yaml ( yaml_root ) : """Convert the YAML object into an RDF Graph object ."""
G = Graph ( ) for top_entry in yaml_root : assert len ( top_entry ) == 1 node = list ( top_entry . keys ( ) ) [ 0 ] build_relations ( G , node , top_entry [ node ] , None ) return G
def get_request_feature ( self , name ) : """Parses the request for a particular feature . Arguments : name : A feature name . Returns : A feature parsed from the URL if the feature is supported , or None ."""
if '[]' in name : # array - type return self . request . query_params . getlist ( name ) if name in self . features else None elif '{}' in name : # object - type ( keys are not consistent ) return self . _extract_object_params ( name ) if name in self . features else { } else : # single - type return self ....
def vlm_set_input ( self , psz_name , psz_input ) : '''Set a media ' s input MRL . This will delete all existing inputs and add the specified one . @ param psz _ name : the media to work on . @ param psz _ input : the input MRL . @ return : 0 on success , - 1 on error .'''
return libvlc_vlm_set_input ( self , str_to_bytes ( psz_name ) , str_to_bytes ( psz_input ) )
def average ( self , dt = None ) : """Modify the current instance to the average of a given instance ( default now ) and the current instance . : type dt : Date or date : rtype : Date"""
if dt is None : dt = Date . today ( ) return self . add ( days = int ( self . diff ( dt , False ) . in_days ( ) / 2 ) )
def add_coord ( self , x , y ) : """Adds a coord to the polyline and creates another circle"""
x = x * self . x_factor y = y * self . y_factor self . plotData . add_coord ( x , y ) self . circles_list . append ( gui . SvgCircle ( x , y , self . circle_radius ) ) self . append ( self . circles_list [ - 1 ] ) if len ( self . circles_list ) > self . maxlen : self . remove_child ( self . circles_list [ 0 ] ) ...