signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def adjustSize ( self ) : """Adjusts the size of this node to support the length of its contents ."""
cell = self . scene ( ) . cellWidth ( ) * 2 minheight = cell minwidth = 2 * cell # fit to the grid size metrics = QFontMetrics ( QApplication . font ( ) ) width = metrics . width ( self . displayName ( ) ) + 20 width = ( ( width / cell ) * cell ) + ( cell % width ) height = self . rect ( ) . height ( ) # adjust for the...
def get_all_children ( self , include_self = False ) : """Return all subsidiaries of this company ."""
ownership = Ownership . objects . filter ( parent = self ) subsidiaries = Company . objects . filter ( child__in = ownership ) for sub in subsidiaries : subsidiaries = subsidiaries | sub . get_all_children ( ) if include_self is True : self_company = Company . objects . filter ( id = self . id ) subsidiarie...
def hide_busy ( self ) : """Unlock buttons A helper function to indicate processing is done ."""
self . progress_bar . hide ( ) self . parent . pbnNext . setEnabled ( True ) self . parent . pbnBack . setEnabled ( True ) self . parent . pbnCancel . setEnabled ( True ) self . parent . repaint ( ) disable_busy_cursor ( )
def spectral_embedding ( geom , n_components = 8 , eigen_solver = 'auto' , random_state = None , drop_first = True , diffusion_maps = False , diffusion_time = 0 , solver_kwds = None ) : """Project the sample on the first eigen vectors of the graph Laplacian . The adjacency matrix is used to compute a normalized g...
random_state = check_random_state ( random_state ) if geom . affinity_matrix is None : geom . compute_affinity_matrix ( ) if not _graph_is_connected ( geom . affinity_matrix ) : warnings . warn ( "Graph is not fully connected: " "spectral embedding may not work as expected." ) if geom . laplacian_matrix is None...
def get_hypertree_from_predecessors ( H , Pv , source_node , node_weights = None , attr_name = "weight" ) : """Gives the hypertree ( i . e . , the subhypergraph formed from the union of the set of paths from an execution of , e . g . , the SBT algorithm ) defined by Pv beginning at a source node . Returns a dic...
if not isinstance ( H , DirectedHypergraph ) : raise TypeError ( "Algorithm only applicable to directed hypergraphs" ) sub_H = DirectedHypergraph ( ) # If node weights are not provided , simply collect all the nodes that are # will be in the hypertree if node_weights is None : nodes = [ node for node in Pv . ke...
def findbeam_radialpeak ( data , orig_initial , mask , rmin , rmax , maxiter = 100 , drive_by = 'amplitude' , extent = 10 , callback = None ) : """Find the beam by minimizing the width of a peak in the radial average . Inputs : data : scattering matrix orig _ initial : first guess for the origin mask : mask...
orig_initial = np . array ( orig_initial ) mask = 1 - mask . astype ( np . uint8 ) data = data . astype ( np . double ) pix = np . arange ( rmin * 1.0 , rmax * 1.0 , 1 ) if drive_by . lower ( ) == 'hwhm' : def targetfunc ( orig , data , mask , orig_orig , callback ) : I = radintpix ( data , None , orig [ 0 ...
def convert ( self , request , response , data ) : """Performs the desired Conversion . : param request : The webob Request object describing the request . : param response : The webob Response object describing the response . : param data : The data dictionary returned by the prepare ( ) method . : r...
# Notes are in bark . notes dictionary return self . escape ( request . environ . get ( 'bark.notes' , { } ) . get ( self . modifier . param , '-' ) )
def get_top_stories ( self ) : """Get the item numbers for the current top stories . Will raise an requests . HTTPError if we got a non - 200 response back . : return : A list with the top story item numbers ."""
suburl = "v0/topstories.json" try : top_stories = self . _make_request ( suburl ) except requests . HTTPError as e : hn_logger . exception ( 'Faulted on getting top stories, with status {}' . format ( e . errno ) ) raise e return top_stories
def _geom_type ( self , source ) : """gets geometry type ( s ) of specified layer"""
if isinstance ( source , AbstractLayer ) : query = source . orig_query else : query = 'SELECT * FROM "{table}"' . format ( table = source ) resp = self . sql_client . send ( utils . minify_sql ( ( 'SELECT' , ' CASE WHEN ST_GeometryType(the_geom)' , ' in (\'ST_Point\', \'ST_MultiPoint\')' , ' ...
def step_through ( self , msg = '' , shutit_pexpect_child = None , level = 1 , print_input = True , value = True ) : """Implements a step - through function , using pause _ point ."""
shutit_global . shutit_global_object . yield_to_draw ( ) shutit_pexpect_child = shutit_pexpect_child or self . get_current_shutit_pexpect_session ( ) . pexpect_child shutit_pexpect_session = self . get_shutit_pexpect_session_from_child ( shutit_pexpect_child ) if ( not shutit_global . shutit_global_object . determine_i...
def _horizontal_segment ( old_offs , new_offs , spacing , diameter ) : '''Vertices of a horizontal rectangle'''
return np . array ( ( ( old_offs [ 0 ] , old_offs [ 1 ] + spacing [ 1 ] ) , ( new_offs [ 0 ] , old_offs [ 1 ] + spacing [ 1 ] ) , ( new_offs [ 0 ] , old_offs [ 1 ] + spacing [ 1 ] - diameter ) , ( old_offs [ 0 ] , old_offs [ 1 ] + spacing [ 1 ] - diameter ) ) )
def findRoleID ( self , name ) : """searches the roles by name and returns the role ' s ID"""
for r in self : if r [ 'name' ] . lower ( ) == name . lower ( ) : return r [ 'id' ] del r return None
def dynamodb_connection_factory ( ) : """Since SessionStore is called for every single page view , we ' d be establishing new connections so frequently that performance would be hugely impacted . We ' ll lazy - load this here on a per - worker basis . Since boto3 . resource . ( ' dynamodb ' ) objects are stat...
global _DYNAMODB_CONN global _BOTO_SESSION if not _DYNAMODB_CONN : logger . debug ( "Creating a DynamoDB connection." ) if not _BOTO_SESSION : _BOTO_SESSION = Boto3Session ( aws_access_key_id = AWS_ACCESS_KEY_ID , aws_secret_access_key = AWS_SECRET_ACCESS_KEY , region_name = AWS_REGION_NAME ) _DYNAM...
def xml_to_json ( element , definition , required = False ) : # TODO document tuple - it looks little too complex """Convert XML ( ElementTree ) to dictionary from a definition schema . Definition schema can be a simple string - XPath or @ attribute for direct extraction or a complex one described by * dictio...
# handle simple definition if isinstance ( definition , str ) and len ( definition ) > 0 : if definition [ 0 ] == '@' : # test for attribute return element . get ( definition [ 1 : ] ) # get tag text else : sub_element = element . find ( definition ) if sub_element is None : ...
def add_point_region ( self , y : float , x : float ) -> Graphic : """Add a point graphic to the data item . : param x : The x coordinate , in relative units [ 0.0 , 1.0] : param y : The y coordinate , in relative units [ 0.0 , 1.0] : return : The : py : class : ` nion . swift . Facade . Graphic ` object that...
graphic = Graphics . PointGraphic ( ) graphic . position = Geometry . FloatPoint ( y , x ) self . __display_item . add_graphic ( graphic ) return Graphic ( graphic )
def _get_optimal_threshold ( arr , quantized_dtype , num_bins = 8001 , num_quantized_bins = 255 ) : """Given a dataset , find the optimal threshold for quantizing it . The reference distribution is ` q ` , and the candidate distribution is ` p ` . ` q ` is a truncated version of the original distribution . Re...
if isinstance ( arr , NDArray ) : arr = arr . asnumpy ( ) elif isinstance ( arr , list ) : assert len ( arr ) != 0 for i , nd in enumerate ( arr ) : if isinstance ( nd , NDArray ) : arr [ i ] = nd . asnumpy ( ) elif not isinstance ( nd , np . ndarray ) : raise TypeErr...
def update_filters ( self , filters ) : """Modify the filters list . Filter with value 0 will be dropped because not active"""
new_filters = { } for ( filter , values ) in filters . items ( ) : new_values = [ ] for value in values : if isinstance ( value , str ) : new_values . append ( value . strip ( "\n " ) ) else : new_values . append ( int ( value ) ) values = new_values if len ( valu...
def is_string_type ( type_ ) : """Checks if the given type is a string type . : param type _ : The type to check : return : True if the type is a string type , otherwise False : rtype : bool"""
string_types = _get_types ( Types . STRING ) if is_typing_type ( type_ ) : return type_ in string_types or is_regex_type ( type_ ) return type_ in string_types
def _get_gcloud_sdk_credentials ( ) : """Gets the credentials and project ID from the Cloud SDK ."""
from google . auth import _cloud_sdk # Check if application default credentials exist . credentials_filename = ( _cloud_sdk . get_application_default_credentials_path ( ) ) if not os . path . isfile ( credentials_filename ) : return None , None credentials , project_id = _load_credentials_from_file ( credentials_fi...
def targets_w_bins ( cnv_file , access_file , target_anti_fn , work_dir , data ) : """Calculate target and anti - target files with pre - determined bins ."""
target_file = os . path . join ( work_dir , "%s-target.bed" % dd . get_sample_name ( data ) ) anti_file = os . path . join ( work_dir , "%s-antitarget.bed" % dd . get_sample_name ( data ) ) if not utils . file_exists ( target_file ) : target_bin , _ = target_anti_fn ( ) with file_transaction ( data , target_fil...
def draw_header ( self , stream , header ) : """Draw header with underline"""
stream . writeln ( '=' * ( len ( header ) + 4 ) ) stream . writeln ( '| ' + header + ' |' ) stream . writeln ( '=' * ( len ( header ) + 4 ) ) stream . writeln ( )
def configure_plugin ( self , name , options ) : """Configure a plugin . Args : name ( string ) : The name of the plugin . The ` ` : latest ` ` tag is optional , and is the default if omitted . options ( dict ) : A key - value mapping of options Returns : ` ` True ` ` if successful"""
url = self . _url ( '/plugins/{0}/set' , name ) data = options if isinstance ( data , dict ) : data = [ '{0}={1}' . format ( k , v ) for k , v in six . iteritems ( data ) ] res = self . _post_json ( url , data = data ) self . _raise_for_status ( res ) return True
def traverse_ingredients ( self ) : """Recursively traverse this ingredient and its sub - ingredients . Yields ingredient : sacred . Ingredient The ingredient as traversed in preorder . depth : int The depth of the ingredient starting from 0. Raises CircularDependencyError : If a circular structure ...
if self . _is_traversing : raise CircularDependencyError ( ingredients = [ self ] ) else : self . _is_traversing = True yield self , 0 with CircularDependencyError . track ( self ) : for ingredient in self . ingredients : for ingred , depth in ingredient . traverse_ingredients ( ) : yiel...
def add ( self , index , value ) : """Add a value to the series . Args : index ( int ) : Index . value ( float ) : Value ."""
self . buf . append ( value ) if ( index - self . flush_at ) < self . interval : return value = np . mean ( self . buf ) if self . verbose : logger . info ( "iter={} {{{}}}={}" . format ( index , self . name , value ) ) if self . fd is not None : print ( "{} {:g}" . format ( index , value ) , file = self . ...
def _remote_chown ( self , paths , user , sudoable = False ) : """Issue an asynchronous os . chown ( ) call for every path in ` paths ` , then format the resulting return value list with fake _ shell ( ) ."""
LOG . debug ( '_remote_chown(%r, user=%r, sudoable=%r)' , paths , user , sudoable ) ent = self . _connection . get_chain ( ) . call ( pwd . getpwnam , user ) return self . fake_shell ( lambda : mitogen . select . Select . all ( self . _connection . get_chain ( ) . call_async ( os . chown , path , ent . pw_uid , ent . p...
def container_fs_limit_bytes ( self , metric , scraper_config ) : """Number of bytes that can be consumed by the container on this filesystem . This method is used by container _ fs _ usage _ bytes , it doesn ' t report any metric"""
pct_m_name = scraper_config [ 'namespace' ] + '.filesystem.usage_pct' if metric . type not in METRIC_TYPES : self . log . error ( "Metric type %s unsupported for metric %s" % ( metric . type , metric . name ) ) return self . _process_limit_metric ( '' , metric , self . fs_usage_bytes , scraper_config , pct_m_na...
def set_input_score_end_range ( self , score ) : """Sets the input score start range . arg : score ( decimal ) : the new start range raise : InvalidArgument - ` ` score ` ` is invalid raise : NoAccess - ` ` range ` ` cannot be modified * compliance : mandatory - - This method must be implemented . *"""
# Implemented from template for osid . grading . GradeSystemForm . set _ lowest _ numeric _ score if self . get_input_score_end_range_metadata ( ) . is_read_only ( ) : raise errors . NoAccess ( ) try : score = float ( score ) except ValueError : raise errors . InvalidArgument ( ) if not self . _is_valid_dec...
def get ( self , sid ) : """Constructs a KeyContext : param sid : The unique string that identifies the resource : returns : twilio . rest . api . v2010 . account . key . KeyContext : rtype : twilio . rest . api . v2010 . account . key . KeyContext"""
return KeyContext ( self . _version , account_sid = self . _solution [ 'account_sid' ] , sid = sid , )
def remove ( self , * members ) : """Removes @ members from the set - > # int the number of members that were removed from the set"""
if self . serialized : members = list ( map ( self . _dumps , members ) ) return self . _client . srem ( self . key_prefix , * members )
def create_key ( policy = None , description = None , key_usage = None , region = None , key = None , keyid = None , profile = None ) : '''Creates a master key . CLI example : : salt myminion boto _ kms . create _ key ' { " Statement " : . . . } ' " My master key "'''
conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile ) r = { } _policy = salt . serializers . json . serialize ( policy ) try : key_metadata = conn . create_key ( _policy , description = description , key_usage = key_usage ) r [ 'key_metadata' ] = key_metadata [ 'KeyMetadata' ] exc...
def Aitken ( s ) : """Accelerate the convergence of the a series using Aitken ' s delta - squared process ( SCIP calls it Euler ) ."""
def accel ( ) : s0 , s1 , s2 = s >> item [ : 3 ] while 1 : yield s2 - ( s2 - s1 ) ** 2 / ( s0 - 2 * s1 + s2 ) s0 , s1 , s2 = s1 , s2 , next ( s ) return accel ( )
def write ( self , offset , data ) : """Write C { data } into this file at position C { offset } . Extending the file past its original end is expected . Unlike python ' s normal C { write ( ) } methods , this method cannot do a partial write : it must write all of C { data } or else return an error . The d...
writefile = getattr ( self , 'writefile' , None ) if writefile is None : return SFTP_OP_UNSUPPORTED try : # in append mode , don ' t care about seeking if ( self . __flags & os . O_APPEND ) == 0 : if self . __tell is None : self . __tell = writefile . tell ( ) if offset != self . __t...
def _render_template_block_nodelist ( nodelist , block_name , context ) : """Recursively iterate over a node to find the wanted block ."""
# Attempt to find the wanted block in the current template . for node in nodelist : # If the wanted block was found , return it . if isinstance ( node , BlockNode ) : # No matter what , add this block to the rendering context . context . render_context [ BLOCK_CONTEXT_KEY ] . push ( node . name , node ) ...
def yindex ( self ) : """Positions of the data on the y - axis : type : ` ~ astropy . units . Quantity ` array"""
try : return self . _yindex except AttributeError : self . _yindex = Index . define ( self . y0 , self . dy , self . shape [ 1 ] ) return self . _yindex
def get_pkg_list ( self ) : """Returns a dictionary of packages in the following format : : { ' package _ name ' : { ' name ' : ' package _ name ' , ' version ' : ' major . minor . version ' } }"""
if self . query_command : cmd = self . query_command pkg_list = shell_out ( cmd , timeout = 0 , chroot = self . chroot ) . splitlines ( ) for pkg in pkg_list : if '|' not in pkg : continue elif pkg . count ( "|" ) == 1 : name , version = pkg . split ( "|" ) ...
def visit ( self , node ) : """Visit a node ."""
f = self . get_visitor ( node ) if f is not None : return f ( node ) return self . generic_visit ( node )
def transform_streams_for_comparison ( outputs ) : """Makes failure output for streams better by having key be the stream name"""
new_outputs = [ ] for output in outputs : if ( output . output_type == 'stream' ) : # Transform output new_outputs . append ( { 'output_type' : 'stream' , output . name : output . text , } ) else : new_outputs . append ( output ) return new_outputs
def get_routertypes ( self , context , filters = None , fields = None , sorts = None , limit = None , marker = None , page_reverse = False ) : """Lists defined router types ."""
pass
def parse_database_url ( url ) : """Parses a database URL ."""
if url == 'sqlite://:memory:' : # this is a special case , because if we pass this URL into # urlparse , urlparse will choke trying to interpret " memory " # as a port number return { 'ENGINE' : DATABASE_SCHEMES [ 'sqlite' ] , 'NAME' : ':memory:' } # note : no other settings are required for sqlite # otherwise ...
def get_plugin_font ( self , rich_text = False ) : """Return plugin font option . All plugins in Spyder use a global font . This is a convenience method in case some plugins will have a delta size based on the default size ."""
if rich_text : option = 'rich_font' font_size_delta = self . RICH_FONT_SIZE_DELTA else : option = 'font' font_size_delta = self . FONT_SIZE_DELTA return get_font ( option = option , font_size_delta = font_size_delta )
def namespaces ( self , psuedo = True ) : """Fetches a list of namespaces for this wiki and returns them as a dictionary of namespace IDs corresponding to namespace names . If * psuedo * is ` ` True ` ` , the dictionary will also list psuedo - namespaces , which are the " Special : " and " Media : " namespace...
if self . _namespaces is None : result = self . call ( { 'action' : 'query' , 'meta' : 'siteinfo' , 'siprop' : 'namespaces' } ) self . _namespaces = { } self . _psuedo_namespaces = { } for nsid in result [ 'query' ] [ 'namespaces' ] : if int ( nsid ) >= 0 : self . _namespaces [ int (...
def enabled ( name , runas = None ) : '''Ensure the RabbitMQ plugin is enabled . name The name of the plugin runas The user to run the rabbitmq - plugin command as'''
ret = { 'name' : name , 'result' : True , 'comment' : '' , 'changes' : { } } try : plugin_enabled = __salt__ [ 'rabbitmq.plugin_is_enabled' ] ( name , runas = runas ) except CommandExecutionError as err : ret [ 'result' ] = False ret [ 'comment' ] = 'Error: {0}' . format ( err ) return ret if plugin_ena...
def xmlchars ( text ) : """Not all of UTF - 8 is considered valid character data in XML . . . Thus , this function can be used to remove illegal characters from ` ` text ` ` ."""
invalid = list ( range ( 0x9 ) ) invalid . extend ( [ 0xb , 0xc ] ) invalid . extend ( range ( 0xe , 0x20 ) ) return re . sub ( '|' . join ( '\\x%0.2X' % i for i in invalid ) , '' , text )
def register ( self , collector ) : """Registers a collector"""
if not isinstance ( collector , Collector ) : raise TypeError ( "Can't register instance, not a valid type of collector" ) if collector . name in self . collectors : raise ValueError ( "Collector already exists or name colision" ) with mutex : self . collectors [ collector . name ] = collector
def lbol_from_spt_dist_mag ( sptnum , dist_pc , jmag , kmag , format = 'cgs' ) : """Estimate a UCD ' s bolometric luminosity given some basic parameters . sptnum : the spectral type as a number ; 8 - > M8 ; 10 - > L0 ; 20 - > T0 Valid values range between 0 and 30 , ie M0 to Y0. dist _ pc : distance to the ob...
bcj = bcj_from_spt ( sptnum ) bck = bck_from_spt ( sptnum ) n = np . zeros ( sptnum . shape , dtype = np . int ) app_mbol = np . zeros ( sptnum . shape ) w = np . isfinite ( bcj ) & np . isfinite ( jmag ) app_mbol [ w ] += jmag [ w ] + bcj [ w ] n [ w ] += 1 w = np . isfinite ( bck ) & np . isfinite ( kmag ) app_mbol [...
def func_str ( func , args = [ ] , kwargs = { } , type_aliases = [ ] , packed = False , packkw = None , truncate = False ) : """string representation of function definition Returns : str : a representation of func with args , kwargs , and type _ aliases Args : func ( function ) : args ( list ) : argument ...
import utool as ut # if truncate : # truncatekw = { ' maxlen ' : 20} # else : truncatekw = { } argrepr_list = ( [ ] if args is None else ut . get_itemstr_list ( args , nl = False , truncate = truncate , truncatekw = truncatekw ) ) kwrepr_list = ( [ ] if kwargs is None else ut . dict_itemstr_list ( kwargs , explicit = T...
def unregister_all ( self ) : """Safely unregisters all active instances . Errors occurred here will be recorded but not raised ."""
aliases = list ( self . _service_objects . keys ( ) ) for alias in aliases : self . unregister ( alias )
def list_limit_range_for_all_namespaces ( self , ** kwargs ) : """list or watch objects of kind LimitRange This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > thread = api . list _ limit _ range _ for _ all _ namespaces ( async ...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . list_limit_range_for_all_namespaces_with_http_info ( ** kwargs ) else : ( data ) = self . list_limit_range_for_all_namespaces_with_http_info ( ** kwargs ) return data
def _get_union_type_name ( type_names_to_union ) : """Construct a unique union type name based on the type names being unioned ."""
if not type_names_to_union : raise AssertionError ( u'Expected a non-empty list of type names to union, received: ' u'{}' . format ( type_names_to_union ) ) return u'Union__' + u'__' . join ( sorted ( type_names_to_union ) )
def mkdir ( path ) : """Make a directory and its parents . Args : path ( str ) : path to create Returns : None Raises : OSError if the directory cannot be created ."""
try : os . makedirs ( path ) # sanity check if not os . path . isdir ( path ) : # pragma : no cover raise IOError ( 'path is not a directory' ) except OSError as e : # EEXIST if e . errno == 17 and os . path . isdir ( path ) : return raise
def _check_limit ( self ) : """Intenal method : check if current cache size exceeds maximum cache size and pop the oldest item in this case"""
# First compress self . _compress ( ) # Then check the max size if len ( self . _store ) >= self . _max_size : self . _store . popitem ( last = False )
def replace_many ( expression : Expression , replacements : Sequence [ Tuple [ Sequence [ int ] , Replacement ] ] ) -> Replacement : r"""Replaces the subexpressions of * expression * at the given positions with the given replacements . The original * expression * itself is not modified , but a modified copy is re...
if len ( replacements ) == 0 : return expression replacements = sorted ( replacements ) if len ( replacements [ 0 ] [ 0 ] ) == 0 : if len ( replacements ) > 1 : raise IndexError ( "Cannot replace child positions for expression {}, got {!r}" . format ( expression , replacements [ 1 : ] ) ) return rep...
def origin_west_asia ( origin ) : """Returns if the origin is located in Western Asia . Holds true for the following countries : * Armenia * Azerbaijan * Bahrain * Cyprus * Georgia * Iraq * Israel * Jordan * Kuwait * Lebanon * Oman * Qatar * Saudi Arabia * Syria * Turkey * United A...
return origin_armenia ( origin ) or origin_azerbaijan ( origin ) or origin_bahrain ( origin ) or origin_cyprus ( origin ) or origin_georgia ( origin ) or origin_georgia ( origin ) or origin_iraq ( origin ) or origin_israel ( origin ) or origin_jordan ( origin ) or origin_kuwait ( origin ) or origin_lebanon ( origin ) o...
def occupations ( self , site_label ) : """Number of these atoms occupying a specific site type . Args : site _ label ( Str ) : Label for the site type being considered . Returns : ( Int ) : Number of atoms occupying sites of type ` site _ label ` ."""
return sum ( atom . site . label == site_label for atom in self . atoms )
def is_dataset ( ds ) : """Whether ds is a Dataset . Compatible across TF versions ."""
import tensorflow as tf from tensorflow_datasets . core . utils import py_utils dataset_types = [ tf . data . Dataset ] v1_ds = py_utils . rgetattr ( tf , "compat.v1.data.Dataset" , None ) v2_ds = py_utils . rgetattr ( tf , "compat.v2.data.Dataset" , None ) if v1_ds is not None : dataset_types . append ( v1_ds ) if...
def create ( path , saltenv = None ) : '''join ` path ` and ` saltenv ` into a ' salt : / / ' URL .'''
if salt . utils . platform . is_windows ( ) : path = salt . utils . path . sanitize_win_path ( path ) path = salt . utils . data . decode ( path ) query = 'saltenv={0}' . format ( saltenv ) if saltenv else '' url = salt . utils . data . decode ( urlunparse ( ( 'file' , '' , path , '' , query , '' ) ) ) return 'salt...
def send ( self , ** req_kwargs ) : """Send an authenticated request to a Google API . Automatically retries if the access token has expired . Args : * * req _ kwargs : Arbitrary keyword arguments to pass to Requests . Return : dict : The parsed JSON response . Raises : APIException : If the server re...
i = 0 while True : response = self . _send ( ** req_kwargs ) . json ( ) if 'error' not in response : break error = response [ 'error' ] if error [ 'code' ] != 401 : raise exception . APIException ( error [ 'code' ] , error ) if i >= self . RETRY_CNT : raise exception . APIExc...
def get_dom ( self ) -> str : """Retrieves the current value of the DOM for the step"""
if self . is_running : return self . dumps ( ) if self . dom is not None : return self . dom dom = self . dumps ( ) self . dom = dom return dom
def FromData ( cls , stream , json_data , http = None , auto_transfer = None , ** kwds ) : """Create a new Download object from a stream and serialized data ."""
info = json . loads ( json_data ) missing_keys = cls . _REQUIRED_SERIALIZATION_KEYS - set ( info . keys ( ) ) if missing_keys : raise exceptions . InvalidDataError ( 'Invalid serialization data, missing keys: %s' % ( ', ' . join ( missing_keys ) ) ) download = cls . FromStream ( stream , ** kwds ) if auto_transfer ...
def fetchThreads ( self , thread_location , before = None , after = None , limit = None ) : """Get all threads in thread _ location . Threads will be sorted from newest to oldest . : param thread _ location : models . ThreadLocation : INBOX , PENDING , ARCHIVED or OTHER : param before : Fetch only thread befo...
threads = [ ] last_thread_timestamp = None while True : # break if limit is exceeded if limit and len ( threads ) >= limit : break # fetchThreadList returns at max 20 threads before last _ thread _ timestamp ( included ) candidates = self . fetchThreadList ( before = last_thread_timestamp , thread_l...
def _type_digest ( self , config : bool ) -> Dict [ str , Any ] : """Return receiver ' s type digest . Args : config : Specifies whether the type is on a configuration node ."""
res = { "base" : self . yang_type ( ) } if self . name is not None : res [ "derived" ] = self . name return res
def hasField ( self , name ) : """Returns true if field with field _ name exists . @ param name : Field Name @ return : Boolean"""
if self . _autoFixNames : name = self . _fixName ( name ) return self . _fieldAttrDict . has_key ( name )
def symmetrize ( self , max_n = 10 , tolerance = 0.3 , epsilon = 1e-3 ) : """Returns a symmetrized molecule The equivalent atoms obtained via : meth : ` ~ Cartesian . get _ equivalent _ atoms ` are rotated , mirrored . . . unto one position . Then the average position is calculated . The average position ...
mg_mol = self . get_pymatgen_molecule ( ) eq = iterative_symmetrize ( mg_mol , max_n = max_n , tolerance = tolerance , epsilon = epsilon ) self . _convert_eq ( eq ) return eq
def run_interactive ( source_x , source_o , timeout = None , memlimit = None , cgroup = None , cgroup_path = None ) : """Challenges source _ x vs source _ y under time / memory constraints memlimit = memory limit in bytes ( for Lua interpreter and everything under ) cgroup = existing cgroup where to put this co...
msg = msgpack . packb ( [ source_x , source_o ] ) run_lua = os . path . join ( os . path . dirname ( __file__ ) , 'run.lua' ) server = [ os . getenv ( "LUA" , "lua" ) , run_lua , '--server' ] args = dict ( bufsize = 0xffff , stdin = subprocess . PIPE , stdout = subprocess . PIPE ) if timeout is not None : server = ...
def accuracy_study ( tdm = None , u = None , s = None , vt = None , verbosity = 0 , ** kwargs ) : """Reconstruct the term - document matrix and measure error as SVD terms are truncated"""
smat = np . zeros ( ( len ( u ) , len ( vt ) ) ) np . fill_diagonal ( smat , s ) smat = pd . DataFrame ( smat , columns = vt . index , index = u . index ) if verbosity : print ( ) print ( 'Sigma:' ) print ( smat . round ( 2 ) ) print ( ) print ( 'Sigma without zeroing any dim:' ) print ( np . di...
def normalize ( trainingset ) : """Morph the input signal to a mean of 0 and scale the signal strength by dividing with the standard deviation ( rather that forcing a [ 0 , 1 ] range )"""
def encoder ( dataset ) : for instance in dataset : if np . any ( stds == 0 ) : nonzero_indexes = np . where ( stds != 0 ) instance . features [ nonzero_indexes ] = instance . features [ nonzero_indexes ] / stds [ nonzero_indexes ] else : instance . features = ins...
def buffer_typechecks ( self , call_id , payload ) : """Adds typecheck events to the buffer"""
if self . currently_buffering_typechecks : for note in payload [ 'notes' ] : self . buffered_notes . append ( note )
def find ( self , searchText , layers , contains = True , searchFields = "" , sr = "" , layerDefs = "" , returnGeometry = True , maxAllowableOffset = "" , geometryPrecision = "" , dynamicLayers = "" , returnZ = False , returnM = False , gdbVersion = "" ) : """performs the map service find operation"""
url = self . _url + "/find" # print url params = { "f" : "json" , "searchText" : searchText , "contains" : self . _convert_boolean ( contains ) , "searchFields" : searchFields , "sr" : sr , "layerDefs" : layerDefs , "returnGeometry" : self . _convert_boolean ( returnGeometry ) , "maxAllowableOffset" : maxAllowableOffse...
def _mine_send ( self , tag , data ) : '''Send mine data to the master'''
channel = salt . transport . client . ReqChannel . factory ( self . opts ) data [ 'tok' ] = self . tok try : ret = channel . send ( data ) return ret except SaltReqTimeoutError : log . warning ( 'Unable to send mine data to master.' ) return None finally : channel . close ( )
def follows ( self , uri ) : """Follow a remote user by uri ( username @ domain ) . Returns a ` user dict ` _ ."""
params = self . __generate_params ( locals ( ) ) return self . __api_request ( 'POST' , '/api/v1/follows' , params )
def getUsers ( context , roles , allow_empty = True ) : """Present a DisplayList containing users in the specified list of roles"""
mtool = getToolByName ( context , 'portal_membership' ) pairs = allow_empty and [ [ '' , '' ] ] or [ ] users = mtool . searchForMembers ( roles = roles ) for user in users : uid = user . getId ( ) fullname = user . getProperty ( 'fullname' ) if not fullname : fullname = uid pairs . append ( ( ui...
def _handle_parens ( self , children , start , formats ) : """Changes ` children ` and returns new start"""
opens , closes = self . _count_needed_parens ( formats ) old_end = self . source . offset new_end = None for i in range ( closes ) : new_end = self . source . consume ( ')' ) [ 1 ] if new_end is not None : if self . children : children . append ( self . source [ old_end : new_end ] ) new_start = start f...
def clear_request ( name = None ) : '''. . versionadded : : 2017.7.3 Clear out the state execution request without executing it CLI Example : . . code - block : : bash salt ' * ' state . clear _ request'''
notify_path = os . path . join ( __opts__ [ 'cachedir' ] , 'req_state.p' ) serial = salt . payload . Serial ( __opts__ ) if not os . path . isfile ( notify_path ) : return True if not name : try : os . remove ( notify_path ) except ( IOError , OSError ) : pass else : req = check_request ...
def contains_point ( self , p ) : """Returns whether this node or a child overlaps p ."""
for iv in self . s_center : if iv . contains_point ( p ) : return True branch = self [ p > self . x_center ] return branch and branch . contains_point ( p )
def instance_variables ( self ) : """Returns all instance variables in the class , sorted alphabetically as a list of ` pydoc . Variable ` . Instance variables are attributes of ` self ` defined in a class ' s ` _ _ init _ _ ` method ."""
p = lambda o : isinstance ( o , Variable ) and self . module . _docfilter ( o ) return filter ( p , self . doc_init . values ( ) )
def get_rules ( self , description = None ) : '''Returns a list of extraction rules that match a given description . @ description - The description to match against . Returns a list of extraction rules that match the given description . If no description is provided , a list of all rules are returned .'''
if description : rules = [ ] description = description . lower ( ) for i in range ( 0 , len ( self . extract_rules ) ) : if self . extract_rules [ i ] [ 'regex' ] . search ( description ) : rules . append ( self . extract_rules [ i ] ) else : rules = self . extract_rules return rules
def _sign ( self , params ) : '''Generate API sign code'''
for k , v in params . iteritems ( ) : if type ( v ) == int : v = str ( v ) elif type ( v ) == float : v = '%.2f' % v elif type ( v ) in ( list , set ) : v = ',' . join ( [ str ( i ) for i in v ] ) elif type ( v ) == bool : v = 'true' if v else 'false' elif type ( v ) ...
def print_to_file ( object_name ) : """Function takes in object of type str , list , or dict and prints out to current working directory as pyoutput . txt : param : Object : object of type str , list , or dict : return : No return . Just prints out to file handler and save to current working directory as py...
with open ( 'pyoutput.txt' , 'w' ) as filehandler : output = None if isinstance ( object_name , list ) : output = json . dumps ( object , indent = 4 ) if isinstance ( object_name , dict ) : output = json . dumps ( object , indent = 4 ) if isinstance ( object_name , str ) : output...
def pid ( self ) : """Return the pool ID used for connection pooling . : rtype : str"""
return hashlib . md5 ( ':' . join ( [ self . __class__ . __name__ , self . _uri ] ) . encode ( 'utf-8' ) ) . hexdigest ( )
def visit_Variable ( self , node ) : """Visitor for ` Variable ` AST node ."""
var_name = node . identifier . name var_symbol = self . table [ var_name ] if var_symbol is None : raise SementicError ( f"Variable `{var_name}` is not declared." )
def set_low_quality_matches_ ( self , matches , all_matches , match_quality_matrix ) : """Produce additional matches for predictions that have only low - quality matches . Specifically , for each ground - truth find the set of predictions that have maximum overlap with it ( including ties ) ; for each predictio...
# For each gt , find the prediction with which it has highest quality highest_quality_foreach_gt , _ = match_quality_matrix . max ( dim = 1 ) # Find highest quality match available , even if it is low , including ties gt_pred_pairs_of_highest_quality = torch . nonzero ( match_quality_matrix == highest_quality_foreach_g...
def writef ( notebook , nb_file , fmt = None ) : """Write a notebook to the file with given name"""
if nb_file == '-' : write ( notebook , sys . stdout , fmt ) return _ , ext = os . path . splitext ( nb_file ) fmt = copy ( fmt or { } ) fmt = long_form_one_format ( fmt , update = { 'extension' : ext } ) create_prefix_dir ( nb_file , fmt ) with io . open ( nb_file , 'w' , encoding = 'utf-8' ) as stream : wr...
def get_script_str ( self , job_name , launch_dir , executable , qout_path , qerr_path , stdin = None , stdout = None , stderr = None , exec_args = None ) : """Returns a ( multi - line ) String representing the queue script , e . g . PBS script . Uses the template _ file along with internal parameters to create t...
# PbsPro does not accept job _ names longer than 15 chars . if len ( job_name ) > 14 and isinstance ( self , PbsProAdapter ) : job_name = job_name [ : 14 ] # Construct the header for the Queue Manager . qheader = self . _make_qheader ( job_name , qout_path , qerr_path ) # Add the bash section . se = ScriptEditor ( ...
def configure ( self , config ) : """Configures component by passing configuration parameters . : param config : configuration parameters to be set ."""
connections = ConnectionParams . many_from_config ( config ) for connection in connections : self . _connections . append ( connection )
def countStewards ( self ) -> int : """Count the number of stewards added to the pool transaction store Note : This is inefficient , a production use case of this function should require an efficient storage mechanism"""
# THIS SHOULD NOT BE DONE FOR PRODUCTION return sum ( 1 for _ , txn in self . ledger . getAllTxn ( ) if ( get_type ( txn ) == NYM ) and ( get_payload_data ( txn ) . get ( ROLE ) == STEWARD ) )
def get_soundcloud_api_playlist_data ( playlist_id ) : """Scrape the new API . Returns the parsed JSON response ."""
url = "https://api.soundcloud.com/playlists/%s?representation=full&client_id=02gUJC0hH2ct1EGOcYXQIzRFU91c72Ea&app_version=1467724310" % ( playlist_id ) response = requests . get ( url ) parsed = response . json ( ) return parsed
def _is_data_from_today ( self , data_point ) : """Takes a DataPoint from SESConnection . get _ send _ statistics ( ) and returns True if it is talking about the current date , False if not . : param dict data _ point : The data point to consider . : rtype : bool : returns : True if this data _ point is for...
today = datetime . date . today ( ) raw_timestr = data_point [ 'Timestamp' ] dtime = datetime . datetime . strptime ( raw_timestr , '%Y-%m-%dT%H:%M:%SZ' ) return today . day == dtime . day
def display_weyl ( decomps ) : """Construct and display 3D plot of canonical coordinates"""
tx , ty , tz = list ( zip ( * decomps ) ) rcParams [ 'axes.labelsize' ] = 24 rcParams [ 'font.family' ] = 'serif' rcParams [ 'font.serif' ] = [ 'Computer Modern Roman' ] rcParams [ 'text.usetex' ] = True fig = pyplot . figure ( ) ax = Axes3D ( fig ) ax . scatter ( tx , ty , tz ) ax . plot ( ( 1 , ) , ( 1 , ) , ( 1 , ) ...
def active_thresholds_value_maps ( keywords , exposure_key ) : """Helper to retrieve active value maps or thresholds for an exposure . : param keywords : Hazard layer keywords . : type keywords : dict : param exposure _ key : The exposure key . : type exposure _ key : str : returns : Active thresholds or ...
if 'classification' in keywords : if keywords [ 'layer_mode' ] == layer_mode_continuous [ 'key' ] : return keywords [ 'thresholds' ] else : return keywords [ 'value_map' ] if keywords [ 'layer_mode' ] == layer_mode_continuous [ 'key' ] : classifications = keywords [ 'thresholds' ] . get ( ex...
def normalize_example_nlp ( task , example , is_infer , vocab_type , vocab_offset , max_input_length , max_target_length , fixed_train_length ) : """Normalize the examples from different tasks so they can be merged . This function is specific to NLP tasks and normalizes them so that in the end the example only ...
if task . has_inputs : example [ "inputs" ] = example [ "inputs" ] [ : - 1 ] # remove EOS token if hasattr ( task , "class_labels" ) : if vocab_type == text_problems . VocabType . CHARACTER : # TODO ( urvashik ) : handle the case where num _ labels > 9 example [ "targets" ] = tf . cast ( discretization ...
def load_env ( file ) : """Generate environment used for ' org . restore ' method : param file : env file : return : env"""
env = yaml . load ( open ( file ) ) for org in env . get ( 'organizations' , [ ] ) : if not org . get ( 'applications' ) : org [ 'applications' ] = [ ] if org . get ( 'starter-kit' ) : kit_meta = get_starter_kit_meta ( org . get ( 'starter-kit' ) ) for meta_app in get_applications_from_m...
def smooth_1D ( arr , n = 10 , smooth_type = "flat" ) -> np . ndarray : """Smooth 1D data using a window function . Edge effects will be present . Parameters arr : array _ like Input array , 1D . n : int ( optional ) Window length . smooth _ type : { ' flat ' , ' hanning ' , ' hamming ' , ' bartlett '...
# check array input if arr . ndim != 1 : raise wt_exceptions . DimensionalityError ( 1 , arr . ndim ) if arr . size < n : message = "Input array size must be larger than window size." raise wt_exceptions . ValueError ( message ) if n < 3 : return arr # construct window array if smooth_type == "flat" : ...
def tags ( self ) : """Creates a list of all the tags of the contained items # Returns ` list [ str ] ` > A list of all the tags"""
tags = set ( ) for i in self : tags |= set ( i . keys ( ) ) return tags
def _filter_queryset ( self , queryset ) : """Filter queryset by entity , label and position . Due to a bug in django - filter these filters have to be applied manually : https : / / github . com / carltongibson / django - filter / issues / 883"""
entities = self . request . query_params . getlist ( 'entity' ) labels = self . request . query_params . getlist ( 'label' ) positions = self . request . query_params . getlist ( 'position' ) if labels and len ( labels ) != len ( entities ) : raise exceptions . ParseError ( 'If `labels` query parameter is given, al...
def get_user_info ( self , save_to_config = True ) : """Get user info and settings from Filemail . : param save _ to _ config : Whether or not to save settings to config file : type save _ to _ config : ` ` bool ` ` : rtype : ` ` dict ` ` containig user information and default settings ."""
method , url = get_URL ( 'user_get' ) payload = { 'apikey' : self . config . get ( 'apikey' ) , 'logintoken' : self . session . cookies . get ( 'logintoken' ) } res = getattr ( self . session , method ) ( url , params = payload ) if res . status_code == 200 : settings = res . json ( ) [ 'user' ] if save_to_conf...
def _domain_event_watchdog_cb ( conn , domain , action , opaque ) : '''Domain watchdog events handler'''
_salt_send_domain_event ( opaque , conn , domain , opaque [ 'event' ] , { 'action' : _get_libvirt_enum_string ( 'VIR_DOMAIN_EVENT_WATCHDOG_' , action ) } )
def sigmaT2 ( self , R , z , nsigma = None , mc = False , nmc = 10000 , gl = True , ngl = _DEFAULTNGL , ** kwargs ) : """NAME : sigmaT2 PURPOSE : calculate sigma _ T ^ 2 by marginalizing over velocity INPUT : R - radius at which to calculate this ( can be Quantity ) z - height at which to calculate this...
if mc : surfmass , vrs , vts , vzs = self . _vmomentdensity ( R , z , 0. , 0. , 0. , nsigma = nsigma , mc = mc , nmc = nmc , _returnmc = True , ** kwargs ) mvt = self . _vmomentdensity ( R , z , 0. , 1. , 0. , nsigma = nsigma , mc = mc , nmc = nmc , _returnmc = False , _vrs = vrs , _vts = vts , _vzs = vzs , ** ...
def listen ( self , listenip = "" , listenport = DEF_TFTP_PORT , timeout = SOCK_TIMEOUT ) : """Start a server listening on the supplied interface and port . This defaults to INADDR _ ANY ( all interfaces ) and UDP port 69 . You can also supply a different socket timeout value , if desired ."""
tftp_factory = TftpPacketFactory ( ) # Don ' t use new 2.5 ternary operator yet # listenip = listenip if listenip else ' 0.0.0.0' if not listenip : listenip = '0.0.0.0' log . info ( "Server requested on ip %s, port %s" % ( listenip , listenport ) ) try : # FIXME - sockets should be non - blocking self . sock = ...
def create_policy ( self , account , client , document , name , arn = None ) : """Create a new IAM policy . If the policy already exists , a new version will be added and if needed the oldest policy version not in use will be removed . Returns a dictionary containing the policy or version information Args : ...
if not arn and not name : raise ValueError ( 'create_policy must be called with either arn or name in the argument list' ) if arn : response = client . list_policy_versions ( PolicyArn = arn ) # If we ' re at the max of the 5 possible versions , remove the oldest version that is not # the currently acti...
def get_starred ( self ) : """: calls : ` GET / user / starred < http : / / developer . github . com / v3 / activity / starring > ` _ : rtype : : class : ` github . PaginatedList . PaginatedList ` of : class : ` github . Repository . Repository `"""
return github . PaginatedList . PaginatedList ( github . Repository . Repository , self . _requester , "/user/starred" , None )