signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def is_simplicial ( G , n ) : """Determines whether a node n in G is simplicial . Parameters G : NetworkX graph The graph on which to check whether node n is simplicial . n : node A node in graph G . Returns is _ simplicial : bool True if its neighbors form a clique . Examples This example check...
return all ( u in G [ v ] for u , v in itertools . combinations ( G [ n ] , 2 ) )
def is_interactive_backend ( backend ) : """Check if backend is interactive"""
matplotlib = sys . modules [ 'matplotlib' ] from matplotlib . rcsetup import interactive_bk , non_interactive_bk # @ UnresolvedImport if backend in interactive_bk : return True elif backend in non_interactive_bk : return False else : return matplotlib . is_interactive ( )
def get_form_kwargs ( self ) : """Returns the keyword arguments for instantiating the form ."""
kwargs = { "initial" : self . get_initial ( ) } if self . request . method == "GET" : kwargs . update ( { "data" : self . request . GET } ) kwargs . update ( { "searchqueryset" : self . get_query_set ( ) } ) return kwargs
def _series_expand_combine_prod ( c1 , c2 , order ) : """Given the result of the ` ` c1 . _ series _ expand ( . . . ) ` ` and ` ` c2 . _ series _ expand ( . . . ) ` ` , construct the result of ` ` ( c1 * c2 ) . _ series _ expand ( . . . ) ` `"""
from qnet . algebra . core . scalar_algebra import Zero res = [ ] c1 = list ( c1 ) c2 = list ( c2 ) for n in range ( order + 1 ) : summands = [ ] for k in range ( n + 1 ) : if c1 [ k ] . is_zero or c2 [ n - k ] . is_zero : summands . append ( Zero ) else : summands . appe...
def del_location ( self , location , sync = True ) : """delete location from this routing area : param location : the location to be deleted from this routing area : param sync : If sync = True ( default ) synchronize with Ariane server . If sync = False , add the location object on list to be removed on next...
LOGGER . debug ( "RoutingArea.del_location" ) if not sync : self . loc_2_rm . append ( location ) else : if location . id is None : location . sync ( ) if self . id is not None and location . id is not None : params = { 'id' : self . id , 'locationID' : location . id } args = { 'http...
def set_money_currency ( self , money_currency ) : """: type money _ currency : str"""
if money_currency not in self . money_formats : raise CurrencyDoesNotExist self . money_currency = money_currency
async def flush ( self , request : Request , stacks : List [ Stack ] ) : """For all stacks to be sent , append a pause after each text layer ."""
ns = await self . expand_stacks ( request , stacks ) ns = self . split_stacks ( ns ) ns = self . clean_stacks ( ns ) await self . next ( request , [ Stack ( x ) for x in ns ] )
def setPageSize ( self , pageSize ) : """Sets the number of items that should be visible in a page . Setting the value to 0 will use all sizes : return < int >"""
if self . _pageSize == pageSize : return self . _pageSize = pageSize # update the display size ssize = nativestring ( pageSize ) if ( ssize == '0' ) : ssize = '' self . _pageSizeCombo . blockSignals ( True ) index = self . _pageSizeCombo . findText ( ssize ) self . _pageSizeCombo . setCurrentIndex ( index ) sel...
def rownumbers ( self , table = None ) : """Return a list containing the row numbers of this table . This method can be useful after a selection or a sort . It returns the row numbers of the rows in this table with respect to the given table . If no table is given , the original table is used . For example ...
if table is None : return self . _rownumbers ( Table ( ) ) return self . _rownumbers ( table )
def add_sign ( xml , key , cert , debug = False , sign_algorithm = OneLogin_Saml2_Constants . RSA_SHA1 , digest_algorithm = OneLogin_Saml2_Constants . SHA1 ) : """Adds signature key and senders certificate to an element ( Message or Assertion ) . : param xml : The element we should sign : type : string | Docu...
if xml is None or xml == '' : raise Exception ( 'Empty string supplied as input' ) elem = OneLogin_Saml2_XML . to_etree ( xml ) sign_algorithm_transform_map = { OneLogin_Saml2_Constants . DSA_SHA1 : xmlsec . Transform . DSA_SHA1 , OneLogin_Saml2_Constants . RSA_SHA1 : xmlsec . Transform . RSA_SHA1 , OneLogin_Saml2_...
def parse_timedelta ( deltastr ) : """Parse a string describing a period of time ."""
matches = TIMEDELTA_REGEX . match ( deltastr ) if not matches : return None components = { } for name , value in matches . groupdict ( ) . items ( ) : if value : components [ name ] = int ( value ) for period , hours in ( ( 'days' , 24 ) , ( 'years' , 8766 ) ) : if period in components : com...
def transport_routes ( self ) : """This method gets a dict of routes listed in Daft . : return :"""
routes = { } try : big_div = self . _ad_page_content . find ( 'div' , { "class" : "half_area_box_right" } ) uls = big_div . find ( "ul" ) if uls is None : return None for li in uls . find_all ( 'li' ) : route_li = li . text . split ( ':' ) routes [ route_li [ 0 ] ] = [ x . strip ...
def blog_recent_posts ( limit = 5 , tag = None , username = None , category = None ) : """Put a list of recently published blog posts into the template context . A tag title or slug , category title or slug or author ' s username can also be specified to filter the recent posts returned . Usage : : { % blog...
blog_posts = BlogPost . objects . published ( ) . select_related ( "user" ) title_or_slug = lambda s : Q ( title = s ) | Q ( slug = s ) if tag is not None : try : tag = Keyword . objects . get ( title_or_slug ( tag ) ) blog_posts = blog_posts . filter ( keywords__keyword = tag ) except Keyword ....
def str_syslog ( self , * args ) : '''get / set the str _ syslog , i . e . the current value of the syslog prepend string . str _ syslog ( ) : returns the current syslog string str _ syslog ( < astr > ) : sets the syslog string to < astr >'''
if len ( args ) : self . _str_syslog = args [ 0 ] else : return self . _str_syslog
def parse ( self ) : """parse data"""
super ( GeoRss , self ) . parse ( ) # support RSS and ATOM tag_name = 'item' if '<item>' in self . data else 'entry' self . parsed_data = self . parsed_data . getElementsByTagName ( tag_name )
def update_subchannel_msgs ( debug = False , force = False ) : """Grab any pending messages and place them inside the vim - ipython shell . This function will do nothing if the vim - ipython shell is not visible , unless force = True argument is passed ."""
if kc is None or ( not vim_ipython_is_open ( ) and not force ) : return False msgs = kc . iopub_channel . get_msgs ( ) b = vim . current . buffer startedin_vimipython = vim . eval ( '@%' ) == 'vim-ipython' if not startedin_vimipython : # switch to preview window vim . command ( "try" "|silent! wincmd P" "|catch...
def merge_dictionaries ( current , new , only_defaults = False , template_special_case = False ) : '''Merge two settings dictionaries , recording how many changes were needed .'''
changes = 0 for key , value in new . items ( ) : if key not in current : if hasattr ( global_settings , key ) : current [ key ] = getattr ( global_settings , key ) LOGGER . debug ( "Set %r to global default %r." , key , current [ key ] ) else : current [ key ] = c...
def all ( self , archived = False , limit = None , page = None ) : """get all adapter data ."""
path = partial ( _path , self . adapter ) if not archived : path = _path ( self . adapter ) else : path = _path ( self . adapter , 'archived' ) return self . _get ( path , limit = limit , page = page )
def hsig ( self , es ) : """return " OK - signal " for rank - one update , ` True ` ( OK ) or ` False ` ( stall rank - one update ) , based on the length of an evolution path"""
self . _update_ps ( es ) if self . ps is None : return True squared_sum = sum ( self . ps ** 2 ) / ( 1 - ( 1 - self . cs ) ** ( 2 * es . countiter ) ) # correction with self . countiter seems not necessary , # as pc also starts with zero return squared_sum / es . N - 1 < 1 + 4. / ( es . N + 1 )
def _compute_inter_event_std ( self , C , C_PGA , pga1100 , mag , vs30 ) : """Compute inter event standard deviation , equation 25 , page 82."""
tau_0 = self . _compute_std_0 ( C [ 's3' ] , C [ 's4' ] , mag ) tau_b_pga = self . _compute_std_0 ( C_PGA [ 's3' ] , C_PGA [ 's4' ] , mag ) delta_amp = self . _compute_partial_derivative_site_amp ( C , pga1100 , vs30 ) std_inter = np . sqrt ( tau_0 ** 2 + ( delta_amp ** 2 ) * ( tau_b_pga ** 2 ) + 2 * delta_amp * tau_0 ...
def _request_process_octet ( response ) : """Handle Document download . Return : ( string ) : The data from the download ( string ) : The status of the download"""
status = 'Failure' # Handle document download data = response . content if data : status = 'Success' return data , status
def get_item_lookup_session_for_bank ( self , bank_id ) : """Gets the ` ` OsidSession ` ` associated with the item lookup service for the given bank . arg : bank _ id ( osid . id . Id ) : the ` ` Id ` ` of the bank return : ( osid . assessment . ItemLookupSession ) - ` ` an _ item _ lookup _ session ` ` rai...
if not self . supports_item_lookup ( ) : raise errors . Unimplemented ( ) # Also include check to see if the catalog Id is found otherwise raise errors . NotFound # pylint : disable = no - member return sessions . ItemLookupSession ( bank_id , runtime = self . _runtime )
def _status ( self ) : """Return the current connection status as an integer value . The status should match one of the following constants : - queries . Session . INTRANS : Connection established , in transaction - queries . Session . PREPARED : Prepared for second phase of transaction - queries . Session ...
if self . _conn . status == psycopg2 . extensions . STATUS_BEGIN : return self . READY return self . _conn . status
def analyze ( problem , X , Y , num_resamples = 1000 , conf_level = 0.95 , print_to_console = False , seed = None ) : """Calculates Derivative - based Global Sensitivity Measure on model outputs . Returns a dictionary with keys ' vi ' , ' vi _ std ' , ' dgsm ' , and ' dgsm _ conf ' , where each entry is a list ...
if seed : np . random . seed ( seed ) D = problem [ 'num_vars' ] if Y . size % ( D + 1 ) == 0 : N = int ( Y . size / ( D + 1 ) ) else : raise RuntimeError ( "Incorrect number of samples in model output file." ) if not 0 < conf_level < 1 : raise RuntimeError ( "Confidence level must be between 0-1." ) ba...
def visible_to_user ( self , element , * ignorable ) : """Determines whether an element is visible to the user . A list of ignorable elements can be passed to this function . These would typically be things like invisible layers sitting atop other elements . This function ignores these elements by setting t...
if not element . is_displayed ( ) : return False return self . driver . execute_script ( """ var el = arguments[0]; var ignorable = arguments[1]; var old_displays = ignorable.map(function (x) { var old = x.style.display; x.style.display = "none"; return o...
def relaxation ( P , p0 , obs , times = [ 1 ] , k = None , ncv = None ) : r"""Relaxation experiment . The relaxation experiment describes the time - evolution of an expectation value starting in a non - equilibrium situation . Parameters P : ( M , M ) ndarray Transition matrix p0 : ( M , ) ndarray ( o...
M = P . shape [ 0 ] T = np . asarray ( times ) . max ( ) if T < M : return relaxation_matvec ( P , p0 , obs , times = times ) else : return relaxation_decomp ( P , p0 , obs , times = times , k = k , ncv = ncv )
def post_pipeline ( self , pipeline ) : """Send Pipeline JSON to Spinnaker . Args : pipeline ( dict , str ) : New Pipeline to create ."""
if isinstance ( pipeline , str ) : pipeline_str = pipeline else : pipeline_str = json . dumps ( pipeline ) pipeline_json = json . loads ( pipeline_str ) # Note pipeline name is manual name = '{0} (onetime-{1})' . format ( pipeline_json [ 'name' ] , self . environments [ 0 ] ) pipeline_json [ 'name' ] = name # I...
def _begin ( self , retry_id = None ) : """Begin the transaction . Args : retry _ id ( Optional [ bytes ] ) : Transaction ID of a transaction to be retried . Raises : ValueError : If the current transaction has already begun ."""
if self . in_progress : msg = _CANT_BEGIN . format ( self . _id ) raise ValueError ( msg ) transaction_response = self . _client . _firestore_api . begin_transaction ( self . _client . _database_string , options_ = self . _options_protobuf ( retry_id ) , metadata = self . _client . _rpc_metadata , ) self . _id ...
def is_tabular_aligned ( c ) : """Return True if all Mentions in the given candidate are from the same Row or Col . : param c : The candidate whose Mentions are being compared : rtype : boolean"""
return same_table ( c ) and ( is_col_aligned ( _to_span ( c [ i ] ) . sentence , _to_span ( c [ 0 ] ) . sentence ) or is_row_aligned ( _to_span ( c [ i ] ) . sentence , _to_span ( c [ 0 ] ) . sentence ) for i in range ( len ( c ) ) )
def add_relation ( self , relation ) : """Parameters relation : etree . Element etree representation of a < relation > element A < relation > always has a type attribute and inherits its ID from its parent element . In the case of a non - expletive relation , it also has a target attribute . Example <...
if self . ignore_relations is False : parent_node_id = self . get_parent_id ( relation ) reltype = relation . attrib [ 'type' ] # add relation type information to parent node self . node [ parent_node_id ] . update ( { 'relation' : reltype } ) self . add_layer ( parent_node_id , self . ns + ':' + re...
def dump_guest_stack ( self , cpu_id ) : """Produce a simple stack dump using the current guest state . This feature is not implemented in the 4.0.0 release but may show up in a dot release . in cpu _ id of type int The identifier of the Virtual CPU . return stack of type str String containing the forma...
if not isinstance ( cpu_id , baseinteger ) : raise TypeError ( "cpu_id can only be an instance of type baseinteger" ) stack = self . _call ( "dumpGuestStack" , in_p = [ cpu_id ] ) return stack
async def find ( self , * tracking_numbers : str ) -> list : """Get tracking info for one or more tracking numbers ."""
data = { 'data' : [ { 'num' : num } for num in tracking_numbers ] } tracking_resp = await self . _request ( 'post' , API_URL_TRACK , json = data ) print ( tracking_resp ) if not tracking_resp . get ( 'dat' ) : raise InvalidTrackingNumberError ( 'Invalid data' ) packages = [ ] for info in tracking_resp [ 'dat' ] : ...
def parse_env_file ( env_file ) : """Reads a line - separated environment file . The format of each line should be " key = value " ."""
environment = { } with open ( env_file , 'r' ) as f : for line in f : if line [ 0 ] == '#' : continue line = line . strip ( ) if not line : continue parse_line = line . split ( '=' , 1 ) if len ( parse_line ) == 2 : k , v = parse_line ...
def main ( ) : '''Calculate the depth of a liquid in inches using a HCSR04 sensor and a Raspberry Pi'''
trig_pin = 17 echo_pin = 27 hole_depth = 31.5 # inches # Default values # unit = ' metric ' # temperature = 20 # round _ to = 1 # Create a distance reading with the hcsr04 sensor module # and overide the default values for temp , unit and rounding ) value = sensor . Measurement ( trig_pin , echo_pin , temperature = 68 ...
def clean ( cls , cnpj ) : u"""Retorna apenas os dígitos do CNPJ . > > > CNPJ . clean ( ' 58.414.462/0001-35 ' ) '58414462000135'"""
if isinstance ( cnpj , six . string_types ) : cnpj = int ( re . sub ( '[^0-9]' , '' , cnpj ) ) return '{0:014d}' . format ( cnpj )
def main ( ) : """Example application that periodically faults a virtual zone and then restores it . This is an advanced feature that allows you to emulate a virtual zone . When the AlarmDecoder is configured to emulate a zone expander we can fault and restore those zones programmatically at will . These ev...
try : # Retrieve the first USB device device = AlarmDecoder ( SerialDevice ( interface = SERIAL_DEVICE ) ) # Set up an event handlers and open the device device . on_zone_fault += handle_zone_fault device . on_zone_restore += handle_zone_restore with device . open ( baudrate = BAUDRATE ) : l...
def sendResult ( self , future ) : """Send back results to broker for distribution to parent task ."""
# Greenlets cannot be pickled future . greenlet = None assert future . _ended ( ) , "The results are not valid" self . socket . sendResult ( future )
def community_post_show ( self , id , ** kwargs ) : "https : / / developer . zendesk . com / rest _ api / docs / help _ center / posts # show - post"
api_path = "/api/v2/community/posts/{id}.json" api_path = api_path . format ( id = id ) return self . call ( api_path , ** kwargs )
def disc ( ghi , solar_zenith , datetime_or_doy , pressure = 101325 , min_cos_zenith = 0.065 , max_zenith = 87 , max_airmass = 12 ) : """Estimate Direct Normal Irradiance from Global Horizontal Irradiance using the DISC model . The DISC algorithm converts global horizontal irradiance to direct normal irradian...
# this is the I0 calculation from the reference # SSC uses solar constant = 1367.0 ( checked 2018 08 15) I0 = get_extra_radiation ( datetime_or_doy , 1370. , 'spencer' ) kt = clearness_index ( ghi , solar_zenith , I0 , min_cos_zenith = min_cos_zenith , max_clearness_index = 1 ) am = atmosphere . get_relative_airmass ( ...
def can_create_activities ( self ) : """Tests if this user can create Activities . A return of true does not guarantee successful authorization . A return of false indicates that it is known creating an Activity will result in a PermissionDenied . This is intended as a hint to an application that may opt no...
url_path = construct_url ( 'authorization' , bank_id = self . _catalog_idstr ) return self . _get_request ( url_path ) [ 'activityHints' ] [ 'canCreate' ]
def serve ( application , host = '127.0.0.1' , port = 8080 ) : """Eventlet - based WSGI - HTTP server . For a more fully - featured Eventlet - capable interface , see also [ Spawning ] ( http : / / pypi . python . org / pypi / Spawning / ) ."""
# Instantiate the server with a bound port and with our application . server ( listen ( host , int ( port ) ) , application )
def rm_command ( ignore_missing , star_silent , recursive , enable_globs , endpoint_plus_path , label , submission_id , dry_run , deadline , skip_activation_check , notify , meow , heartbeat , polling_interval , timeout , timeout_exit_code , ) : """Executor for ` globus rm `"""
endpoint_id , path = endpoint_plus_path client = get_client ( ) # attempt to activate unless - - skip - activation - check is given if not skip_activation_check : autoactivate ( client , endpoint_id , if_expires_in = 60 ) delete_data = DeleteData ( client , endpoint_id , label = label , recursive = recursive , igno...
def xyzlim ( vmin , vmax = None ) : """Set limits or all axis the same , if vmax not given , use [ - vmin , vmin ] ."""
if vmax is None : vmin , vmax = - vmin , vmin xlim ( vmin , vmax ) ylim ( vmin , vmax ) zlim ( vmin , vmax )
def draw ( self , category , num_top_words_to_annotate = 4 , words_to_annotate = [ ] , scores = None , transform = percentile_alphabetical ) : '''Outdated . MPLD3 drawing . Parameters category num _ top _ words _ to _ annotate words _ to _ annotate scores transform Returns pd . DataFrame , html of f...
try : import matplotlib . pyplot as plt except : raise Exception ( "matplotlib and mpld3 need to be installed to use this function." ) try : from mpld3 import plugins , fig_to_html except : raise Exception ( "mpld3 need to be installed to use this function." ) all_categories , other_categories = self . ...
def render_page ( page , page_args ) : """Renders the template at page . template"""
print ( page_args ) template_name = page . template if page . template else page . name template = "signage/pages/{}.html" . format ( template_name ) if page . function : context_method = getattr ( pages , page . function ) else : context_method = getattr ( pages , page . name ) sign , request = page_args conte...
def relfreq ( inlist , numbins = 10 , defaultreallimits = None ) : """Returns a relative frequency histogram , using the histogram function . Usage : lrelfreq ( inlist , numbins = 10 , defaultreallimits = None ) Returns : list of cumfreq bin values , lowerreallimit , binsize , extrapoints"""
h , l , b , e = histogram ( inlist , numbins , defaultreallimits ) for i in range ( len ( h ) ) : h [ i ] = h [ i ] / float ( len ( inlist ) ) return h , l , b , e
def plot3d ( self , * args , ** kwargs ) : """NAME : plot3d PURPOSE : plot 3D aspects of an Orbit INPUT : ro = ( Object - wide default ) physical scale for distances to use to convert vo = ( Object - wide default ) physical scale for velocities to use to convert use _ physical = use to override Object...
if ( kwargs . get ( 'use_physical' , False ) and kwargs . get ( 'ro' , self . _roSet ) ) or ( not 'use_physical' in kwargs and kwargs . get ( 'ro' , self . _roSet ) ) : labeldict = { 't' : r'$t\ (\mathrm{Gyr})$' , 'R' : r'$R\ (\mathrm{kpc})$' , 'vR' : r'$v_R\ (\mathrm{km\,s}^{-1})$' , 'vT' : r'$v_T\ (\mathrm{km\,s}...
def invalid_content_type ( self , request = None , response = None ) : """Returns the content type that should be used by default on validation errors"""
if callable ( self . invalid_outputs . content_type ) : return self . invalid_outputs . content_type ( request = request , response = response ) else : return self . invalid_outputs . content_type
def save ( self ) : """Save this node ( and all its attributes ) to config"""
cfg_file = "/etc/nago/nago.ini" config = ConfigParser . ConfigParser ( ) config . read ( cfg_file ) result = { } token = self . data . pop ( "token" , self . token ) if token != self . _original_token : config . remove_section ( self . _original_token ) config . add_section ( token ) if token not in config . se...
def use_comparative_log_entry_view ( self ) : """Pass through to provider LogEntryLookupSession . use _ comparative _ log _ entry _ view"""
self . _object_views [ 'log_entry' ] = COMPARATIVE # self . _ get _ provider _ session ( ' log _ entry _ lookup _ session ' ) # To make sure the session is tracked for session in self . _get_provider_sessions ( ) : try : session . use_comparative_log_entry_view ( ) except AttributeError : pass
def is_running ( process_id : int ) -> bool : """Uses the Unix ` ` ps ` ` program to see if a process is running ."""
pstr = str ( process_id ) encoding = sys . getdefaultencoding ( ) s = subprocess . Popen ( [ "ps" , "-p" , pstr ] , stdout = subprocess . PIPE ) for line in s . stdout : strline = line . decode ( encoding ) if pstr in strline : return True return False
def parse_byte_range ( byte_range , min_byte = 0 , max_byte = sys . maxint ) : """Parse and validate a byte range . A byte range is a tuple of ( begin , end ) indices . ` begin ' should be smaller than ` end ' , and both should fall within the ` min _ byte ' and ` max _ byte ' . In case of a violation , a ` V...
if not byte_range : return min_byte , max_byte begin = byte_range [ 0 ] or min_byte end = byte_range [ 1 ] or max_byte if end < begin : raise ValueError ( "End before begin" ) if begin < min_byte : raise ValueError ( "Begin smaller than min" ) if end > max_byte : raise ValueError ( "End larger than max"...
def find_zone_name ( data , zone_id ) : """Find on the HTML document the zone name . # expected result < span class = " more _ info " title = " Zone can be renamed on Setup tab " > 1 - zone1 < / span > , : param data : BeautifulSoup object : param zone : zone id : return : zone name : rtype : string :...
if not isinstance ( data , BeautifulSoup ) : raise TypeError ( "Function requires BeautilSoup HTML element." ) table = data . find ( 'table' , { 'class' : 'zone_table' } ) table_body = table . find ( 'tbody' ) rows = table_body . find_all ( 'span' , { 'class' : 'more_info' } ) for row in rows : if row . get_tex...
def plot_ax ( self , ax = None , fontsize = 12 , ** kwargs ) : """Plot the equation of state on axis ` ax ` Args : ax : matplotlib : class : ` Axes ` or None if a new figure should be created . fontsize : Legend fontsize . color ( str ) : plot color . label ( str ) : Plot label text ( str ) : Legend tex...
ax , fig , plt = get_ax_fig_plt ( ax = ax ) color = kwargs . get ( "color" , "r" ) label = kwargs . get ( "label" , "{} fit" . format ( self . __class__ . __name__ ) ) lines = [ "Equation of State: %s" % self . __class__ . __name__ , "Minimum energy = %1.2f eV" % self . e0 , "Minimum or reference volume = %1.2f Ang^3" ...
def _connect ( self , sock , addr , timeout ) : """Start watching the socket for it to be writtable ."""
if self . connection : raise SocketClientConnectedError ( ) if self . connector : raise SocketClientConnectingError ( ) self . connect_deferred = Deferred ( self . loop ) self . sock = sock self . addr = addr self . connector = Connector ( self . loop , sock , addr , timeout ) self . connector . deferred . add_...
def _hm_form_message_crc ( self , thermostat_id , protocol , source , function , start , payload ) : """Forms a message payload , including CRC"""
data = self . _hm_form_message ( thermostat_id , protocol , source , function , start , payload ) crc = CRC16 ( ) data = data + crc . run ( data ) return data
def create_favorite ( self , favorite , project ) : """CreateFavorite . [ Preview API ] Creates a ref favorite : param : class : ` < GitRefFavorite > < azure . devops . v5_0 . git . models . GitRefFavorite > ` favorite : The ref favorite to create . : param str project : Project ID or project name : rtype :...
route_values = { } if project is not None : route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' ) content = self . _serialize . body ( favorite , 'GitRefFavorite' ) response = self . _send ( http_method = 'POST' , location_id = '876f70af-5792-485a-a1c7-d0a7b2f42bbb' , version = '5.0-p...
def dssps ( self ) : """Dict of filepaths for all dssp files associated with code . Notes Runs dssp and stores writes output to files if not already present . Also downloads mmol files if not already present . Calls isambard . external _ programs . dssp and so needs dssp to be installed . Returns dssps ...
dssps_dict = { } dssp_dir = os . path . join ( self . parent_dir , 'dssp' ) if not os . path . exists ( dssp_dir ) : os . makedirs ( dssp_dir ) for i , mmol_file in self . mmols . items ( ) : dssp_file_name = '{0}.dssp' . format ( os . path . basename ( mmol_file ) ) dssp_file = os . path . join ( dssp_dir ...
def get_fqn ( base_fqn , delimiter , name = None ) : """Return the fully qualified name of an object within this context . If the name passed already appears to be a fully qualified name , it will be returned with no further processing ."""
if name and name . startswith ( "%s%s" % ( base_fqn , delimiter ) ) : return name return delimiter . join ( [ _f for _f in [ base_fqn , name ] if _f ] )
def start ( self , trunk_type ) : """Type of internal network trunk . in trunk _ type of type str Type of internal network trunk ."""
if not isinstance ( trunk_type , basestring ) : raise TypeError ( "trunk_type can only be an instance of type basestring" ) self . _call ( "start" , in_p = [ trunk_type ] )
def decrypt_element ( encrypted_data , key , debug = False , inplace = False ) : """Decrypts an encrypted element . : param encrypted _ data : The encrypted data . : type : lxml . etree . Element | DOMElement | basestring : param key : The key . : type : string : param debug : Activate the xmlsec debug ...
if isinstance ( encrypted_data , Element ) : encrypted_data = fromstring ( str ( encrypted_data . toxml ( ) ) , forbid_dtd = True ) elif isinstance ( encrypted_data , basestring ) : encrypted_data = fromstring ( str ( encrypted_data ) , forbid_dtd = True ) elif not inplace and isinstance ( encrypted_data , etre...
def reset ( self ) : """Discover plug - ins and run collection"""
self . context = pyblish . api . Context ( ) self . plugins = pyblish . api . discover ( ) self . was_discovered . emit ( ) self . pair_generator = None self . current_pair = ( None , None ) self . current_error = None self . processing = { "nextOrder" : None , "ordersWithError" : set ( ) } self . _load ( ) self . _run...
def _set_from_ini ( self , namespace , ini_file ) : """Copy values from loaded INI file to namespace ."""
# Isolate global values global_vars = dict ( ( key , val ) for key , val in namespace . items ( ) if isinstance ( val , basestring ) ) # Copy all sections for section in ini_file . sections ( ) : # Get values set so far if section == "GLOBAL" : raw_vars = global_vars else : raw_vars = namespace ...
def _get_match ( self , key ) : """Gets a MatchObject for the given key . Args : key ( str ) : Key of the property to look - up . Return : MatchObject : The discovered match ."""
return self . _get_string_match ( key = key ) or self . _get_non_string_match ( key = key )
def is_min_heap ( lst , idx = 0 ) : """Function to verify if a given array represents a min heap or not . > > > is _ min _ heap ( [ 1 , 2 , 3 , 4 , 5 , 6 ] ) True > > > is _ min _ heap ( [ 2 , 3 , 4 , 5 , 10 , 15 ] ) True > > > is _ min _ heap ( [ 2 , 10 , 4 , 5 , 3 , 15 ] ) False Args : lst : List ...
# If we are outside the list return True if idx * 2 + 2 > len ( lst ) : return True # Check if parent is smaller than its children and recurse is_left_valid = lst [ idx ] <= lst [ idx * 2 + 1 ] and is_min_heap ( lst , idx * 2 + 1 ) is_right_valid = idx * 2 + 2 == len ( lst ) or ( lst [ idx ] <= lst [ idx * 2 + 2 ] ...
def max_play ( w , i , grid ) : "Play like Spock , except breaking ties by drunk _ value ."
return min ( successors ( grid ) , key = lambda succ : ( evaluate ( succ ) , drunk_value ( succ ) ) )
def cable_from_html ( html , reference_id = None ) : """Returns a cable from the provided HTML page . ` html ` The HTML page of the cable ` reference _ id ` The reference identifier of the cable . If the reference _ id is ` ` None ` ` this function tries to detect it ."""
if not html : raise ValueError ( 'The HTML page of the cable must be provided, got: "%r"' % html ) if not reference_id : reference_id = reader . reference_id_from_html ( html ) cable = Cable ( reference_id ) reader . parse_meta ( html , cable ) cable . header = reader . get_header_as_text ( html , reference_id ...
def submit_jobs ( self , link , job_dict = None , job_archive = None , stream = sys . stdout ) : """Submit all the jobs in job _ dict"""
if link is None : return JobStatus . no_job if job_dict is None : job_keys = link . jobs . keys ( ) else : job_keys = sorted ( job_dict . keys ( ) ) # copy & reverse the keys b / c we will be popping item off the back of # the list unsubmitted_jobs = job_keys unsubmitted_jobs . reverse ( ) failed = False if...
def _serialize_fields ( point ) : """Field values can be floats , integers , strings , or Booleans ."""
output = [ ] for k , v in point [ 'fields' ] . items ( ) : k = escape ( k , key_escape ) if isinstance ( v , bool ) : output . append ( f'{k}={v}' ) elif isinstance ( v , int ) : output . append ( f'{k}={v}i' ) elif isinstance ( v , str ) : output . append ( f'{k}="{v.translate(s...
def equalize_list_lengths ( a , b ) : """Modifies the length of list a to match b . Returns a . a can also not be a list ( will convert it to one ) . a will not be modified ."""
if not _s . fun . is_iterable ( a ) : a = [ a ] a = list ( a ) while len ( a ) > len ( b ) : a . pop ( - 1 ) while len ( a ) < len ( b ) : a . append ( a [ - 1 ] ) return a
def set_matrix ( self , matrix ) : """Apply the 3x3 transformation matrix to absolute device coordinates . This matrix has no effect on relative events . Given a 6 - element array [ a , b , c , d , e , f ] , the matrix is applied as [ a b c ] [ x ] [ d e f ] * [ y ] [ 0 0 1 ] [ 1 ] The translation compo...
matrix = ( c_float * 6 ) ( * matrix ) return self . _libinput . libinput_device_config_calibration_set_matrix ( self . _handle , matrix )
def oauth_get_user ( client_id , account_info = None , access_token = None ) : """Retrieve user object for the given request . Uses either the access token or extracted account information to retrieve the user object . : param client _ id : The client id . : param account _ info : The dictionary with the ac...
if access_token : token = RemoteToken . get_by_token ( client_id , access_token ) if token : return token . remote_account . user if account_info : external_id = _get_external_id ( account_info ) if external_id : user_identity = UserIdentity . query . filter_by ( id = external_id [ 'id' ...
def get_attributes ( self ) : """Returns the unordered list of attributes : return : list of strings"""
attr = [ 'chr' , 'start' , 'stop' ] if self . strandPos is not None : attr . append ( 'strand' ) if self . otherPos : for i , o in enumerate ( self . otherPos ) : attr . append ( o [ 1 ] ) return attr
def submit_link ( self , sr , title , url , follow = True ) : """Login required . POSTs a link submission . Returns : class : ` things . Link ` object if ` ` follow = True ` ` ( default ) , or the string permalink of the new submission otherwise . Argument ` ` follow ` ` exists because reddit only returns the per...
return self . _submit ( sr , title , 'link' , url = url , follow = follow )
def update_customer_by_id ( cls , customer_id , customer , ** kwargs ) : """Update Customer Update attributes of Customer This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async = True > > > thread = api . update _ customer _ by _ id ( customer _ id...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async' ) : return cls . _update_customer_by_id_with_http_info ( customer_id , customer , ** kwargs ) else : ( data ) = cls . _update_customer_by_id_with_http_info ( customer_id , customer , ** kwargs ) return data
def mask ( self ) : '''The array of indices to be masked . This is the union of the sets of outliers , bad ( flagged ) cadences , transit cadences , and : py : obj : ` NaN ` cadences .'''
return np . array ( list ( set ( np . concatenate ( [ self . outmask , self . badmask , self . transitmask , self . nanmask ] ) ) ) , dtype = int )
def uniform_binned ( self , name = None ) : """Return a new histogram with constant width bins along all axes by using the bin indices as the bin edges of the new histogram ."""
if self . GetDimension ( ) == 1 : new_hist = Hist ( self . GetNbinsX ( ) , 0 , self . GetNbinsX ( ) , name = name , type = self . TYPE ) elif self . GetDimension ( ) == 2 : new_hist = Hist2D ( self . GetNbinsX ( ) , 0 , self . GetNbinsX ( ) , self . GetNbinsY ( ) , 0 , self . GetNbinsY ( ) , name = name , type ...
def suffix ( filename , suffix ) : '''returns a filenames with ` ` suffix ` ` inserted before the dataset suffix'''
return os . path . split ( re . sub ( _afni_suffix_regex , "%s\g<1>" % suffix , str ( filename ) ) ) [ 1 ]
def findFileRtiIndex ( self , childIndex ) : """Traverses the tree upwards from the item at childIndex until the tree item is found that represents the file the item at childIndex"""
parentIndex = childIndex . parent ( ) if not parentIndex . isValid ( ) : return childIndex else : parentItem = self . getItem ( parentIndex ) childItem = self . getItem ( childIndex ) if parentItem . fileName == childItem . fileName : return self . findFileRtiIndex ( parentIndex ) else : ...
def SUSSelection ( self , mating_pool_size ) : '''Make Selection of the mating pool with the stochastic universal sampling algorithm'''
A = numpy . zeros ( self . length ) mating_pool = numpy . zeros ( mating_pool_size ) r = numpy . random . random ( ) / float ( mating_pool_size ) [ F , S , P ] = self . rankingEval ( ) P_Sorted = numpy . zeros ( self . length ) for i in range ( self . length ) : P_Sorted [ i ] = P [ S [ i ] ] for i in range ( self ...
def _json_body_ ( cls ) : """Return the JSON body of given datapoints . : return : JSON body of these datapoints ."""
json = [ ] for series_name , data in six . iteritems ( cls . _datapoints ) : for point in data : json_point = { "measurement" : series_name , "fields" : { } , "tags" : { } , "time" : getattr ( point , "time" ) } for field in cls . _fields : value = getattr ( point , field ) i...
def control_volumes ( self ) : """Compute the control volumes of all nodes in the mesh ."""
if self . _control_volumes is None : # 1/3 . * ( 0.5 * edge _ length ) * covolume # = 1/6 * edge _ length * * 2 * ce _ ratio _ edge _ ratio v = self . ei_dot_ei * self . ce_ratios / 6.0 # Explicitly sum up contributions per cell first . Makes # numpy . add . at faster . # For every node k ( range ( 4 ) ...
def plot_aperture ( self , show = True ) : '''Plot sample postage stamps for the target with the aperture outline marked , as well as a high - res target image ( if available ) . : param bool show : Show the plot or return the ` ( fig , ax ) ` instance ? Default : py : obj : ` True `'''
# Set up the axes fig , ax = pl . subplots ( 2 , 2 , figsize = ( 6 , 8 ) ) fig . subplots_adjust ( top = 0.975 , bottom = 0.025 , left = 0.05 , right = 0.95 , hspace = 0.05 , wspace = 0.05 ) ax = ax . flatten ( ) fig . canvas . set_window_title ( '%s %d' % ( self . _mission . IDSTRING , self . ID ) ) super ( Everest , ...
def compar ( self , x , y ) : '''simple comparator method'''
indX = 0 indY = 0 a = int ( x [ 0 ] . split ( '-' ) [ 1 ] ) b = int ( y [ 0 ] . split ( '-' ) [ 1 ] ) if a > b : return 1 if a == b : return 0 if a < b : return - 1
def get_series ( self , key ) : """Get a series object from TempoDB given its key . : param string key : a string name for the series : rtype : : class : ` tempodb . response . Response ` with a : class : ` tempodb . protocol . objects . Series ` data payload"""
url = make_series_url ( key ) resp = self . session . get ( url ) return resp
def commit ( self , f ) : '''Move the temporary file to the target location .'''
if self . _overwrite : replace_atomic ( f . name , self . _path ) else : move_atomic ( f . name , self . _path )
def volume_correlation ( results , references ) : r"""Volume correlation . Computes the linear correlation in binary object volume between the contents of the successive binary images supplied . Measured through the Pearson product - moment correlation coefficient . Parameters results : sequence of array ...
results = numpy . atleast_2d ( numpy . array ( results ) . astype ( numpy . bool ) ) references = numpy . atleast_2d ( numpy . array ( references ) . astype ( numpy . bool ) ) results_volumes = [ numpy . count_nonzero ( r ) for r in results ] references_volumes = [ numpy . count_nonzero ( r ) for r in references ] retu...
def queries ( self , last_updated_ms ) : """Get the updated queries ."""
stats_logger . incr ( 'queries' ) if not g . user . get_id ( ) : return json_error_response ( 'Please login to access the queries.' , status = 403 ) # Unix time , milliseconds . last_updated_ms_int = int ( float ( last_updated_ms ) ) if last_updated_ms else 0 # UTC date time , same that is stored in the DB . last_u...
def scale_up ( self , n , pods = None , ** kwargs ) : """Make sure we have n dask - workers available for this cluster Examples > > > cluster . scale _ up ( 20 ) # ask for twenty workers"""
maximum = dask . config . get ( 'kubernetes.count.max' ) if maximum is not None and maximum < n : logger . info ( "Tried to scale beyond maximum number of workers %d > %d" , n , maximum ) n = maximum pods = pods or self . _cleanup_terminated_pods ( self . pods ( ) ) to_create = n - len ( pods ) new_pods = [ ] f...
def forward ( A , pobs , pi , T = None , alpha_out = None , dtype = np . float32 ) : """Compute P ( obs | A , B , pi ) and all forward coefficients . Parameters A : ndarray ( ( N , N ) , dtype = float ) transition matrix of the hidden states pobs : ndarray ( ( T , N ) , dtype = float ) pobs [ t , i ] is t...
# set T if T is None : T = pobs . shape [ 0 ] # if not set , use the length of pobs as trajectory length elif T > pobs . shape [ 0 ] : raise ValueError ( 'T must be at most the length of pobs.' ) # set N N = A . shape [ 0 ] # initialize output if necessary if alpha_out is None : alpha_out = np . zeros (...
def path ( self , value ) : """Setter for * * self . _ _ path * * attribute . : param value : Attribute value . : type value : unicode"""
if value is not None : assert type ( value ) is unicode , "'{0}' attribute: '{1}' type is not 'unicode'!" . format ( "path" , value ) self . __path = value
def convex_hull ( points ) : """Computes the convex hull of a set of 2D points . Implements ` Andrew ' s monotone chain algorithm < http : / / en . wikibooks . org / wiki / Algorithm _ Implementation / Geometry / Convex _ hull / Monotone _ chain > ` _ . The algorithm has O ( n log n ) complexity . Credit : ` ...
# Sort the points lexicographically ( tuples are compared lexicographically ) . # Remove duplicates to detect the case we have just one unique point . points = sorted ( set ( points ) ) # Boring case : no points or a single point , possibly repeated multiple times . if len ( points ) <= 1 : return points # 2D cross...
def _get_flag_value_from_var ( flag , var , delim = ' ' ) : """Extract flags from an environment variable . Parameters flag : str The flag to extract , for example ' - I ' or ' - L ' var : str The environment variable to extract the flag from , e . g . CFLAGS or LDFLAGS . delim : str , optional The de...
if sys . platform . startswith ( 'win' ) : return None # Simple input validation if not var or not flag : return None flag_length = len ( flag ) if not flag_length : return None # Look for var in os . eviron then in get _ config _ var if var in os . environ : flags = os . environ [ var ] else : try ...
def snv_get_blockstack_ops_at ( current_block_id , current_consensus_hash , block_id , consensus_hash , proxy = None ) : """Simple name verification ( snv ) lookup : Use a known - good " current " consensus hash and block ID to look up a set of name operations from the past , given the previous point in time ...
import blockstack log . debug ( 'verify {}-{} to {}-{}' . format ( current_block_id , current_consensus_hash , block_id , consensus_hash ) ) proxy = get_default_proxy ( ) if proxy is None else proxy # work backwards in time , using a Merkle skip - list constructed # by blockstackd over the set of consensus hashes . nex...
def get_providers ( self ) : """Get OAuth providers Returns a dictionary of oauth applications ready to be registered with flask oauth extension at application bootstrap ."""
if self . providers : return self . providers providers = dict ( ) for provider in self . config : configurator = provider . lower ( ) + '_config' if not hasattr ( self , configurator ) : err = 'Provider [{}] not recognized' . format ( provider ) raise ValueError ( err ) provider_config ...
def umask ( self , new_mask ) : """Change the current umask . Args : new _ mask : ( int ) The new umask value . Returns : The old umask . Raises : TypeError : if new _ mask is of an invalid type ."""
if not is_int_type ( new_mask ) : raise TypeError ( 'an integer is required' ) old_umask = self . filesystem . umask self . filesystem . umask = new_mask return old_umask
def get_parent_data ( tree , node , current ) : """Recurse up the tree getting parent data : param tree : The tree : param node : The current node : param current : The current list : return : The hierarchical dictionary"""
if not current : current = [ ] parent = tree . parent ( node . identifier ) if parent . is_root ( ) : return current current . insert ( 0 , ( parent . tag , parent . data ) ) return PlateManager . get_parent_data ( tree , parent , current )
def unique_char_count ( input_str : str ) -> int : """Counts the number of unique characters in a string without considering case sensitivity . Args : input _ str ( str ) : Input string from which unique characters are to be counted . Returns : int : Number of unique characters in the input string . Examp...
return len ( set ( input_str . upper ( ) ) )
def unmount ( self , remove_rw = False , allow_lazy = False ) : """Removes all ties of this disk to the filesystem , so the image can be unmounted successfully . : raises SubsystemError : when one of the underlying commands fails . Some are swallowed . : raises CleanupError : when actual cleanup fails . Some ar...
for m in list ( sorted ( self . volumes , key = lambda v : v . mountpoint or "" , reverse = True ) ) : try : m . unmount ( allow_lazy = allow_lazy ) except ImageMounterError : logger . warning ( "Error unmounting volume {0}" . format ( m . mountpoint ) ) if self . _paths . get ( 'nbd' ) : _u...
def get_tetrahedra_relative_grid_address ( microzone_lattice ) : """Returns relative ( differences of ) grid addresses from the central Parameter microzone _ lattice : ndarray or list of list column vectors of parallel piped microzone lattice , i . e . , microzone _ lattice = np . linalg . inv ( cell . get ...
relative_grid_address = np . zeros ( ( 24 , 4 , 3 ) , dtype = 'intc' ) phonoc . tetrahedra_relative_grid_address ( relative_grid_address , np . array ( microzone_lattice , dtype = 'double' , order = 'C' ) ) return relative_grid_address