signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _is_valid_id ( self , inpt ) : """Checks if input is a valid Id"""
from dlkit . abstract_osid . id . primitives import Id as abc_id if isinstance ( inpt , abc_id ) : return True else : return False
def optional ( name , default ) -> 'Wildcard' : """Create a ` Wildcard ` that matches a single argument with a default value . If the wildcard does not match , the substitution will contain the default value instead . Args : name : The name for the wildcard . default : The default value of the wildcar...
return Wildcard ( min_count = 1 , fixed_size = True , variable_name = name , optional = default )
def plot_mv_voltages ( self , ** kwargs ) : """Plots voltages in MV grid on grid topology plot . For more information see : func : ` edisgo . tools . plots . mv _ grid _ topology ` ."""
if self . network . pypsa is not None : try : v_res = self . network . results . v_res ( ) except : logging . warning ( "Voltages `pfa_v_mag_pu` from power flow " "analysis must be available to plot them." ) return plots . mv_grid_topology ( self . network . pypsa , self . network . ...
def cmd_status ( args ) : '''show status'''
if len ( args ) == 0 : mpstate . status . show ( sys . stdout , pattern = None ) else : for pattern in args : mpstate . status . show ( sys . stdout , pattern = pattern )
def create_downsampled_data ( params ) : '''Creates one CSD or LFP file with downsampled data per cell type'''
maxsamples = 1 for data_type in [ 'LFP' , 'CSD' ] : if RANK == 0 : if not os . path . isdir ( os . path . join ( params . savefolder , 'populations' , 'subsamples' ) ) : os . mkdir ( ( os . path . join ( params . savefolder , 'populations' , 'subsamples' ) ) ) COMM . Barrier ( ) try : ...
def plot_depth_descent_ascent ( depths , dive_mask , des , asc ) : '''Plot depth data for whole deployment , descents , and ascents Args depths : ndarray Depth values at each sensor sampling dive _ mask : ndarray Boolean mask slicing dives from the tag data des : ndarray boolean mask for slicing desce...
import numpy from . import plotutils # Indices where depths are descents or ascents des_ind = numpy . where ( dive_mask & des ) [ 0 ] asc_ind = numpy . where ( dive_mask & asc ) [ 0 ] fig , ax1 = plt . subplots ( ) ax1 . title . set_text ( 'Dive descents and ascents' ) ax1 = plotutils . plot_noncontiguous ( ax1 , depth...
def get_user_sets ( client_id , user_id ) : """Find all user sets ."""
data = api_call ( 'get' , 'users/{}/sets' . format ( user_id ) , client_id = client_id ) return [ WordSet . from_dict ( wordset ) for wordset in data ]
def get_sync_info ( self , name , key = None ) : """Get mtime / size when this target ' s current dir was last synchronized with remote ."""
peer_target = self . peer if self . is_local ( ) : info = self . cur_dir_meta . dir [ "peer_sync" ] . get ( peer_target . get_id ( ) ) else : info = peer_target . cur_dir_meta . dir [ "peer_sync" ] . get ( self . get_id ( ) ) if name is not None : info = info . get ( name ) if info else None if info and key...
def parse ( cls , json ) : # type : ( dict ) - > Any """Parse a json dict and return the correct subclass of : class : ` ValidatorEffect ` . It uses the ' effect ' key to determine which : class : ` ValidatorEffect ` to instantiate . Please refer to : class : ` enums . ValidatorEffectTypes ` for the supported e...
effect = json . get ( 'effect' ) if effect : from pykechain . models . validators import effects effect_implementation_classname = effect [ 0 ] . upper ( ) + effect [ 1 : ] if hasattr ( effects , effect_implementation_classname ) : return getattr ( effects , effect_implementation_classname ) ( json ...
def parse_logs ( self , f ) : """Parse a given HiCExplorer log file from hicBuildMatrix ."""
data = { } for l in f . splitlines ( ) : # catch empty lines if len ( l ) == 0 : continue s = l . split ( "\t" ) data_ = [ ] # catch lines with descriptive content : " Of pairs used : " for i in s [ 1 : ] : if len ( i ) == 0 : continue try : i . replac...
def _is_ready ( self ) : """Return True if and only if final result has been received , optionally blocking until this is the case , or the timeout is exceeded . This is a synchronous implementation but an async one can be added by subclassing this . : return : True if ready , False if not"""
while not self . finish_time or time . time ( ) < self . finish_time : result = self . _poll_deferred ( ) if result == 'success' : return True if result == 'failed' : raise couchbase . exceptions . InternalError ( "Failed exception" ) time . sleep ( self . interval ) raise couchbase . ex...
def _query ( _node_id , value = None , ** kw ) : "Look up value by using Query table"
query_result = [ ] try : query_result = db . execute ( text ( fetch_query_string ( 'select_query_from_node.sql' ) ) , ** kw ) . fetchall ( ) except DatabaseError as err : current_app . logger . error ( "DatabaseError: %s, %s" , err , kw ) return value # current _ app . logger . debug ( " queries kw : % s " ...
def camelcase_search_options ( self , options ) : """change all underscored variants back to what the API is expecting"""
new_options = { } for key in options : value = options [ key ] new_key = SEARCH_OPTIONS_DICT . get ( key , key ) if new_key == 'sort' : value = SORT_OPTIONS_DICT . get ( value , value ) elif new_key == 'timePivot' : value = TIME_PIVOT_OPTIONS_DICT . get ( value , value ) elif new_key...
def separable_approx ( h , N = 1 ) : """finds the k - th rank approximation to h , where k = 1 . . N similar to separable _ series Parameters h : ndarray input array ( 2 or 2 dimensional ) N : int order of approximation Returns all N apprxoimations res [ i ] , the i - th approximation"""
if h . ndim == 2 : return _separable_approx2 ( h , N ) elif h . ndim == 3 : return _separable_approx3 ( h , N ) else : raise ValueError ( "unsupported array dimension: %s (only 2d or 3d) " % h . ndim )
def openbin ( self , path , mode = 'r' , buffering = - 1 , ** options ) : # noqa : D102 """Open a binary file - like object . Arguments : path ( str ) : A path on the filesystem . mode ( str ) : Mode to open the file ( must be a valid , non - text mode ) . Since this method only opens binary files , the ` `...
self . check ( ) _path = self . validatepath ( path ) _mode = Mode ( mode ) _mode . validate_bin ( ) with self . _lock : if _mode . exclusive : if self . exists ( _path ) : raise errors . FileExists ( path ) else : _mode = Mode ( '' . join ( set ( mode . replace ( 'x' , 'w' )...
def loadd ( self , ava , base64encode = False ) : """Sets attributes , children , extension elements and extension attributes of this element instance depending on what is in the given dictionary . If there are already values on properties those will be overwritten . If the keys in the dictionary does not c...
for prop , _typ , _req in self . c_attributes . values ( ) : if prop in ava : value = ava [ prop ] if isinstance ( value , ( bool , int ) ) : setattr ( self , prop , str ( value ) ) else : setattr ( self , prop , value ) if "text" in ava : self . set_text ( ava [ ...
def standardize_mapping ( into ) : """Helper function to standardize a supplied mapping . . . versionadded : : 0.21.0 Parameters into : instance or subclass of collections . abc . Mapping Must be a class , an initialized collections . defaultdict , or an instance of a collections . abc . Mapping subclass ...
if not inspect . isclass ( into ) : if isinstance ( into , collections . defaultdict ) : return partial ( collections . defaultdict , into . default_factory ) into = type ( into ) if not issubclass ( into , abc . Mapping ) : raise TypeError ( 'unsupported type: {into}' . format ( into = into ) ) eli...
def add ( self , obj = None , filename = None , data = None , info = { } , html = None ) : "Similar to FileArchive . add but accepts html strings for substitution"
initial_last_key = list ( self . _files . keys ( ) ) [ - 1 ] if len ( self ) else None if self . _auto : exporters = self . exporters [ : ] # Can only associate html for one exporter at a time for exporter in exporters : self . exporters = [ exporter ] super ( NotebookArchive , self ) . add ...
def children_as_pi ( self , squash = False ) : """Returns the child visit counts as a probability distribution , pi If squash is true , exponentiate the probabilities by a temperature slightly larger than unity to encourage diversity in early play and hopefully to move away from 3-3s"""
probs = self . child_N if squash : probs = probs ** .98 sum_probs = np . sum ( probs ) if sum_probs == 0 : return probs return probs / np . sum ( probs )
def info ( self ) : """Return information of chord to display"""
return """{} root={} quality={} appended={} on={}""" . format ( self . _chord , self . _root , self . _quality , self . _appended , self . _on )
def bolditalic ( name , rawtext , text , lineno , inliner , options = { } , content = [ ] ) : """Add bolditalic role . Returns 2 part tuple containing list of nodes to insert into the document and a list of system messages . Both are allowed to be empty . : param name : The role name used in the document . ...
node = nodes . inline ( rawtext , text ) node . set_class ( 'bolditalic' ) return [ node ] , [ ]
def remove_html_tag ( input_str = '' , tag = None ) : """Returns a string with the html tag and all its contents from a string"""
result = input_str if tag is not None : pattern = re . compile ( '<{tag}[\s\S]+?/{tag}>' . format ( tag = tag ) ) result = re . sub ( pattern , '' , str ( input_str ) ) return result
def ssim ( test , ref , mask = None ) : """Structural Similarity ( SSIM ) Calculate the SSIM between a test image and a reference image . Parameters ref : np . ndarray the reference image test : np . ndarray the tested image mask : np . ndarray , optional the mask for the ROI Notes Compute the m...
if not import_skimage : # pragma : no cover raise ImportError ( 'Scikit-Image package not found' ) test , ref , mask = _preprocess_input ( test , ref , mask ) assim , ssim = compare_ssim ( test , ref , full = True ) if mask is None : return assim else : return ( mask * ssim ) . sum ( ) / mask . sum ( )
def getArrays ( self , attr = None , specfiles = None , sort = False , reverse = False , selector = None , defaultValue = None ) : """Return a condensed array of data selected from : class : ` Fi ` instances from ` ` self . container ` ` for fast and convenient data processing . : param attr : list of : class :...
selector = ( lambda fi : fi . isValid ) if selector is None else selector attr = attr if attr is not None else [ ] attr = set ( [ 'id' , 'specfile' ] + aux . toList ( attr ) ) items = self . getItems ( specfiles , sort , reverse , selector ) return _getArrays ( items , attr , defaultValue )
def expectation_sensitivity ( T , a ) : r"""Sensitivity of expectation value of observable A = ( a _ i ) . Parameters T : ( M , M ) ndarray Transition matrix a : ( M , ) ndarray Observable , a [ i ] is the value of the observable at state i . Returns S : ( M , M ) ndarray Sensitivity matrix of the e...
# check input T = _types . ensure_ndarray_or_sparse ( T , ndim = 2 , uniform = True , kind = 'numeric' ) a = _types . ensure_float_vector ( a , require_order = True ) # go if _issparse ( T ) : _showSparseConversionWarning ( ) return dense . sensitivity . expectation_sensitivity ( T . toarray ( ) , a ) else : ...
def create_absolute_values_structure ( layer , fields ) : """Helper function to create the structure for absolute values . : param layer : The vector layer . : type layer : QgsVectorLayer : param fields : List of name field on which we want to aggregate . : type fields : list : return : The data structure...
# Let ' s create a structure like : # key is the index of the field : ( flat table , definition name ) source_fields = layer . keywords [ 'inasafe_fields' ] absolute_fields = [ field [ 'key' ] for field in count_fields ] summaries = { } for field in source_fields : if field in absolute_fields : field_name =...
def __get_nondirect_init ( self , init ) : """return the non - direct init if the direct algorithm has been selected ."""
crc = init for i in range ( self . Width ) : bit = crc & 0x01 if bit : crc ^= self . Poly crc >>= 1 if bit : crc |= self . MSB_Mask return crc & self . Mask
def store_meta_data ( self , copy_path = None ) : """Save meta data of state model to the file system This method generates a dictionary of the meta data of the state together with the meta data of all state elements ( data ports , outcomes , etc . ) and stores it on the filesystem . Secure that the store met...
if copy_path : meta_file_path_json = os . path . join ( copy_path , self . state . get_storage_path ( ) , storage . FILE_NAME_META_DATA ) else : if self . state . file_system_path is None : logger . error ( "Meta data of {0} can be stored temporary arbitrary but by default first after the " "respective ...
def try_one_generator_really ( project , name , generator , target_type , properties , sources ) : """Returns usage requirements + list of created targets ."""
if __debug__ : from . targets import ProjectTarget assert isinstance ( project , ProjectTarget ) assert isinstance ( name , basestring ) or name is None assert isinstance ( generator , Generator ) assert isinstance ( target_type , basestring ) assert isinstance ( properties , property_set . Prop...
def launchApplication ( self , pchAppKey ) : """Launches the application . The existing scene application will exit and then the new application will start . This call is not valid for dashboard overlay applications ."""
fn = self . function_table . launchApplication result = fn ( pchAppKey ) return result
def disconnect ( self , listener , pass_signal = False ) : """Disconnect an existing listener from this signal : param listener : The listener ( callable ) to remove : param pass _ signal : An optional argument that controls if the signal object is explicitly passed to this listener when it is being fired...
info = listenerinfo ( listener , pass_signal ) self . _listeners . remove ( info ) _logger . debug ( "disconnect %r from %r" , str ( listener ) , self . _name ) if inspect . ismethod ( listener ) : listener_object = listener . __self__ if hasattr ( listener_object , "__listeners__" ) : listener_object ....
def to_json ( self ) : """Converts given document to JSON dict ."""
json_data = dict ( ) for field_name , field_obj in self . _fields . items ( ) : if isinstance ( field_obj , NestedDocumentField ) : nested_document = field_obj . __get__ ( self , self . __class__ ) value = None if nested_document is None else nested_document . to_json ( ) elif isinstance ( field...
def next_listing ( self , limit = None ) : """GETs next : class : ` Listing ` directed to by this : class : ` Listing ` . Returns : class : ` Listing ` object . : param limit : max number of entries to get : raise UnsupportedError : raised when trying to load more comments"""
if self . after : return self . _reddit . _limit_get ( self . _path , params = { 'after' : self . after } , limit = limit or self . _limit ) elif self . _has_literally_more : more = self [ - 1 ] data = dict ( link_id = self [ 0 ] . parent_id , id = more . name , children = ',' . join ( more . children ) ) ...
def _fix_history_sequence ( self , df , table ) : """fix out - of - sequence ticks / bars"""
# remove " Unnamed : x " columns cols = df . columns [ df . columns . str . startswith ( 'Unnamed:' ) ] . tolist ( ) df . drop ( cols , axis = 1 , inplace = True ) # remove future dates df [ 'datetime' ] = pd . to_datetime ( df [ 'datetime' ] , utc = True ) blacklist = df [ df [ 'datetime' ] > pd . to_datetime ( 'now' ...
def doEpisodes ( self , number = 1 ) : """Does the the given number of episodes ."""
env = self . task . env self . Pg = zeros ( ( len ( env . case . online_generators ) , len ( env . profile ) ) ) rewards = super ( OPFExperiment , self ) . doEpisodes ( number ) # Average the set - points for each period . self . Pg = self . Pg / number return rewards
def find_parent_id_for_component ( self , component_id ) : """Given the URL to a component , returns the parent component ' s URL . : param string component _ id : The URL of the component . : return : A tuple containing : * The type of the parent record ; valid values are ArchivesSpaceClient . RESOURCE and A...
response = self . get_record ( component_id ) if "parent" in response : return ( ArchivesSpaceClient . RESOURCE_COMPONENT , response [ "parent" ] [ "ref" ] ) # if this is the top archival object , return the resource instead elif "resource" in response : return ( ArchivesSpaceClient . RESOURCE , response [ "res...
def usnjrnl_timeline ( self ) : """Iterates over the changes occurred within the filesystem . Yields UsnJrnlEvent namedtuples containing : file _ reference _ number : known in Unix FS as inode . path : full path of the file . size : size of the file in bytes if recoverable . allocated : whether the file e...
filesystem_content = defaultdict ( list ) self . logger . debug ( "Extracting Update Sequence Number journal." ) journal = self . _read_journal ( ) for dirent in self . _visit_filesystem ( ) : filesystem_content [ dirent . inode ] . append ( dirent ) self . logger . debug ( "Generating timeline." ) yield from gener...
def parse_parameter_group ( self , global_params , region , parameter_group ) : """Parse a single Redshift parameter group and fetch all of its parameters : param global _ params : Parameters shared for all regions : param region : Name of the AWS region : param parameter _ group : Parameter group"""
pg_name = parameter_group . pop ( 'ParameterGroupName' ) pg_id = self . get_non_aws_id ( pg_name ) # Name could be used as only letters digits or hyphens parameter_group [ 'name' ] = pg_name parameter_group [ 'parameters' ] = { } api_client = api_clients [ region ] parameters = handle_truncated_response ( api_client . ...
def auto_consume ( func ) : """Decorator for auto consuming lines when leaving the function"""
def inner ( * args , ** kwargs ) : func ( * args , ** kwargs ) args [ 0 ] . consume_line ( ) return inner
def cli ( # pylint : disable = too - many - arguments ctx , target , config , c , commits , extra_path , ignore , msg_filename , verbose , silent , debug , ) : """Git lint tool , checks your git commit messages for styling issues"""
try : if debug : logging . getLogger ( "gitlint" ) . setLevel ( logging . DEBUG ) log_system_info ( ) # Get the lint config from the commandline parameters and # store it in the context ( click allows storing an arbitrary object in ctx . obj ) . config , config_builder = build_config ( ctx ,...
def phonetic_i_umlaut ( sound : Vowel ) -> Vowel : """> > > umlaut _ a = OldNorsePhonology . phonetic _ i _ umlaut ( a ) > > > umlaut _ a . ipar > > > umlaut _ au = OldNorsePhonology . phonetic _ i _ umlaut ( DIPHTHONGS _ IPA _ class [ " au " ] ) > > > umlaut _ au . ipar ' ɐy ' : param sound : : return ...
if sound . is_equal ( a ) : return ee elif sound . is_equal ( a . lengthen ( ) ) : return ee . lengthen ( ) elif sound . is_equal ( o ) : return oee elif sound . is_equal ( o . lengthen ( ) ) : return oee . lengthen ( ) elif sound . is_equal ( u ) : return y elif sound . is_equal ( u . lengthen ( ) ...
def filter_wildcard ( names , pattern ) : """Return a tuple of strings that match a shell - style wildcard pattern ."""
return tuple ( name for name in names if fnmatch . fnmatch ( name , pattern ) )
def get_version ( self ) : """This gets the version of OpenALPR : return : Version information"""
ptr = self . _get_version_func ( self . alpr_pointer ) version_number = ctypes . cast ( ptr , ctypes . c_char_p ) . value version_number = _convert_from_charp ( version_number ) self . _free_json_mem_func ( ctypes . c_void_p ( ptr ) ) return version_number
def encodeMotorInput ( self , motorInput ) : """Encode motor command to bit vector . @ param motorInput ( 1D numpy . array ) Motor command to be encoded . @ return ( 1D numpy . array ) Encoded motor command ."""
if not hasattr ( motorInput , "__iter__" ) : motorInput = list ( [ motorInput ] ) return self . motorEncoder . encode ( motorInput )
def iterqueue ( queue , expected ) : """Iterate all value from the queue until the ` ` expected ` ` number of EXIT elements is received"""
while expected > 0 : for item in iter ( queue . get , EXIT ) : yield item expected -= 1
def get_video_transcript_storage ( ) : """Return the configured django storage backend for video transcripts ."""
if hasattr ( settings , 'VIDEO_TRANSCRIPTS_SETTINGS' ) : return get_storage_class ( settings . VIDEO_TRANSCRIPTS_SETTINGS . get ( 'STORAGE_CLASS' ) , ) ( ** settings . VIDEO_TRANSCRIPTS_SETTINGS . get ( 'STORAGE_KWARGS' , { } ) ) else : # during edx - platform loading this method gets called but settings are not re...
def contact_number ( self ) : """This method returns the contact phone number . : return :"""
try : number = self . _ad_page_content . find ( 'button' , { 'class' : 'phone-number' } ) return ( base64 . b64decode ( number . attrs [ 'data-p' ] ) ) . decode ( 'ascii' ) except Exception as e : if self . _debug : logging . error ( "Error getting contact_number. Error message: " + e . args [ 0 ] )...
def run_analysis ( self , argv ) : """Run this analysis"""
args = self . _parser . parse_args ( argv ) # Read the input maps ccube_dirty = HpxMap . create_from_fits ( args . ccube_dirty , hdu = 'SKYMAP' ) bexpcube_dirty = HpxMap . create_from_fits ( args . bexpcube_dirty , hdu = 'HPXEXPOSURES' ) ccube_clean = HpxMap . create_from_fits ( args . ccube_clean , hdu = 'SKYMAP' ) be...
def on_put ( self , req , resp , handler = None , ** kwargs ) : """Respond on PUT HTTP request assuming resource update flow . This request handler assumes that PUT requests are associated with resource update / modification . Thus default flow for such requests is : * Modify existing resource instance and pr...
self . handle ( handler or self . update , req , resp , ** kwargs ) resp . status = falcon . HTTP_ACCEPTED
def get_user_ip ( request ) : """Return user ip : param request : Django request object : return : user ip"""
ip = get_real_ip ( request ) if ip is None : ip = get_ip ( request ) if ip is None : ip = '127.0.0.1' return ip
def _siren_settings ( setting , value , validate_value ) : """Will validate siren settings and values , returns data packet ."""
if validate_value : if value not in CONST . SETTING_DISABLE_ENABLE : raise AbodeException ( ERROR . INVALID_SETTING_VALUE , CONST . SETTING_DISABLE_ENABLE ) return { 'action' : setting , 'option' : value }
def save_feedback ( rdict ) : """Save feedback file"""
# Check for output folder if not os . path . exists ( _feedback_dir ) : os . makedirs ( _feedback_dir ) jcont = json . dumps ( rdict ) f = open ( _feedback_file , 'w' ) f . write ( jcont ) f . close ( )
def convert_from ( self , base ) : """Convert a BOOST _ METAPARSE _ STRING mode document into one with this mode"""
if self . identifier == 'bmp' : return base elif self . identifier == 'man' : result = [ ] prefix = 'BOOST_METAPARSE_STRING("' while True : bmp_at = base . find ( prefix ) if bmp_at == - 1 : return '' . join ( result ) + base else : result . append ( base ...
def has_flag ( compiler , flagname ) : """Return a boolean indicating whether a flag name is supported on the specified compiler ."""
with tempfile . NamedTemporaryFile ( "w" , suffix = ".cpp" ) as f : f . write ( "int main (int argc, char **argv) { return 0; }" ) try : compiler . compile ( [ f . name ] , extra_postargs = [ flagname ] ) except setuptools . distutils . errors . CompileError : return False return True
def delete_user_by_email ( self , email ) : """This call will delete a user from the Iterable database . This call requires a path parameter to be passed in , ' email ' in this case , which is why we ' re just adding this to the ' call ' argument that goes into the ' api _ call ' request ."""
call = "/api/users/" + str ( email ) return self . api_call ( call = call , method = "DELETE" )
def request ( self , url , method , body = None , headers = None , ** kwargs ) : """Request without authentication ."""
content_type = kwargs . pop ( 'content_type' , None ) or 'application/json' headers = headers or { } headers . setdefault ( 'Accept' , content_type ) if body : headers . setdefault ( 'Content-Type' , content_type ) headers [ 'User-Agent' ] = self . USER_AGENT resp = requests . request ( method , url , data = body ,...
def vphi ( self , * args , ** kwargs ) : """NAME : vphi PURPOSE : return angular velocity INPUT : t - ( optional ) time at which to get the angular velocity vo = ( Object - wide default ) physical scale for velocities to use to convert use _ physical = use to override Object - wide default for using a...
thiso = self ( * args , ** kwargs ) if not len ( thiso . shape ) == 2 : thiso = thiso . reshape ( ( thiso . shape [ 0 ] , 1 ) ) return thiso [ 2 , : ] / thiso [ 0 , : ]
def uncheckButton ( self ) : """Removes the checked stated of all buttons in this widget . This method is also a slot ."""
# for button in self . buttons [ 1 : ] : for button in self . buttons : # supress editButtons toggled event button . blockSignals ( True ) if button . isChecked ( ) : button . setChecked ( False ) button . blockSignals ( False )
def make_colormap ( seq ) : """Return a LinearSegmentedColormap seq : a sequence of floats and RGB - tuples . The floats should be increasing and in the interval ( 0,1 ) ."""
seq = [ ( None , ) * 3 , 0.0 ] + list ( seq ) + [ 1.0 , ( None , ) * 3 ] cdict = { 'red' : [ ] , 'green' : [ ] , 'blue' : [ ] } for i , item in enumerate ( seq ) : if isinstance ( item , float ) : r1 , g1 , b1 = seq [ i - 1 ] r2 , g2 , b2 = seq [ i + 1 ] cdict [ 'red' ] . append ( [ item , r...
def initStats ( self , extras = None ) : """Query and parse Web Server Status Page . @ param extras : Include extra metrics , which can be computationally more expensive ."""
if extras is not None : self . _extras = extras if self . _extras : detail = 1 else : detail = 0 url = "%s://%s:%d/%s?detail=%s" % ( self . _proto , self . _host , self . _port , self . _monpath , detail ) response = util . get_url ( url , self . _user , self . _password ) self . _statusDict = { } for line ...
def to_dictionary ( self ) : """Serialize an object into dictionary form . Useful if you have to serialize an array of objects into JSON . Otherwise , if you call the : meth : ` to _ json ` method on each object in the list and then try to dump the array , you end up with an array with one string ."""
j = { } j [ 'interval' ] = { 'start' : self . start . isoformat ( ) , 'end' : self . end . isoformat ( ) } j [ 'found' ] = { 'v' : self . v , 't' : self . t . isoformat ( ) } return j
def get_json_results ( self , response ) : '''Parses the request result and returns the JSON object . Handles all errors .'''
try : # return the proper JSON object , or error code if request didn ' t go through . self . most_recent_json = response . json ( ) json_results = response . json ( ) if response . status_code in [ 401 , 403 ] : # 401 is invalid key , 403 is out of monthly quota . raise PyMsCognitiveWebSearchExcept...
def route_get ( name , route_table , resource_group , ** kwargs ) : '''. . versionadded : : 2019.2.0 Get details about a specific route . : param name : The route to query . : param route _ table : The route table containing the route . : param resource _ group : The resource group name assigned to the ro...
result = { } netconn = __utils__ [ 'azurearm.get_client' ] ( 'network' , ** kwargs ) try : route = netconn . routes . get ( resource_group_name = resource_group , route_table_name = route_table , route_name = name ) result = route . as_dict ( ) except CloudError as exc : __utils__ [ 'azurearm.log_cloud_erro...
def queue_resize ( self ) : """request the element to re - check it ' s child sprite sizes"""
self . _children_resize_queued = True parent = getattr ( self , "parent" , None ) if parent and isinstance ( parent , graphics . Sprite ) and hasattr ( parent , "queue_resize" ) : parent . queue_resize ( )
def from_etree ( cls , etree_element ) : """creates a ` ` SaltLabel ` ` from an etree element representing a label element in a SaltXMI file . A label element in SaltXMI looks like this : : < labels xsi : type = " saltCore : SFeature " namespace = " salt " name = " SNAME " value = " ACED0005740007735370616E...
return cls ( name = etree_element . attrib [ 'name' ] , value = etree_element . attrib [ 'valueString' ] , xsi_type = get_xsi_type ( etree_element ) , namespace = etree_element . attrib . get ( 'namespace' ) , hexvalue = etree_element . attrib [ 'value' ] )
def ngayThangNamCanChi ( nn , tt , nnnn , duongLich = True , timeZone = 7 ) : """chuyển đổi năm , tháng âm / dương lịch sang Can , Chi trong tiếng Việt . Không tính đến can ngày vì phải chuyển đổi qua lịch Julius . Hàm tìm can ngày là hàm canChiNgay ( nn , tt , nnnn , duongLich = ...
if duongLich is True : [ nn , tt , nnnn , thangNhuan ] = ngayThangNam ( nn , tt , nnnn , timeZone = timeZone ) # Can của tháng canThang = ( nnnn * 12 + tt + 3 ) % 10 + 1 # Can chi của năm canNamSinh = ( nnnn + 6 ) % 10 + 1 chiNam = ( nnnn + 8 ) % 12 + 1 return [ canThang , canNamSinh , chiNam ]
def write_field_repr ( self , name , out , visited ) : '''Extract the PyObject * field named " name " , and write its representation to file - like object " out "'''
field_obj = self . pyop_field ( name ) field_obj . write_repr ( out , visited )
def set_synchronous_standby ( self , name ) : """Sets a node to be synchronous standby and if changed does a reload for PostgreSQL ."""
if name and name != '*' : name = quote_ident ( name ) if name != self . _synchronous_standby_names : if name is None : self . _server_parameters . pop ( 'synchronous_standby_names' , None ) else : self . _server_parameters [ 'synchronous_standby_names' ] = name self . _synchronous_standb...
def dict2row ( d , model , rel = None , exclude = None , exclude_pk = None , exclude_underscore = None , only = None , fk_suffix = None ) : """Recursively walk dict attributes to serialize ones into a row . : param d : dict that represent a serialized row : param model : class nested from the declarative base c...
if not isinstance ( d , dict ) : raise TypeError ( 'Source must be instance of dict, got %s instead' % type ( d ) . __name__ ) row = model ( ) mapper = get_mapper ( row ) if rel is None : rel = getattr ( row , ATTR_REL , DEFAULT_REL ) if exclude is None : exclude = getattr ( row , ATTR_EXCLUDE , DEFAULT_EXC...
def nankurt ( values , axis = None , skipna = True , mask = None ) : """Compute the sample excess kurtosis The statistic computed here is the adjusted Fisher - Pearson standardized moment coefficient G2 , computed directly from the second and fourth central moment . Parameters values : ndarray axis : in...
values = com . values_from_object ( values ) if mask is None : mask = isna ( values ) if not is_float_dtype ( values . dtype ) : values = values . astype ( 'f8' ) count = _get_counts ( mask , axis ) else : count = _get_counts ( mask , axis , dtype = values . dtype ) if skipna : values = values . cop...
def cancel ( self , consumer_tag ) : """Cancel a channel by consumer tag ."""
if not self . channel . conn : return self . channel . basic_cancel ( consumer_tag )
def get_composition_form ( self , * args , ** kwargs ) : """Pass through to provider CompositionAdminSession . get _ composition _ form _ for _ update"""
# Implemented from kitosid template for - # osid . resource . ResourceAdminSession . get _ resource _ form _ for _ update # This method might be a bit sketchy . Time will tell . if isinstance ( args [ - 1 ] , list ) or 'composition_record_types' in kwargs : return self . get_composition_form_for_create ( * args , *...
def prioritize ( self , item , force = False ) : """Moves the item to the very left of the queue ."""
with self . condition : # If the job is already running ( or about to be forced ) , # there is nothing to be done . if item in self . working or item in self . force : return self . queue . remove ( item ) if force : self . force . append ( item ) else : self . queue . appendleft...
def overplot_boundaries_from_params ( ax , params , parmodel , list_islitlet , list_csu_bar_slit_center , micolors = ( 'm' , 'c' ) , linetype = '--' , labels = True , alpha_fill = None , global_offset_x_pix = 0 , global_offset_y_pix = 0 ) : """Overplot boundaries computed from fitted parameters . Parameters ax ...
# duplicate to shorten the variable names xoff = float ( global_offset_x_pix ) yoff = float ( global_offset_y_pix ) list_pol_lower_boundaries = [ ] list_pol_upper_boundaries = [ ] for islitlet , csu_bar_slit_center in zip ( list_islitlet , list_csu_bar_slit_center ) : tmpcolor = micolors [ islitlet % 2 ] pol_lo...
def resizeEvent ( self , event ) : """Resizes the details box if present ( i . e . when ' Show Details ' button was clicked )"""
result = super ( ResizeDetailsMessageBox , self ) . resizeEvent ( event ) details_box = self . findChild ( QtWidgets . QTextEdit ) if details_box is not None : # details _ box . setFixedSize ( details _ box . sizeHint ( ) ) details_box . setFixedSize ( QtCore . QSize ( self . detailsBoxWidth , self . detailBoxHeigh...
def zip_dir ( path , zip_handler , include_dir = True , use_arc_name = False ) : """zip all files and items in dir : param only _ init : : param path : : param zip _ handler : zip file handler : param boolean include _ dir : specify if we want the archive with or without the directory"""
for root , dirs , files in os . walk ( path ) : for file_to_zip in files : filename = os . path . join ( root , file_to_zip ) zip_con = filename . replace ( '\\' , '/' ) if zip_con in zip_handler . namelist ( ) : continue add_file ( filename , zip_handler , include_dir , ...
def _SetExtractionParsersAndPlugins ( self , configuration , session ) : """Sets the parsers and plugins before extraction . Args : configuration ( ProcessingConfiguration ) : processing configuration . session ( Session ) : session ."""
names_generator = parsers_manager . ParsersManager . GetParserAndPluginNames ( parser_filter_expression = configuration . parser_filter_expression ) session . enabled_parser_names = list ( names_generator ) session . parser_filter_expression = configuration . parser_filter_expression
def assign_objective_requisite ( self , objective_id , requisite_objective_id ) : """Creates a requirement dependency between two ` ` Objectives ` ` . arg : objective _ id ( osid . id . Id ) : the ` ` Id ` ` of the dependent ` ` Objective ` ` arg : requisite _ objective _ id ( osid . id . Id ) : the ` ` Id ` ...
requisite_type = Type ( ** Relationship ( ) . get_type_data ( 'OBJECTIVE.REQUISITE' ) ) ras = self . _get_provider_manager ( 'RELATIONSHIP' ) . get_relationship_admin_session_for_family ( self . get_objective_bank_id ( ) , proxy = self . _proxy ) rfc = ras . get_relationship_form_for_create ( objective_id , requisite_o...
def chmod ( path , mode ) : """change pernmissions of path"""
import os , stat st = os . stat ( path ) return os . chmod ( path , mode )
def _update_record ( self , identifier = None , rtype = None , name = None , content = None ) : # pylint : disable = too - many - locals , too - many - branches """Connects to Hetzner account , changes an existing record and returns a boolean , if update was successful or not . Needed identifier or rtype & name t...
with self . _session ( self . domain , self . domain_id ) as ddata : # Validate method parameters if identifier : dtype , dname , dcontent = self . _parse_identifier ( identifier , ddata [ 'zone' ] [ 'data' ] ) if dtype and dname and dcontent : rtype = rtype if rtype else dtype ...
def parse_markdown ( self , attr_string ) : """Read markdown attributes ."""
attr_string = attr_string . strip ( '{}' ) splitter = re . compile ( self . split_regex ( separator = self . spnl ) ) attrs = splitter . split ( attr_string ) [ 1 : : 2 ] # match single word attributes e . g . ` ` ` python if len ( attrs ) == 1 and not attr_string . startswith ( ( '#' , '.' ) ) and '=' not in attr_stri...
def addEmptyTab ( self , text = '' ) : """Add a new DEFAULT _ TAB _ WIDGET , open editor to set text if no text is given"""
tab = self . defaultTabWidget ( ) c = self . count ( ) self . addTab ( tab , text ) self . setCurrentIndex ( c ) if not text : self . tabBar ( ) . editTab ( c ) self . sigTabAdded . emit ( tab ) return tab
def RemoveClientLabels ( self , client_id , owner , labels ) : """Removes a list of user labels from a given client ."""
labelset = self . labels . setdefault ( client_id , { } ) . setdefault ( owner , set ( ) ) for l in labels : labelset . discard ( utils . SmartUnicode ( l ) )
def _get_credentials ( self ) : # type : ( ) - > Optional [ Tuple [ str , str ] ] """Return HDX site username and password Returns : Optional [ Tuple [ str , str ] ] : HDX site username and password or None"""
site = self . data [ self . hdx_site ] username = site . get ( 'username' ) if username : return b64decode ( username ) . decode ( 'utf-8' ) , b64decode ( site [ 'password' ] ) . decode ( 'utf-8' ) else : return None
def artist_create ( self , name , urls = None , alias = None , group = None ) : """Function to create an artist ( Requires login ) ( UNTESTED ) . Parameters : name ( str ) : The artist ' s name . urls ( str ) : A list of URLs associated with the artist , whitespace delimited . alias ( str ) : The artist t...
params = { 'artist[name]' : name , 'artist[urls]' : urls , 'artist[alias]' : alias , 'artist[group]' : group } return self . _get ( 'artist/create' , params , method = 'POST' )
def task_absent ( name ) : '''Ensure that a task is absent from Kapacitor . name Name of the task .'''
ret = { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : '' } task = __salt__ [ 'kapacitor.get_task' ] ( name ) if task : if __opts__ [ 'test' ] : ret [ 'result' ] = None ret [ 'comment' ] = 'Task would have been deleted' else : result = __salt__ [ 'kapacitor.delete_task' ...
def count_inner_triangles ( total_size , inner_size ) : """This function computes the maximum number of equilateral triangles that can be formed inside a larger equilateral triangle . Examples : count _ inner _ triangles ( 4 , 2 ) - > 7 count _ inner _ triangles ( 4 , 3 ) - > 3 count _ inner _ triangles ( 1...
if total_size < inner_size : return - 1 count_upper = 0 count_upper = ( ( total_size - inner_size + 1 ) * ( total_size - inner_size + 2 ) ) // 2 count_lower = 0 count_lower = ( ( total_size - 2 * inner_size + 1 ) * ( total_size - 2 * inner_size + 2 ) ) // 2 return count_upper + count_lower
def invoices ( self , ** params ) : """Return a deferred ."""
params [ 'customer' ] = self . id return Invoice . all ( self . api_key , ** params )
def _reorient_3d ( image ) : """Reorganize the data for a 3d nifti"""
# Create empty array where x , y , z correspond to LR ( sagittal ) , PA ( coronal ) , IS ( axial ) directions and the size # of the array in each direction is the same with the corresponding direction of the input image . new_image = numpy . zeros ( [ image . dimensions [ image . sagittal_orientation . normal_component...
def add_optional_arg_param ( self , param_name , layer_index , blob_index ) : """Add an arg param . If there is no such param in . caffemodel fie , silently ignore it ."""
blobs = self . layers [ layer_index ] . blobs if blob_index < len ( blobs ) : self . add_arg_param ( param_name , layer_index , blob_index )
def add ( self , obj ) : """Adds a member to the collection . : param obj : Object to add . Example : > > > mycollection . add ( pump . Person ( ' bob @ example . org ' ) )"""
activity = { "verb" : "add" , "object" : { "objectType" : obj . object_type , "id" : obj . id } , "target" : { "objectType" : self . object_type , "id" : self . id } } self . _post_activity ( activity ) # Remove the cash so it ' s re - generated next time it ' s needed self . _members = None
def insert_constant ( self , cname , ctype ) : """Inserts a constant ( or returns index if the constant already exists ) Additionally , checks for range ."""
index = self . lookup_symbol ( cname , stype = ctype ) if index == None : num = int ( cname ) if ctype == SharedData . TYPES . INT : if ( num < SharedData . MIN_INT ) or ( num > SharedData . MAX_INT ) : raise SemanticException ( "Integer constant '%s' out of range" % cname ) elif ctype =...
def _load_version1 ( self , filename ) : """load a version 1 pest control file information Parameters filename : str pst filename Raises lots of exceptions for incorrect format"""
f = open ( filename , 'r' ) f . readline ( ) # control section line = f . readline ( ) assert "* control data" in line , "Pst.load() error: looking for control" + " data section, found:" + line iskeyword = False if "keyword" in line . lower ( ) : iskeyword = True control_lines = [ ] while True : line = f . read...
def get_num_part_files ( ) : """Get the number of PART . html files currently saved to disk ."""
num_parts = 0 for filename in os . listdir ( os . getcwd ( ) ) : if filename . startswith ( 'PART' ) and filename . endswith ( '.html' ) : num_parts += 1 return num_parts
def count ( self , cls , filters , quick = True , sort_by = None , select = None ) : """Get the number of results that would be returned in this query"""
query = "select count(*) from `%s` %s" % ( self . domain . name , self . _build_filter_part ( cls , filters , sort_by , select ) ) count = 0 for row in self . domain . select ( query ) : count += int ( row [ 'Count' ] ) if quick : return count return count
async def register ( self , request ) : """Registers the user ."""
session = await get_session ( request ) user_id = session . get ( 'user_id' ) if user_id : return redirect ( request , 'timeline' ) error = None form = None if request . method == 'POST' : form = await request . post ( ) user_id = await db . get_user_id ( self . mongo . user , form [ 'username' ] ) if n...
def get_mem_usage ( ** kwargs ) : """Calculates memory statistics from mapd _ server _ client . get _ memory call Kwargs : con ( class ' pymapd . connection . Connection ' ) : Mapd connection mem _ type ( str ) : [ gpu , cpu ] Type of memory to gather metrics for Returns : ramusage ( dict ) : : : usedra...
try : con_mem_data_list = con . _client . get_memory ( session = kwargs [ "con" ] . _session , memory_level = kwargs [ "mem_type" ] ) usedram = 0 freeram = 0 for con_mem_data in con_mem_data_list : page_size = con_mem_data . page_size node_memory_data_list = con_mem_data . node_memory_da...
def _set_name_server ( self , v , load = False ) : """Setter method for name _ server , mapped from YANG variable / ip / dns / name _ server ( list ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ name _ server is considered as a private method . Backends looking to ...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = YANGListType ( "name_server_ip" , name_server . name_server , yang_name = "name-server" , rest_name = "name-server" , parent = self , is_container = 'list' , user_ordered = False , path_helper = self . _path_helper , yang_key...
def radiance_to_bt ( arr , wc_ , a__ , b__ ) : """Convert to BT ."""
return a__ + b__ * ( C2 * wc_ / ( da . log ( 1 + ( C1 * ( wc_ ** 3 ) / arr ) ) ) )
def _getdevicetuple ( iobtdevice ) : """Returns an ( addr , name , COD ) device tuple from a IOBluetoothDevice object ."""
addr = _macutil . formatdevaddr ( iobtdevice . getAddressString ( ) ) name = iobtdevice . getName ( ) cod = iobtdevice . getClassOfDevice ( ) return ( addr , name , cod )