signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def strip_trailing_slashes ( self , path ) : """Return input path minus any trailing slashes ."""
m = re . match ( r"(.*)/+$" , path ) if ( m is None ) : return ( path ) return ( m . group ( 1 ) )
def _get_key_location ( self , key ) -> ( int , int ) : """Return chunk no and 1 - based offset of key : param key : : return :"""
key = int ( key ) if key == 0 : return 1 , 0 remainder = key % self . chunkSize addend = ChunkedFileStore . firstChunkIndex chunk_no = key - remainder + addend if remainder else key - self . chunkSize + addend offset = remainder or self . chunkSize return chunk_no , offset
def get_hosted_zone ( Id , region = None , key = None , keyid = None , profile = None ) : '''Return detailed info about the given zone . Id The unique Zone Identifier for the Hosted Zone . region Region to connect to . key Secret key to be used . keyid Access key to be used . profile Dict , or p...
conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile ) args = { 'Id' : Id } return _collect_results ( conn . get_hosted_zone , None , args )
def uinit ( self , ushape ) : """Return initialiser for working variable U ."""
if self . opt [ 'Y0' ] is None : return np . zeros ( ushape , dtype = self . dtype ) else : # If initial Y is non - zero , initial U is chosen so that # the relevant dual optimality criterion ( see ( 3.10 ) in # boyd - 2010 - distributed ) is satisfied . Yss = np . sqrt ( np . sum ( self . Y [ ... , 0 : - 1 ] *...
def _drop_nodes_from_errorpaths ( self , _errors , dp_items , sp_items ) : """Removes nodes by index from an errorpath , relatively to the basepaths of self . : param errors : A list of : class : ` errors . ValidationError ` instances . : param dp _ items : A list of integers , pointing at the nodes to drop f...
dp_basedepth = len ( self . document_path ) sp_basedepth = len ( self . schema_path ) for error in _errors : for i in sorted ( dp_items , reverse = True ) : error . document_path = drop_item_from_tuple ( error . document_path , dp_basedepth + i ) for i in sorted ( sp_items , reverse = True ) : e...
def _getpwnam ( name , root = None ) : '''Alternative implementation for getpwnam , that use only / etc / passwd'''
root = '/' if not root else root passwd = os . path . join ( root , 'etc/passwd' ) with salt . utils . files . fopen ( passwd ) as fp_ : for line in fp_ : line = salt . utils . stringutils . to_unicode ( line ) comps = line . strip ( ) . split ( ':' ) if comps [ 0 ] == name : # Generate a ge...
def plot_factor_rank_auto_correlation ( factor_autocorrelation , period = 1 , ax = None ) : """Plots factor rank autocorrelation over time . See factor _ rank _ autocorrelation for more details . Parameters factor _ autocorrelation : pd . Series Rolling 1 period ( defined by time _ rule ) autocorrelation ...
if ax is None : f , ax = plt . subplots ( 1 , 1 , figsize = ( 18 , 6 ) ) factor_autocorrelation . plot ( title = '{} Period Factor Rank Autocorrelation' . format ( period ) , ax = ax ) ax . set ( ylabel = 'Autocorrelation Coefficient' , xlabel = '' ) ax . axhline ( 0.0 , linestyle = '-' , color = 'black' , lw = 1 )...
def write_bashrc ( _path ) : """Write a valid gentoo bashrc file to : path : . Args : path - The output path of the make . conf"""
cfg_mounts = CFG [ "container" ] [ "mounts" ] . value cfg_prefix = CFG [ "container" ] [ "prefixes" ] . value path . mkfile_uchroot ( "/etc/portage/bashrc" ) mounts = uchroot . mounts ( "mnt" , cfg_mounts ) p_paths , p_libs = uchroot . env ( cfg_prefix ) paths , libs = uchroot . env ( mounts ) paths = paths + p_paths l...
def dropEvent ( self , event ) : """Processes the drag drop event using the filter set by the setDragDropFilter : param event | < QDropEvent >"""
filt = self . dragDropFilter ( ) if ( filt and not filt ( self , event ) ) : return super ( XTableWidget , self ) . dropEvent ( event )
def parse ( binary , ** params ) : """Turns a JSON structure into a python object ."""
encoding = params . get ( 'charset' , 'UTF-8' ) return json . loads ( binary , encoding = encoding )
def filter ( self , record ) : """Is the specified record to be logged ? Returns zero for no , nonzero for yes . If deemed appropriate , the record may be modified in - place by this method . : param logging . LogRecord record : The log record to process : rtype : int"""
if self . _exists : return int ( getattr ( record , 'correlation_id' , None ) is not None ) return int ( getattr ( record , 'correlation_id' , None ) is None )
def create_data ( datatype = 'ChanTime' , n_trial = 1 , s_freq = 256 , chan_name = None , n_chan = 8 , time = None , freq = None , start_time = None , signal = 'random' , amplitude = 1 , color = 0 , sine_freq = 10 , attr = None ) : """Create data of different datatype from scratch . Parameters datatype : str ...
possible_datatypes = ( 'ChanTime' , 'ChanFreq' , 'ChanTimeFreq' ) if datatype not in possible_datatypes : raise ValueError ( 'Datatype should be one of ' + ', ' . join ( possible_datatypes ) ) if time is not None : if isinstance ( time , tuple ) and len ( time ) == 2 : time = arange ( time [ 0 ] , time ...
def _build_credentials ( self , nexus_switches ) : """Build credential table for Rest API Client . : param nexus _ switches : switch config : returns credentials : switch credentials list"""
credentials = { } for switch_ip , attrs in nexus_switches . items ( ) : credentials [ switch_ip ] = ( attrs [ const . USERNAME ] , attrs [ const . PASSWORD ] , attrs [ const . HTTPS_VERIFY ] , attrs [ const . HTTPS_CERT ] , None ) if not attrs [ const . HTTPS_VERIFY ] : LOG . warning ( "HTTPS Certificat...
def scan ( self , string ) : """Returns True if search ( Sentence ( string ) ) may yield matches . If is often faster to scan prior to creating a Sentence and searching it ."""
# In the following example , first scan the string for " good " and " bad " : # p = Pattern . fromstring ( " good | bad NN " ) # for s in open ( " parsed . txt " ) : # if p . scan ( s ) : # s = Sentence ( s ) # m = p . search ( s ) # if m : # print ( m ) w = ( constraint . words for constraint in self . sequence if not...
def user_token ( scopes , client_id = None , client_secret = None , redirect_uri = None ) : """Generate a user access token : param List [ str ] scopes : Scopes to get : param str client _ id : Spotify Client ID : param str client _ secret : Spotify Client secret : param str redirect _ uri : Spotify redirec...
webbrowser . open_new ( authorize_url ( client_id = client_id , redirect_uri = redirect_uri , scopes = scopes ) ) code = parse_code ( raw_input ( 'Enter the URL that you were redirected to: ' ) ) return User ( code , client_id = client_id , client_secret = client_secret , redirect_uri = redirect_uri )
def load_config ( filename = "logging.ini" , * args , ** kwargs ) : """Load logger config from file Keyword arguments : filename - - configuration filename ( Default : " logging . ini " ) * args - - options passed to fileConfig * * kwargs - - options passed to fileConfigg"""
logging . config . fileConfig ( filename , * args , ** kwargs )
def gate ( self , name , params , qubits ) : """Add a gate to the program . . . note : : The matrix elements along each axis are ordered by bitstring . For two qubits the order is ` ` 00 , 01 , 10 , 11 ` ` , where the the bits * * are ordered in reverse * * by the qubit index , i . e . , for qubits 0 and 1 ...
return self . inst ( Gate ( name , params , [ unpack_qubit ( q ) for q in qubits ] ) )
def draw ( self , startpoint = ( 0 , 0 ) , mode = 'plain' , showfig = False ) : """lattice visualization : param startpoint : start drawing point coords , default : ( 0 , 0) : param showfig : show figure or not , default : False : param mode : artist mode , ' plain ' or ' fancy ' , ' plain ' by default : re...
p0 = startpoint angle = 0.0 patchlist = [ ] anotelist = [ ] xmin0 , xmax0 , ymin0 , ymax0 = 0 , 0 , 0 , 0 xmin , xmax , ymin , ymax = 0 , 0 , 0 , 0 for ele in self . _lattice_eleobjlist : ele . setDraw ( p0 = p0 , angle = angle , mode = mode ) angle += ele . next_inc_angle # print ( ele . name + ele . next ...
def _interpolate_cube ( self , lon , lat , egy = None , interp_log = True ) : """Perform interpolation on a healpix cube . If egy is None then interpolation will be performed on the existing energy planes ."""
shape = np . broadcast ( lon , lat , egy ) . shape lon = lon * np . ones ( shape ) lat = lat * np . ones ( shape ) theta = np . pi / 2. - np . radians ( lat ) phi = np . radians ( lon ) vals = [ ] for i , _ in enumerate ( self . hpx . evals ) : v = hp . pixelfunc . get_interp_val ( self . counts [ i ] , theta , phi...
def answers ( self , other ) : """DEV : true if self is an answer from other"""
if other . __class__ == self . __class__ : return ( other . service + 0x40 ) == self . service or ( self . service == 0x7f and ( self . requestServiceId == other . service ) ) return 0
def data_to_binary ( self ) : """: return : bytes"""
return bytes ( [ COMMAND_CODE , self . channels_to_byte ( self . closed ) , self . channels_to_byte ( self . enabled ) , self . channels_to_byte ( self . normal ) , self . channels_to_byte ( self . locked ) ] )
def simple_dict ( ) -> Callable : """A simple dictionary format that does not require spaces or quoting . Supported types : bool , int , float : return : A method that can be used as a type in argparse ."""
def parse ( dict_str : str ) : def _parse ( value : str ) : if value == "True" : return True if value == "False" : return False if "." in value : return float ( value ) return int ( value ) _dict = dict ( ) try : for entry in dict_s...
def _format_event ( self , orig_event , external_metadata = None ) : """Format the event to the expected Alooma format , packing it into a message field and adding metadata : param orig _ event : The original event that was sent , should be dict , str or unicode . : param external _ metadata : ( Optional ) ...
event_wrapper = { } # Add ISO6801 timestamp and frame info timestamp = datetime . datetime . utcnow ( ) . isoformat ( ) event_wrapper [ consts . WRAPPER_REPORT_TIME ] = timestamp # Add the enclosing frame frame = inspect . currentframe ( ) . f_back . f_back filename = frame . f_code . co_filename line_number = frame . ...
def validate_str ( s ) : """Validate a string Parameters s : str Returns str Raises ValueError"""
if not isinstance ( s , six . string_types ) : raise ValueError ( "Did not found string!" ) return six . text_type ( s )
def get_valid_https_verify ( value ) : '''Get a value that can be the boolean representation of a string or a boolean itself and returns It as a boolean . If this is not the case , It returns a string . : value : The HTTPS _ verify input value . A string can be passed as a path to a CA _ BUNDLE certificate ...
http_verify_value = value bool_values = { 'false' : False , 'true' : True } if isinstance ( value , bool ) : http_verify_value = value elif ( isinstance ( value , str ) or isinstance ( value , unicode ) ) and value . lower ( ) in bool_values . keys ( ) : http_verify_value = bool_values [ value . lower ( ) ] ret...
def _is_url ( url ) : """Used to determine if a given string represents a URL"""
regex = re . compile ( r'^(?:http|ftp)s?://' # http : / / or https : / / r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain . . . r'localhost|' # localhost . . . r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # . . . or ip r'(?::\d+)?' # optional port r'(?:/?|[/?]\S+)$' , re . IGNOREC...
def inflate_parameter_leaf ( sub_parameter , base_year , inflator , unit_type = 'unit' ) : """Inflate a Parameter leaf according to unit type Basic unit type are supposed by default Other admissible unit types are threshold _ unit and rate _ unit"""
if isinstance ( sub_parameter , Scale ) : if unit_type == 'threshold_unit' : for bracket in sub_parameter . brackets : threshold = bracket . children [ 'threshold' ] inflate_parameter_leaf ( threshold , base_year , inflator ) return else : # Remove new values for year > base ...
def _check_command_parameters ( self , ** kwargs ) : """Params given to exec _ cmd should satisfy required params . : params : kwargs : raises : MissingRequiredCommandParameter"""
rset = self . _meta_data [ 'required_command_parameters' ] check = _missing_required_parameters ( rset , ** kwargs ) if check : error_message = 'Missing required params: %s' % check raise MissingRequiredCommandParameter ( error_message )
def _enqueue_init_updates ( self ) : """Enqueues current routes to be shared with this peer ."""
assert self . state . bgp_state == const . BGP_FSM_ESTABLISHED if self . is_mbgp_cap_valid ( RF_RTC_UC ) : # Enqueues all best - RTC _ NLRIs to be sent as initial update to this # peer . self . _peer_manager . comm_all_rt_nlris ( self ) self . _schedule_sending_init_updates ( ) else : # Enqueues all best - path...
def groups_to_display ( self , value ) : """An array containing the unsubscribe groups that you would like to be displayed on the unsubscribe preferences page . Max of 25 groups . : param groups _ to _ display : Unsubscribe groups to display : type groups _ to _ display : GroupsToDisplay , list ( int ) , opti...
if isinstance ( value , GroupsToDisplay ) : self . _groups_to_display = value else : self . _groups_to_display = GroupsToDisplay ( value )
def validate ( self , ** kwargs ) : """Validates a submission file : param file _ path : path to file to be loaded . : param data : pre loaded YAML object ( optional ) . : return : Bool to indicate the validity of the file ."""
try : submission_file_schema = json . load ( open ( self . default_schema_file , 'r' ) ) additional_file_section_schema = json . load ( open ( self . additional_info_schema , 'r' ) ) # even though we are using the yaml package to load , # it supports JSON and YAML data = kwargs . pop ( "data" , None...
def draw_spectra_stacked ( ss , title = None , num_rows = None , setup = _default_setup ) : """Same as plot _ spectra _ stacked ( ) , but does not call plt . show ( ) ; returns figure"""
n = len ( ss ) assert n > 0 , "ss is empty" if not num_rows : num_rows = n num_cols = 1 else : num_cols = int ( np . ceil ( float ( n ) / num_rows ) ) a99 . format_BLB ( ) fig , axarr = plt . subplots ( num_rows , num_cols , sharex = True , squeeze = False ) xmin = 1e38 xmax = - 1e38 i , j = - 1 , num_cols ...
def to_iter ( obj ) : """Convert an object to a list if it is not already an iterable . Nones are returned unaltered . This is an awful function that proliferates an explosion of types , please do not use anymore ."""
if isinstance ( obj , type ( None ) ) : return None elif isinstance ( obj , six . string_types ) : return [ obj ] else : # Nesting here since symmetry is broken in isinstance checks . # Strings are iterables in python 3 , so the relative order of if statements is important . if isinstance ( obj , collection...
def get ( self , name_or_klass ) : """Gets a mode by name ( or class ) : param name _ or _ klass : The name or the class of the mode to get : type name _ or _ klass : str or type : rtype : pyqode . core . api . Mode"""
if not isinstance ( name_or_klass , str ) : name_or_klass = name_or_klass . __name__ return self . _modes [ name_or_klass ]
def map_to_adjust ( self , strain , ** params ) : """Map an input dictionary of sampling parameters to the adjust _ strain function by filtering the dictionary for the calibration parameters , then calling adjust _ strain . Parameters strain : FrequencySeries The strain to be recalibrated . params : dic...
# calibration param names arg_names = [ 'delta_fs' , 'delta_fc' , 'delta_qinv' , 'kappa_c' , 'kappa_tst_re' , 'kappa_tst_im' , 'kappa_pu_re' , 'kappa_pu_im' ] # calibration param labels as they exist in config files arg_labels = [ '' . join ( [ 'calib_' , name ] ) for name in arg_names ] # default values for calibratio...
def enable_global_typelogged_profiler ( flag = True ) : """Enables or disables global typelogging mode via a profiler . See flag global _ typelogged _ profiler . Does not work if typelogging _ enabled is false ."""
global global_typelogged_profiler , _global_type_agent , global_typechecked_profiler global_typelogged_profiler = flag if flag and typelogging_enabled : if _global_type_agent is None : _global_type_agent = TypeAgent ( ) _global_type_agent . start ( ) elif not _global_type_agent . active : ...
def _zforce ( self , R , z , phi = 0. , t = 0. ) : """NAME : _ zforce PURPOSE : evaluate the vertical force for this potential INPUT : R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT : the vertical force HISTORY : 2010-07-09 - Written - Bovy ( NYU )"""
sqrtbz = nu . sqrt ( self . _b2 + z ** 2. ) asqrtbz = self . _a + sqrtbz if isinstance ( R , float ) and sqrtbz == asqrtbz : return ( - z / ( R ** 2. + ( self . _a + nu . sqrt ( z ** 2. + self . _b2 ) ) ** 2. ) ** ( 3. / 2. ) ) else : return ( - z * asqrtbz / sqrtbz / ( R ** 2. + ( self . _a + nu . sqrt ( z ** ...
def nltk_tokenzier_factory ( nltk_tokenizer ) : '''Parameters nltk _ tokenizer : nltk . tokenize . * instance ( e . g . , nltk . TreebankWordTokenizer ( ) ) Returns Doc of tweets Notes Requires NLTK to be installed'''
def tokenize ( text ) : toks = [ ] for tok in nltk_tokenizer . tokenize ( text ) : if len ( tok ) > 0 : toks . append ( Tok ( _get_pos_tag ( tok ) , tok . lower ( ) , tok . lower ( ) , ent_type = '' , tag = '' ) ) return Doc ( [ toks ] , text ) return tokenize
def _split_module_dicts ( ) : '''Create a copy of _ _ salt _ _ dictionary with module . function and module [ function ] Takes advantage of Jinja ' s syntactic sugar lookup : . . code - block : : { { salt . cmd . run ( ' uptime ' ) } }'''
if not isinstance ( __salt__ , dict ) : return __salt__ mod_dict = dict ( __salt__ ) for module_func_name , mod_fun in six . iteritems ( mod_dict . copy ( ) ) : mod , fun = module_func_name . split ( '.' , 1 ) if mod not in mod_dict : # create an empty object that we can add attributes to mod_dict [...
def get_application_configuration ( name ) : """Get a named application configuration . An application configuration is a named set of securely stored properties where each key and its value in the property set is a string . An application configuration object is used to store information that IBM Streams a...
_check ( ) rc = _ec . get_application_configuration ( name ) if rc is False : raise ValueError ( "Application configuration {0} not found." . format ( name ) ) return rc
def battery_update ( self , SYS_STATUS ) : '''update battery level'''
# main flight battery self . battery_level = SYS_STATUS . battery_remaining self . voltage_level = SYS_STATUS . voltage_battery self . current_battery = SYS_STATUS . current_battery if self . settings . numcells != 0 : self . per_cell = ( self . voltage_level * 0.001 ) / self . settings . numcells
def _make_middleware_stack ( middleware , base ) : """Given a list of in - order middleware callables ` middleware ` and a base function ` base ` , chains them together so each middleware is fed the function below , and returns the top level ready to call ."""
for ware in reversed ( middleware ) : base = ware ( base ) return base
def parse_children ( parent ) : """Recursively parse child tags until match is found"""
components = [ ] for tag in parent . children : matched = parse_tag ( tag ) if matched : components . append ( matched ) elif hasattr ( tag , 'contents' ) : components += parse_children ( tag ) return components
def compile_less ( input_file , output_file ) : """Compile a LESS source file . Minifies the output in release mode ."""
from . modules import less if not isinstance ( input_file , str ) : raise RuntimeError ( 'LESS compiler takes only a single input file.' ) return { 'dependencies_fn' : less . less_dependencies , 'compiler_fn' : less . less_compile , 'input' : input_file , 'output' : output_file , 'kwargs' : { } , }
def is_processed ( self , db_versions ) : """Check if version is already applied in the database . : param db _ versions :"""
return self . number in ( v . number for v in db_versions if v . date_done )
def create_image ( cloud , ** kwargs ) : """proxy call for ec2 , rackspace create ami backend functions"""
if cloud == 'ec2' : return create_ami ( ** kwargs ) if cloud == 'rackspace' : return create_rackspace_image ( ** kwargs ) if cloud == 'gce' : return create_gce_image ( ** kwargs )
def client_delete ( self , url , ** kwargs ) : """Send POST request with given url ."""
response = requests . delete ( self . make_url ( url ) , headers = self . headers ) if not response . ok : raise Exception ( '{status}: {reason}.\nCircleCI Status NOT OK' . format ( status = response . status_code , reason = response . reason ) ) return response . json ( )
def get_dist_dependencies ( name , recurse = True ) : """Get the dependencies of the given , already installed distribution . @ param recurse If True , recursively find all dependencies . @ returns A set of package names . @ note The first entry in the list is always the top - level package itself ."""
dist = pkg_resources . get_distribution ( name ) pkg_name = convert_name ( dist . project_name ) reqs = set ( ) working = set ( [ dist ] ) depth = 0 while working : deps = set ( ) for distname in working : dist = pkg_resources . get_distribution ( distname ) pkg_name = convert_name ( dist . proj...
def list_policies ( region = None , key = None , keyid = None , profile = None ) : '''List all policies Returns list of policies CLI Example : . . code - block : : bash salt myminion boto _ iot . list _ policies Example Return : . . code - block : : yaml policies :'''
try : conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile ) policies = [ ] for ret in __utils__ [ 'boto3.paged_call' ] ( conn . list_policies , marker_flag = 'nextMarker' , marker_arg = 'marker' ) : policies . extend ( ret [ 'policies' ] ) if not bool ( policies ) ...
def add_to_gui ( self , content ) : """add content to the gui script ."""
if not self . rewrite_config : raise DirectoryException ( "Error! Directory was not intialized w/ rewrite_config." ) if not self . gui_file : self . gui_path , self . gui_file = self . __get_gui_handle ( self . root_dir ) self . gui_file . write ( content + '\n' )
def threshold_monitor_hidden_threshold_monitor_Memory_poll ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) threshold_monitor_hidden = ET . SubElement ( config , "threshold-monitor-hidden" , xmlns = "urn:brocade.com:mgmt:brocade-threshold-monitor" ) threshold_monitor = ET . SubElement ( threshold_monitor_hidden , "threshold-monitor" ) Memory = ET . SubElement ( threshold_monitor , "Memory" ...
def report_pairs ( data , cutoff = 0 , mateorientation = None , pairsfile = None , insertsfile = None , rclip = 1 , ascii = False , bins = 20 , distmode = "ss" , mpcutoff = 1000 ) : """This subroutine is used by the pairs function in blast . py and cas . py . Reports number of fragments and pairs as well as linke...
allowed_mateorientations = ( "++" , "--" , "+-" , "-+" ) if mateorientation : assert mateorientation in allowed_mateorientations num_fragments , num_pairs = 0 , 0 all_dist = [ ] linked_dist = [ ] # + - ( forward - backward ) is ` innie ` , - + ( backward - forward ) is ` outie ` orientations = defaultdict ( int ) #...
def removeextensibles ( bunchdt , data , commdct , key , objname ) : """remove the extensible items in the object"""
theobject = getobject ( bunchdt , key , objname ) if theobject == None : return theobject theidd = iddofobject ( data , commdct , key ) extensible_i = [ i for i in range ( len ( theidd ) ) if 'begin-extensible' in theidd [ i ] ] try : extensible_i = extensible_i [ 0 ] except IndexError : return theobject wh...
def clearOldCalibrations ( self , date = None ) : '''if not only a specific date than remove all except of the youngest calibration'''
self . coeffs [ 'dark current' ] = [ self . coeffs [ 'dark current' ] [ - 1 ] ] self . coeffs [ 'noise' ] = [ self . coeffs [ 'noise' ] [ - 1 ] ] for light in self . coeffs [ 'flat field' ] : self . coeffs [ 'flat field' ] [ light ] = [ self . coeffs [ 'flat field' ] [ light ] [ - 1 ] ] for light in self . coeffs [...
def WriteFileEntry ( self , path ) : """Writes the file path to file . Args : path ( str ) : path of the file ."""
string = '{0:s}\n' . format ( path ) encoded_string = self . _EncodeString ( string ) self . _file_object . write ( encoded_string )
def _add ( self ) : """Add function logic , override to implement different logic returns add widget or None"""
is_valid_form = True get_filter_args ( self . _filters ) exclude_cols = self . _filters . get_relation_cols ( ) form = self . add_form . refresh ( ) if request . method == "POST" : self . _fill_form_exclude_cols ( exclude_cols , form ) if form . validate ( ) : self . process_form ( form , True ) ...
def list_length ( queue , backend = 'sqlite' ) : '''Provide the number of items in a queue CLI Example : . . code - block : : bash salt - run queue . list _ length myqueue salt - run queue . list _ length myqueue backend = sqlite'''
queue_funcs = salt . loader . queues ( __opts__ ) cmd = '{0}.list_length' . format ( backend ) if cmd not in queue_funcs : raise SaltInvocationError ( 'Function "{0}" is not available' . format ( cmd ) ) ret = queue_funcs [ cmd ] ( queue = queue ) return ret
def set_layer ( self , name : str , matrix : np . ndarray , chunks : Tuple [ int , int ] = ( 64 , 64 ) , chunk_cache : int = 512 , dtype : str = "float32" , compression_opts : int = 2 ) -> None : """* * DEPRECATED * * - Use ` ds . layer . Name = matrix ` or ` ds . layer [ ` Name ` ] = matrix ` instead"""
deprecated ( "'set_layer' is deprecated. Use 'ds.layer.Name = matrix' or 'ds.layer['Name'] = matrix' instead" ) self . layers [ name ] = matrix
def alignment_a ( self ) : """Computes the rotation matrix that aligns the unit cell with the Cartesian axes , starting with cell vector a . * a parallel to x * b in xy - plane with b _ y positive * c with c _ z positive"""
from molmod . transformations import Rotation new_x = self . matrix [ : , 0 ] . copy ( ) new_x /= np . linalg . norm ( new_x ) new_z = np . cross ( new_x , self . matrix [ : , 1 ] ) new_z /= np . linalg . norm ( new_z ) new_y = np . cross ( new_z , new_x ) new_y /= np . linalg . norm ( new_y ) return Rotation ( np . ar...
def _parse_allow ( allow ) : '''Convert firewall rule allowed user - string to specified REST API format .'''
# input = > tcp : 53 , tcp : 80 , tcp : 443 , icmp , tcp : 4201 , udp : 53 # output < = [ # { " IPProtocol " : " tcp " , " ports " : [ " 53 " , " 80 " , " 443 " , " 4201 " ] } , # { " IPProtocol " : " icmp " } , # { " IPProtocol " : " udp " , " ports " : [ " 53 " ] } , seen_protos = { } allow_dict = [ ] protocols = all...
def add_query ( self , query , join_with = AND ) : """Join a new query to existing queries on the stack . Args : query ( tuple or list or DomainCondition ) : The condition for the query . If a ` ` DomainCondition ` ` object is not provided , the input should conform to the interface defined in : func : ` ...
if not isinstance ( query , DomainCondition ) : query = DomainCondition . from_tuple ( query ) if len ( self . query ) : self . query . append ( join_with ) self . query . append ( query )
def register_defs ( self , def_list , ** kwargs ) : """Registers a list of Rml defintions objects Args : def _ list : list of objects defining the rml definitons"""
for item in def_list : if isinstance ( item , tuple ) : self . register_rml_def ( * item , ** kwargs ) elif isinstance ( item , dict ) : cp_kwargs = kwargs . copy ( ) item . update ( kwargs ) self . register_rml_def ( ** item )
def get_result ( self , errors = GRACEFUL , ** params ) : """Get all results , no filtering , etc . by creating and polling the session ."""
additional_params = self . get_additional_params ( ** params ) return self . poll_session ( self . create_session ( ** params ) , errors = errors , ** additional_params )
def render ( plain , urlHandler = None , templatePaths = None , options = None , defaultTag = 'div' , wikiStyle = 'basic' ) : """Renders the inputted plain text wiki information into HTML rich text . : param plain | < str > | Include some additional documentation urlHandler | < UlrHandler > | | None : return ...
if not plain : return '' __style = WIKI_STYLES . styles . get ( wikiStyle , WIKI_STYLES . styles [ 'basic' ] ) # process the wiki text with the mako template system if not urlHandler : urlHandler = UrlHandler . current ( ) # render the text out from mako template plain = projex . makotext . render ( plain , opt...
def get_complete_ph_dos ( partial_dos_path , phonopy_yaml_path ) : """Creates a pymatgen CompletePhononDos from a partial _ dos . dat and phonopy . yaml files . The second is produced when generating a Dos and is needed to extract the structure . Args : partial _ dos _ path : path to the partial _ dos . d...
a = np . loadtxt ( partial_dos_path ) . transpose ( ) d = loadfn ( phonopy_yaml_path ) structure = get_structure_from_dict ( d [ 'primitive_cell' ] ) total_dos = PhononDos ( a [ 0 ] , a [ 1 : ] . sum ( axis = 0 ) ) pdoss = { } for site , pdos in zip ( structure , a [ 1 : ] ) : pdoss [ site ] = pdos . tolist ( ) ret...
def repval ( self , limitsok = False ) : """Get a best - effort representative value as a float . This can be DANGEROUS because it discards limit information , which is rarely wise ."""
if not limitsok and self . dkind in ( 'lower' , 'upper' ) : raise LimitError ( ) if self . dkind == 'unif' : lower , upper = map ( float , self . data ) v = 0.5 * ( lower + upper ) elif self . dkind in _noextra_dkinds : v = float ( self . data ) elif self . dkind in _yesextra_dkinds : v = float ( se...
def setup_system ( self , system , name_from_system = '' , ** kwargs ) : """Set system attribute and do some initialization . Used by System ."""
if not self . system : self . system = system name , traits = self . _passed_arguments new_name = self . system . get_unique_name ( self , name , name_from_system ) if not self in self . system . reverse : self . name = new_name self . logger = self . system . logger . getChild ( '%s.%s' % ( self . __class__ . ...
def _Rforce ( self , R , phi = 0. , t = 0. ) : """NAME : _ Rforce PURPOSE : evaluate the radial force for this potential INPUT : R - Galactocentric cylindrical radius phi - azimuth t - time OUTPUT : the radial force HISTORY : 2011-10-19 - Written - Bovy ( IAS )"""
if R < self . _rb : return - self . _p * self . _mphio / self . _m * self . _rb2p / R ** ( self . _p + 1. ) * math . cos ( self . _m * phi - self . _mphib ) else : return - self . _p * self . _mphio / self . _m * R ** ( self . _p - 1. ) * math . cos ( self . _m * phi - self . _mphib )
def _determine_auth_mechanism ( username , password , delegation ) : """if the username contains at ' @ ' sign we will use kerberos if the username contains a ' / we will use ntlm either NTLM or Kerberos . In fact its basically always Negotiate ."""
if re . match ( '(.*)@(.+)' , username ) is not None : if delegation is True : raise Exception ( 'Kerberos is not yet supported, specify the username in <domain>\<username> form for NTLM' ) else : raise Exception ( 'Kerberos is not yet supported, specify the username in <domain>>\<username> form...
def iter_flux_bias ( cur ) : """Iterate over all flux biases in the cache . Args : cur ( : class : ` sqlite3 . Cursor ` ) : An sqlite3 cursor . This function is meant to be run within a : obj : ` with ` statement . Yields : tuple : A 4 - tuple : list : The chain . str : The system name . float : The...
select = """ SELECT nodes, system_name, flux_bias, chain_strength FROM flux_bias_view; """ for nodes , system , flux_bias , chain_strength in cur . execute ( select ) : yield json . loads ( nodes ) , system , _decode_real ( flux_bias ) , _decode_real ( chain_strength )
def _build_word ( syl , vowels ) : """Builds a Pinyin word re pattern from a Pinyin syllable re pattern . A word is defined as a series of consecutive valid Pinyin syllables with optional hyphens and apostrophes interspersed . Hyphens must be followed immediately by another valid Pinyin syllable . Apostrophes...
return "(?:{syl}(?:-(?={syl})|'(?=[{a}{e}{o}])(?={syl}))?)+" . format ( syl = syl , a = vowels [ 'a' ] , e = vowels [ 'e' ] , o = vowels [ 'o' ] )
def breakdown_tt2000 ( tt2000 , to_np = None ) : # @ NoSelf """Breaks down the epoch ( s ) into UTC components . For CDF _ EPOCH : they are 7 date / time components : year , month , day , hour , minute , second , and millisecond For CDF _ EPOCH16: they are 10 date / time components : year , month , day , ...
if ( isinstance ( tt2000 , int ) or isinstance ( tt2000 , np . int64 ) ) : new_tt2000 = [ tt2000 ] elif ( isinstance ( tt2000 , list ) or isinstance ( tt2000 , tuple ) or isinstance ( tt2000 , np . ndarray ) ) : new_tt2000 = tt2000 else : print ( 'Bad input data' ) return None count = len ( new_tt2000 )...
def fix_paths ( self , d , root = None , project = None ) : """Fix the paths in the given dictionary to get absolute paths Parameters % ( ExperimentsConfig . fix _ paths . parameters ) s Returns % ( ExperimentsConfig . fix _ paths . returns ) s Notes d is modified in place !"""
if root is None and project is None : project = d . get ( 'project' ) if project is not None : root = self [ project ] [ 'root' ] else : root = d [ 'root' ] elif root is None : root = self [ project ] [ 'root' ] elif project is None : pass paths = self . paths for key , val in d . it...
def run_process ( analysis , action_name , message = '__nomessagetoken__' ) : """Executes an action in the analysis with the given message . It also handles the start and stop signals in the case that message is a ` dict ` with a key ` ` _ _ process _ id ` ` . : param str action _ name : Name of the action to...
if analysis is None : return # detect process _ id process_id = None if isinstance ( message , dict ) and '__process_id' in message : process_id = message [ '__process_id' ] del message [ '__process_id' ] if process_id : yield analysis . emit ( '__process' , { 'id' : process_id , 'status' : 'start' } ) ...
def save_datasets ( self , datasets , compute = True , ** kwargs ) : """Save all datasets to one or more files . Subclasses can use this method to save all datasets to one single file or optimize the writing of individual datasets . By default this simply calls ` save _ dataset ` for each dataset provided . ...
results = [ ] for ds in datasets : results . append ( self . save_dataset ( ds , compute = False , ** kwargs ) ) if compute : LOG . info ( "Computing and writing results..." ) return compute_writer_results ( [ results ] ) targets , sources , delayeds = split_results ( [ results ] ) if delayeds : # This writ...
def permission_required_raise ( perm , login_url = None , raise_exception = True ) : """A permission _ required decorator that raises by default ."""
return permission_required ( perm , login_url = login_url , raise_exception = raise_exception )
def pop ( self , key ) : """Removes @ key from the instance , returns its value"""
r = self [ key ] self . remove ( key ) return r
def generate_evenly_distributed_data ( dim = 2000 , num_active = 40 , num_samples = 1000 , num_negatives = 500 ) : """Generates a set of data drawn from a uniform distribution . The binning structure from Poirazi & Mel is ignored , and all ( dim choose num _ active ) arrangements are possible . num _ negatives ...
sparse_data = [ numpy . random . choice ( dim , size = num_active , replace = False ) for i in range ( num_samples ) ] data = [ [ 0 for i in range ( dim ) ] for i in range ( num_samples ) ] for datapoint , sparse_datapoint in zip ( data , sparse_data ) : for i in sparse_datapoint : datapoint [ i ] = 1 negat...
def update_compatibility_decorators ( binding , decorators ) : """This optional function is called by Qt . py to modify the decorators applied to QtCompat namespace objects . Arguments : binding ( str ) : The Qt binding being wrapped by Qt . py decorators ( dict ) : Maps specific decorator functions to Qt...
def _widgetDecorator ( some_function ) : def wrapper ( * args , ** kwargs ) : ret = some_function ( * args , ** kwargs ) # Modifies the returned value so we can test that the # decorator works . return "Test: {}" . format ( ret ) # preserve docstring and name of original function...
def last_or_default ( self , default , predicate = None ) : '''The last element ( optionally satisfying a predicate ) or a default . If the predicate is omitted or is None this query returns the last element in the sequence ; otherwise , it returns the last element in the sequence for which the predicate eval...
if self . closed ( ) : raise ValueError ( "Attempt to call last_or_default() on a " "closed Queryable." ) return self . _last_or_default ( default ) if predicate is None else self . _last_or_default_predicate ( default , predicate )
def _minimally_quoted_parameter_value ( value ) : """Per RFC 7321 ( https : / / tools . ietf . org / html / rfc7231 # section - 3.1.1.1 ) : Parameters values don ' t need to be quoted if they are a " token " . Token characters are defined by RFC 7320 ( https : / / tools . ietf . org / html / rfc7230 # section -...
if re . match ( "^[{charset}]*$" . format ( charset = MediaType . RFC7320_TOKEN_CHARSET ) , value ) : return value else : return MediaType . _quote ( value )
def set_level ( cls , level ) : """: raises : ValueError"""
level = ( level if not is_str ( level ) else int ( LOGGING_LEVELS . get ( level . upper ( ) , level ) ) ) for handler in root . handlers : handler . setLevel ( level ) root . setLevel ( level )
def path_for_import ( name ) : """Returns the directory path for the given package or module ."""
return os . path . dirname ( os . path . abspath ( import_module ( name ) . __file__ ) )
def update_detail ( self , request ) : """: param request : an apiv2 request object : return : request if successful with entities set on request"""
entity = request . context_params [ self . detail_property_name ] updated_entity = self . update_entity ( request , entity , ** request . context_params [ 'data' ] ) request . context_params [ self . updated_property_name ] = updated_entity return request
def find_dependencies ( self , dataset_keys , ** dfilter ) : """Create the dependency tree . Args : dataset _ keys ( iterable ) : Strings or DatasetIDs to find dependencies for * * dfilter ( dict ) : Additional filter parameters . See ` satpy . readers . get _ key ` for more details . Returns : ( Node ,...
unknown_datasets = set ( ) for key in dataset_keys . copy ( ) : n , unknowns = self . _find_dependencies ( key , ** dfilter ) dataset_keys . discard ( key ) # remove old non - DatasetID if n is not None : dataset_keys . add ( n . name ) # add equivalent DatasetID if unknowns : ...
def get_context_data ( self , ** kwargs ) : """Add context data to view"""
context = super ( ) . get_context_data ( ** kwargs ) context . update ( { 'title' : self . title , 'submit_value' : self . submit_value , 'cancel_url' : self . get_cancel_url ( ) , 'model_verbose_name' : self . get_model_class ( ) . _meta . verbose_name } ) return context
def close ( self ) : """Closes the record file ."""
if not self . is_open : return super ( MXIndexedRecordIO , self ) . close ( ) self . fidx . close ( )
def mark_entities_to_export ( self , export_config ) : """Apply the specified : class : ` meteorpi _ model . ExportConfiguration ` to the database , running its contained query and creating rows in t _ observationExport or t _ fileExport for matching entities . : param ExportConfiguration export _ config : An...
# Retrieve the internal ID of the export configuration , failing if it hasn ' t been stored self . con . execute ( 'SELECT uid FROM archive_exportConfig WHERE exportConfigID = %s;' , ( export_config . config_id , ) ) export_config_id = self . con . fetchall ( ) if len ( export_config_id ) < 1 : raise ValueError ( "...
def requestTimingInfo ( self ) : """Returns the time needed to process the request by the frontend server in microseconds and the EPOC timestamp of the request in microseconds . : rtype : tuple containing processing time and timestamp"""
try : return tuple ( item . split ( '=' ) [ 1 ] for item in self . http_response . header . get ( 'CMS-Server-Time' ) . split ( ) ) except AttributeError : return None , None
def update_script ( self , information , timeout = - 1 ) : """Updates the configuration script of the logical enclosure and on all enclosures in the logical enclosure with the specified ID . Args : information : Updated script . timeout : Timeout in seconds . Wait for task completion by default . The timeou...
uri = "{}/script" . format ( self . data [ "uri" ] ) return self . _helper . update ( information , uri = uri , timeout = timeout )
def checklist ( self ) : """Run dialog checklist"""
choice = [ ] for item in self . data : choice . append ( ( item , "" , self . status ) ) code , self . tags = self . d . checklist ( text = self . text , height = 20 , width = 65 , list_height = 13 , choices = choice , title = self . title , backtitle = self . backtitle ) if code == "ok" : self . unicode_to_str...
def _post_parse_request ( self , request , client_id = '' , ** kwargs ) : """This is where clients come to refresh their access tokens : param request : The request : param authn : Authentication info , comes from HTTP header : returns :"""
request = RefreshAccessTokenRequest ( ** request . to_dict ( ) ) try : keyjar = self . endpoint_context . keyjar except AttributeError : keyjar = "" request . verify ( keyjar = keyjar , opponent_id = client_id ) if "client_id" not in request : # Optional for refresh access token request request [ "client_id...
def patched_normalizeargs ( sequence , output = None ) : """Normalize declaration arguments Normalization arguments might contain Declarions , tuples , or single interfaces . Anything but individial interfaces or implements specs will be expanded ."""
if output is None : output = [ ] if Broken in getattr ( sequence , '__bases__' , ( ) ) : return [ sequence ] cls = sequence . __class__ if InterfaceClass in cls . __mro__ or zope . interface . declarations . Implements in cls . __mro__ : output . append ( sequence ) else : for v in sequence : pa...
def ftp_listing_paths ( ftpconn : FTP , root : str ) -> Iterable [ str ] : """Generate the full file paths from a root path ."""
for current_path , dirs , files in ftp_walk ( ftpconn , root ) : yield from ( os . path . join ( current_path , file ) for file in files )
def get_domain_home_from_url ( self , url ) : """parse url for domain and homepage : param url : the req url : type url : str : return : ( homepage , domain ) : rtype :"""
p = parse . urlparse ( url ) if p . netloc : self . domain = p . netloc self . homepage = '{}://{}' . format ( p . scheme , p . netloc ) return self . homepage , p . netloc else : return '' , ''
def color_for_thread ( thread_id ) : """Associates the thread ID with the next color in the ` thread _ colors ` cycle , so that thread - specific parts of a log have a consistent separate color ."""
if thread_id not in seen_thread_colors : seen_thread_colors [ thread_id ] = next ( thread_colors ) return seen_thread_colors [ thread_id ]
def immutable_task ( task , state , pre_state , created ) : """Converts to an immutable slots class to handle internally ."""
# noinspection PyUnresolvedReferences , PyProtectedMember return TaskData . _make ( chain ( ( getattr ( task , f ) for f in TASK_OWN_FIELDS ) , ( state , pre_state , created ) , ) )
def page_count ( self ) : """Get count of total pages"""
postcount = self . post_set . count ( ) max_pages = ( postcount / get_paginate_by ( ) ) if postcount % get_paginate_by ( ) != 0 : max_pages += 1 return max_pages
def _setHeaderLabel ( self , col , text ) : """Sets the header of column col to text . Will increase the number of columns if col is larger than the current number ."""
model = self . tree . model ( ) item = model . horizontalHeaderItem ( col ) if item : item . setText ( text ) else : model . setHorizontalHeaderItem ( col , QtGui . QStandardItem ( text ) )
def _on_click ( self , event ) : """Function bound to event of selection in the Combobox , calls callback if callable : param event : Tkinter event"""
if callable ( self . __callback ) : self . __callback ( self . selection )