signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def do_reconfig ( self , params ) : """\x1b [1mNAME \x1b [0m reconfig - Reconfigures a ZooKeeper cluster ( adds / removes members ) \x1b [1mSYNOPSIS \x1b [0m reconfig < add | remove > < arg > [ from _ config ] \x1b [1mDESCRIPTION \x1b [0m reconfig add < members > [ from _ config ] adds the given members...
if params . cmd not in [ "add" , "remove" ] : raise ValueError ( "Bad command: %s" % params . cmd ) joining , leaving , from_config = None , None , params . from_config if params . cmd == "add" : joining = params . args elif params . cmd == "remove" : leaving = params . args try : value , _ = self . _zk...
def AddFileDescriptor ( self , file_desc ) : """Adds a FileDescriptor to the pool , non - recursively . If the FileDescriptor contains messages or enums , the caller must explicitly register them . Args : file _ desc : A FileDescriptor ."""
self . _AddFileDescriptor ( file_desc ) # TODO ( jieluo ) : This is a temporary solution for FieldDescriptor . file . # Remove it when FieldDescriptor . file is added in code gen . for extension in file_desc . extensions_by_name . values ( ) : self . _file_desc_by_toplevel_extension [ extension . full_name ] = file...
def file_detector_context ( self , file_detector_class , * args , ** kwargs ) : """Overrides the current file detector ( if necessary ) in limited context . Ensures the original file detector is set afterwards . Example : with webdriver . file _ detector _ context ( UselessFileDetector ) : someinput . send ...
last_detector = None if not isinstance ( self . file_detector , file_detector_class ) : last_detector = self . file_detector self . file_detector = file_detector_class ( * args , ** kwargs ) try : yield finally : if last_detector is not None : self . file_detector = last_detector
def white_move ( self ) : """Calls the white player ' s ` ` generate _ move ( ) ` ` method and updates the board with the move returned ."""
move = self . player_white . generate_move ( self . position ) move = make_legal ( move , self . position ) self . position . update ( move )
def coord_to_pixel ( self , lat , lon , width , ground_width , lat2 , lon2 ) : '''return pixel coordinate ( px , py ) for position ( lat2 , lon2) in an area image . Note that the results are relative to top , left and may be outside the image'''
pixel_width = ground_width / float ( width ) if lat is None or lon is None or lat2 is None or lon2 is None : return ( 0 , 0 ) dx = mp_util . gps_distance ( lat , lon , lat , lon2 ) if lon2 < lon : dx = - dx dy = mp_util . gps_distance ( lat , lon , lat2 , lon ) if lat2 > lat : dy = - dy dx /= pixel_width dy...
def _resolve_duplicates ( self ) : '''Merge variables connected by identity operator to reduce the number of redundant variables'''
self . _initialize_graph_status_for_traversing ( ) # Traverse the graph from roots to leaves for operator in self . topological_operator_iterator ( ) : if operator . type != 'identity' : continue if any ( variable . is_root for variable in operator . inputs ) and any ( variable . is_leaf for variable in...
def lrun ( command , * args , ** kwargs ) : '''Run a local command from project root'''
return run ( 'cd {0} && {1}' . format ( ROOT , command ) , * args , ** kwargs )
def determine_opening_indent ( indent_texts ) : '''Determine the opening indent level for a docstring . The opening indent level is the indent level is the first non - zero indent level of a non - empty line in the docstring . Args : indent _ texts : The lines of the docstring as an iterable over 2 - tuples...
num_lines = len ( indent_texts ) if num_lines < 1 : return 0 assert num_lines >= 1 first_line_indent = indent_texts [ 0 ] [ 0 ] if num_lines == 1 : return first_line_indent assert num_lines >= 2 second_line_indent = indent_texts [ 1 ] [ 0 ] second_line_text = indent_texts [ 1 ] [ 1 ] if len ( second_line_text )...
def get_base_type_of_signal ( signal ) : # type : ( canmatrix . Signal ) - > typing . Tuple [ str , int ] """Get signal arxml - type and size based on the Signal properties ."""
if signal . is_float : if signal . size > 32 : create_type = "double" size = 64 else : create_type = "single" size = 32 else : if signal . size > 32 : if signal . is_signed : create_type = "sint64" else : create_type = "uint64" ...
def getVersionNumber ( self ) : """get OpenThreadWpan stack firmware version number"""
print '%s call getVersionNumber' % self . port versionStr = self . __sendCommand ( WPANCTL_CMD + 'getprop -v NCP:Version' ) [ 0 ] return self . __stripValue ( versionStr )
def applies ( self , dataset ) : """Determines whether the dim transform can be applied to the Dataset , i . e . whether all referenced dimensions can be resolved ."""
if isinstance ( self . dimension , dim ) : applies = self . dimension . applies ( dataset ) else : applies = dataset . get_dimension ( self . dimension ) is not None if isinstance ( dataset , Graph ) and not applies : applies = dataset . nodes . get_dimension ( self . dimension ) is not None for op ...
def _get_nits ( self , filename ) : """Iterate over the instances style checker and yield Nits . : param filename : str pointing to a file within the buildroot ."""
try : python_file = PythonFile . parse ( filename , root = self . _root_dir ) except CheckSyntaxError as e : yield e . as_nit ( ) return if noqa_file_filter ( python_file ) : return if self . _excluder : # Filter out any suppressed plugins check_plugins = [ ( plugin_name , plugin_factory ) for plugi...
def get_rudder_scores ( self , category ) : '''Computes Rudder score . Parameters category : str category name to score Returns np . array'''
category_percentiles = self . _get_term_percentiles_in_category ( category ) not_category_percentiles = self . _get_term_percentiles_not_in_category ( category ) rudder_scores = self . _get_rudder_scores_for_percentile_pair ( category_percentiles , not_category_percentiles ) return rudder_scores
def _set_ldp_protocol_errors_instance_since_clear ( self , v , load = False ) : """Setter method for ldp _ protocol _ errors _ instance _ since _ clear , mapped from YANG variable / mpls _ state / ldp / statistics / ldp _ protocol _ errors _ instance _ since _ clear ( container ) If this variable is read - only (...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = ldp_protocol_errors_instance_since_clear . ldp_protocol_errors_instance_since_clear , is_container = 'container' , presence = False , yang_name = "ldp-protocol-errors-instance-since-clear" , rest_name = "ldp-protocol-errors-i...
def copyHdfsDirectoryToLocal ( hdfsDirectory , localDirectory , hdfsClient ) : '''Copy directory from HDFS to local'''
if not os . path . exists ( localDirectory ) : os . makedirs ( localDirectory ) try : listing = hdfsClient . list_status ( hdfsDirectory ) except Exception as exception : nni_log ( LogType . Error , 'List hdfs directory {0} error: {1}' . format ( hdfsDirectory , str ( exception ) ) ) raise exception for...
def open_session ( self ) : """Open a new session to modify this server . You can either call this fnc directly , or turn on autosession which will open / commit sessions for you transparently ."""
if self . session is not None : msg = "session already open; commit it or rollback before opening another one in %s" % self logger . error ( msg ) raise RuntimeError ( msg ) logger . info ( "opening a new session" ) logger . info ( "removing %s" % self . loc_session ) try : shutil . rmtree ( self . loc_...
def define_natives ( cls ) : """Define the native functions for PFP"""
if len ( cls . _natives ) > 0 : return glob_pattern = os . path . join ( os . path . dirname ( __file__ ) , "native" , "*.py" ) for filename in glob . glob ( glob_pattern ) : basename = os . path . basename ( filename ) . replace ( ".py" , "" ) if basename == "__init__" : continue try : ...
def has_response ( self , beacon_config , request , client_address ) : """: meth : ` . WBeaconMessengerBase . has _ response ` method implementation . This method compares request headers as : meth : ` . WBeaconGouverneurMessenger . has _ response ` do and compares specified group names with internal names ."""
try : groups , address = self . _message_hostgroup_parse ( request ) if len ( self . __hostgroups ) == 0 or len ( groups ) == 0 : return True for group_name in groups : if group_name in self . __hostgroups : return True return False except ValueError : pass return False
def polygon_to_geohashes ( polygon , precision , inner = True ) : """: param polygon : shapely polygon . : param precision : int . Geohashes ' precision that form resulting polygon . : param inner : bool , default ' True ' . If false , geohashes that are completely outside from the polygon are ignored . : ret...
inner_geohashes = set ( ) outer_geohashes = set ( ) envelope = polygon . envelope centroid = polygon . centroid testing_geohashes = queue . Queue ( ) testing_geohashes . put ( geohash . encode ( centroid . y , centroid . x , precision ) ) while not testing_geohashes . empty ( ) : current_geohash = testing_geohashes...
def PopupGetFolder ( message , title = None , default_path = '' , no_window = False , size = ( None , None ) , button_color = None , background_color = None , text_color = None , icon = DEFAULT_WINDOW_ICON , font = None , no_titlebar = False , grab_anywhere = False , keep_on_top = False , location = ( None , None ) , i...
if no_window : if Window . QTApplication is None : Window . QTApplication = QApplication ( sys . argv ) folder_name = QFileDialog . getExistingDirectory ( dir = initial_folder ) return folder_name layout = [ [ Text ( message , auto_size_text = True , text_color = text_color , background_color = back...
def encode_ndarray ( obj ) : """Write a numpy array and its shape to base64 buffers"""
shape = obj . shape if len ( shape ) == 1 : shape = ( 1 , obj . shape [ 0 ] ) if obj . flags . c_contiguous : obj = obj . T elif not obj . flags . f_contiguous : obj = asfortranarray ( obj . T ) else : obj = obj . T try : data = obj . astype ( float64 ) . tobytes ( ) except AttributeError : data...
def get_redditor ( self , user_name , * args , ** kwargs ) : """Return a Redditor instance for the user _ name specified . The additional parameters are passed directly into the : class : ` . Redditor ` constructor ."""
return objects . Redditor ( self , user_name , * args , ** kwargs )
def data_type_to_numpy ( datatype , unsigned = False ) : """Convert an ncstream datatype to a numpy one ."""
basic_type = _dtypeLookup [ datatype ] if datatype in ( stream . STRING , stream . OPAQUE ) : return np . dtype ( basic_type ) if unsigned : basic_type = basic_type . replace ( 'i' , 'u' ) return np . dtype ( '=' + basic_type )
def describe_parameters ( name , Source = None , MaxRecords = None , Marker = None , region = None , key = None , keyid = None , profile = None ) : '''Returns a list of ` DBParameterGroup ` parameters . CLI example to description of parameters : : salt myminion boto _ rds . describe _ parameters parametergroupn...
res = __salt__ [ 'boto_rds.parameter_group_exists' ] ( name , tags = None , region = region , key = key , keyid = keyid , profile = profile ) if not res . get ( 'exists' ) : return { 'result' : False , 'message' : 'Parameter group {0} does not exist' . format ( name ) } try : conn = _get_conn ( region = region ...
def print_table ( table , title = '' , delim = '|' , centering = 'center' , col_padding = 2 , header = True , headerchar = '-' ) : """Print a table from a list of lists representing the rows of a table . Parameters table : list list of lists , e . g . a table with 3 columns and 2 rows could be [ [ ' 0,0 ' ,...
table_str = '\n' # sometimes , the table will be passed in as ( title , table ) if isinstance ( table , tuple ) : title = table [ 0 ] table = table [ 1 ] # Calculate each column ' s width colwidths = [ ] for i in range ( len ( table ) ) : # extend colwidths for row i for k in range ( len ( table [ i ] ) - l...
def read_gpx ( xml , gpxns = None ) : """Parse a GPX file into a GpxModel . Args : xml : A file - like - object opened in binary mode - that is containing bytes rather than characters . The root element of the XML should be a < gpx > element containing a version attribute . GPX versions 1.1 is supported ....
tree = etree . parse ( xml ) gpx_element = tree . getroot ( ) return parse_gpx ( gpx_element , gpxns = gpxns )
def command_cycles_per_sec ( self , event = None ) : """TODO : refactor : move code to CPU !"""
try : cycles_per_sec = self . cycles_per_sec_var . get ( ) except ValueError : self . cycles_per_sec_var . set ( self . runtime_cfg . cycles_per_sec ) return self . cycles_per_sec_label_var . set ( "cycles/sec / 1000000 = %f MHz CPU frequency * 16 = %f Mhz crystal" % ( cycles_per_sec / 1000000 , cycles_per_...
def mandelbrot_capture ( x , y , w , h , params ) : """Computes the number of iterations of the given pixel - space coordinates , for high - res capture purposes . Contrary to : func : ` mandelbrot ` , this function returns a continuous number of iterations to avoid banding . : param x : X coordinate on the...
# FIXME : Figure out why these corrections are necessary or how to make them perfect # Viewport is offset compared to window when capturing without these ( found empirically ) if params . plane_ratio >= 1.0 : x -= params . plane_w else : x += 3.0 * params . plane_w ratio = w / h n_x = x * 2.0 / w * ratio - 1.0 ...
def walknode ( top , skiphidden = True ) : """Returns a recursive iterator over all Nodes under top . If skiphidden is True ( the default ) then structure branches starting with an underscore will be ignored ."""
if skiphidden and top . name . startswith ( '._' ) : return yield top for child in top : for c in walknode ( child ) : yield c
def assess_quality ( feed : "Feed" ) -> DataFrame : """Return a DataFrame of various feed indicators and values , e . g . number of trips missing shapes . Parameters feed : Feed Returns DataFrame The columns are - ` ` ' indicator ' ` ` : string ; name of an indicator , e . g . ' num _ routes ' - ` `...
d = OrderedDict ( ) # Count duplicate route short names r = feed . routes dup = r . duplicated ( subset = [ "route_short_name" ] ) n = dup [ dup ] . count ( ) d [ "num_route_short_names_duplicated" ] = n d [ "frac_route_short_names_duplicated" ] = n / r . shape [ 0 ] # Count stop times missing shape _ dist _ traveled v...
def get_font ( self , face , bold = False , italic = False ) : """Get a font described by face and size"""
key = '%s-%s-%s' % ( face , bold , italic ) if key not in self . _fonts : font = dict ( face = face , bold = bold , italic = italic ) self . _fonts [ key ] = TextureFont ( font , self . _renderer ) return self . _fonts [ key ]
def _succeed ( self , result ) : """Fire the success chain ."""
for fn , args , kwargs in self . _callbacks : fn ( result , * args , ** kwargs ) self . _resulted_in = result
def returner ( ret ) : '''Return data to a Cassandra ColumnFamily'''
consistency_level = getattr ( pycassa . ConsistencyLevel , __opts__ [ 'cassandra.consistency_level' ] ) pool = pycassa . ConnectionPool ( __opts__ [ 'cassandra.keyspace' ] , __opts__ [ 'cassandra.servers' ] ) ccf = pycassa . ColumnFamily ( pool , __opts__ [ 'cassandra.column_family' ] , write_consistency_level = consis...
def close ( self ) : """Closes all currently open file pointers"""
if not self . active : return self . active = False if self . _file : self . _file . close ( ) self . _sincedb_update_position ( force_update = True ) if self . _current_event : event = '\n' . join ( self . _current_event ) self . _current_event . clear ( ) self . _callback_wrapper ( [ event ] )
def get_threads ( self ) : """Returns a dict of all threads and indicates thread being debugged . key is thread ident and values thread info . Information from this list can be used to swap thread being debugged ."""
thread_list = { } for thread in threading . enumerate ( ) : thread_ident = thread . ident thread_list [ thread_ident ] = { "ident" : thread_ident , "name" : thread . name , "is_debugger" : thread_ident == self . debugger_thread_ident , "is_debugged" : thread_ident == self . debugged_thread_ident } return thread...
def pcre ( tgt , minion_id = None ) : '''Return True if the minion ID matches the given pcre target minion _ id Specify the minion ID to match against the target expression . . versionadded : : 2014.7.0 CLI Example : . . code - block : : bash salt ' * ' match . pcre ' . * ' '''
if minion_id is not None : opts = copy . copy ( __opts__ ) if not isinstance ( minion_id , six . string_types ) : minion_id = six . text_type ( minion_id ) opts [ 'id' ] = minion_id else : opts = __opts__ matchers = salt . loader . matchers ( opts ) try : return matchers [ 'pcre_match.match'...
def get_param ( self ) : """Method to get current optimizer ' s parameter value"""
cycle_progress = self . event_index / self . cycle_size return self . start_value + ( ( self . end_value - self . start_value ) / 2 ) * ( 1 - math . cos ( math . pi * cycle_progress ) )
def parse_from_xml ( self , xml_spec ) : '''Parse a string or file containing an XML specification . Example : > > > s = RtsProfile ( ) > > > s . parse _ from _ xml ( open ( ' test / rtsystem . xml ' ) ) > > > len ( s . components ) Load of invalid data should throw exception : > > > s . parse _ from _ ...
if type ( xml_spec ) in string_types ( ) : dom = xml . dom . minidom . parseString ( xml_spec ) else : dom = xml . dom . minidom . parse ( xml_spec ) self . _parse_xml ( dom ) dom . unlink ( )
def dispatch_request ( self , * args , ** kwargs ) : """Dispatch current request . Dispatch the current request using : class : ` flask . views . MethodView ` ` dispatch _ request ( ) ` then , if the result is not already a : py : class : ` flask . Response ` , search for the serializing function which matc...
result = super ( ContentNegotiatedMethodView , self ) . dispatch_request ( * args , ** kwargs ) if isinstance ( result , Response ) : return result elif isinstance ( result , ( list , tuple ) ) : return self . make_response ( * result ) else : return self . make_response ( result )
def _end_of_century ( self ) : """Reset the date to the last day of the century and the time to 23:59:59.99999. : rtype : DateTime"""
year = self . year - 1 - ( self . year - 1 ) % YEARS_PER_CENTURY + YEARS_PER_CENTURY return self . set ( year , 12 , 31 , 23 , 59 , 59 , 999999 )
def read ( self , source_path ) : """Parse content and metadata of textile files ."""
with pelican_open ( source_path ) as text : parts = text . split ( '----' , 1 ) if len ( parts ) == 2 : headerlines = parts [ 0 ] . splitlines ( ) headerpairs = map ( lambda l : l . split ( ':' , 1 ) , headerlines ) headerdict = { pair [ 0 ] : pair [ 1 ] . strip ( ) for pair in headerpai...
def _internal_function_call ( self , call_conf ) : '''Call internal function . : param call _ conf : : return :'''
def stub ( * args , ** kwargs ) : message = 'Function {} is not available' . format ( call_conf [ 'fun' ] ) self . out . error ( message ) log . debug ( 'Attempt to run "%s" with %s arguments and %s parameters.' , call_conf [ 'fun' ] , call_conf [ 'arg' ] , call_conf [ 'kwargs' ] ) return message return...
def serialize ( self ) : """Produce YAML version of this catalog . Note that this is not the same as ` ` . yaml ( ) ` ` , which produces a YAML block referring to this catalog ."""
import yaml output = { "metadata" : self . metadata , "sources" : { } , "name" : self . name } for key , entry in self . items ( ) : output [ "sources" ] [ key ] = entry . _captured_init_kwargs return yaml . dump ( output )
def _write_apt_gpg_keyfile ( key_name , key_material ) : """Writes GPG key material into a file at a provided path . : param key _ name : A key name to use for a key file ( could be a fingerprint ) : type key _ name : str : param key _ material : A GPG key material ( binary ) : type key _ material : ( str ,...
with open ( '/etc/apt/trusted.gpg.d/{}.gpg' . format ( key_name ) , 'wb' ) as keyf : keyf . write ( key_material )
def readline ( self ) -> bytes : '''Read a line of data .'''
assert self . _state == ConnectionState . created , 'Expect conn created. Got {}.' . format ( self . _state ) with self . _close_timer . with_timeout ( ) : data = yield from self . run_network_operation ( self . reader . readline ( ) , close_timeout = self . _timeout , name = 'Readline' ) return data
def _read_utf ( cls , data , pos , kind = None ) : """: param kind : Optional ; a human - friendly identifier for the kind of UTF - 8 data we ' re loading ( e . g . is it a keystore alias ? an algorithm identifier ? something else ? ) . Used to construct more informative exception messages when a decoding error o...
size = b2 . unpack_from ( data , pos ) [ 0 ] pos += 2 try : return data [ pos : pos + size ] . decode ( 'utf-8' ) , pos + size except ( UnicodeEncodeError , UnicodeDecodeError ) as e : raise BadKeystoreFormatException ( ( "Failed to read %s, contains bad UTF-8 data: %s" % ( kind , str ( e ) ) ) if kind else ( "...
def get_data_item_for_reference_key ( self , data_item_reference_key : str = None , create_if_needed : bool = False , large_format : bool = False ) -> DataItem : """Get the data item associated with data item reference key . Optionally create if missing . : param data _ item _ reference _ key : The data item refe...
document_model = self . _document_model data_item_reference = document_model . get_data_item_reference ( data_item_reference_key ) data_item = data_item_reference . data_item if data_item is None and create_if_needed : data_item = DataItemModule . DataItem ( large_format = large_format ) data_item . ensure_data...
def generate_voxel_grid ( bbox , szval , use_cubes = False ) : """Generates the voxel grid with the desired size . : param bbox : bounding box : type bbox : list , tuple : param szval : size in x - , y - , z - directions : type szval : list , tuple : param use _ cubes : use cube voxels instead of cuboid o...
# Input validation if szval [ 0 ] <= 1 or szval [ 1 ] <= 1 or szval [ 2 ] <= 1 : raise GeomdlException ( "Size values must be bigger than 1" , data = dict ( sizevals = szval ) ) # Find step size for each direction steps = [ float ( bbox [ 1 ] [ idx ] - bbox [ 0 ] [ idx ] ) / float ( szval [ idx ] - 1 ) for idx in r...
def _accumulate_sufficient_statistics ( self , stats , X , framelogprob , posteriors , fwdlattice , bwdlattice ) : """Updates sufficient statistics from a given sample . Parameters stats : dict Sufficient statistics as returned by : meth : ` ~ base . _ BaseHMM . _ initialize _ sufficient _ statistics ` . ...
stats [ 'nobs' ] += 1 if 's' in self . params : stats [ 'start' ] += posteriors [ 0 ] if 't' in self . params : n_samples , n_components = framelogprob . shape # when the sample is of length 1 , it contains no transitions # so there is no reason to update our trans . matrix estimate if n_samples <= ...
def get ( cls , action , suffix = None ) : """Get or register a handler for the given action . : param func action : Callback that is called when invoking the Handler : param func suffix : Optional suffix for the handler ' s ID"""
action_id = _action_id ( action , suffix ) if action_id not in cls . _HANDLERS : if LOG_OPTS [ 'register' ] : hookenv . log ( 'Registering reactive handler for %s' % _short_action_id ( action , suffix ) , level = hookenv . DEBUG ) cls . _HANDLERS [ action_id ] = cls ( action , suffix ) return cls . _HAN...
def find_or_new ( self , id , columns = None ) : """Find a model by its primary key or return new instance of the related model . : param id : The primary key : type id : mixed : param columns : The columns to retrieve : type columns : list : rtype : Collection or Model"""
if columns is None : columns = [ "*" ] instance = self . _query . find ( id , columns ) if instance is None : instance = self . _related . new_instance ( ) instance . set_attribute ( self . get_plain_foreign_key ( ) , self . get_parent_key ( ) ) return instance
def rescue ( env , identifier ) : """Reboot into a rescue image ."""
vsi = SoftLayer . VSManager ( env . client ) vs_id = helpers . resolve_id ( vsi . resolve_ids , identifier , 'VS' ) if not ( env . skip_confirmations or formatting . confirm ( "This action will reboot this VSI. Continue?" ) ) : raise exceptions . CLIAbort ( 'Aborted' ) vsi . rescue ( vs_id )
def raw_mod ( opts , name , functions , mod = 'modules' ) : '''Returns a single module loaded raw and bypassing the _ _ virtual _ _ function . . code - block : : python import salt . config import salt . loader _ _ opts _ _ = salt . config . minion _ config ( ' / etc / salt / minion ' ) testmod = salt . l...
loader = LazyLoader ( _module_dirs ( opts , mod , 'module' ) , opts , tag = 'rawmodule' , virtual_enable = False , pack = { '__salt__' : functions } , ) # if we don ' t have the module , return an empty dict if name not in loader . file_mapping : return { } loader . _load_module ( name ) # load a single module ( th...
def plot_skyreg ( header , data , ** kwargs ) : """Plot sky region defined by header and data header : FITS header data : Data array"""
kwargs . setdefault ( 'cmap' , 'binary' ) fig = plt . figure ( ) ax = pywcsgrid2 . subplot ( 111 , header = header ) ax . set_ticklabel_type ( "dms" ) im = ax . imshow ( data , origin = "center" , ** kwargs ) ax . grid ( ) ax . add_compass ( loc = 1 , coord = 'fk5' ) ax . add_compass ( loc = 4 , coord = 'gal' ) return ...
def redo ( self , channel , image ) : """This method is called when an image is set in a channel ."""
imname = image . get ( 'name' , 'none' ) chname = channel . name # is image in contents tree yet ? in_contents = self . is_in_contents ( chname , imname ) # get old highlighted entries for this channel - - will be # an empty set or one key old_highlight = channel . extdata . contents_old_highlight # calculate new highl...
def tile_and_reflect ( input ) : """Make 3x3 tiled array . Central area is ' input ' , surrounding areas are reflected . Adapted from https : / / github . com / nicjhan / gaussian - filter"""
tiled_input = np . tile ( input , ( 3 , 3 ) ) rows = input . shape [ 0 ] cols = input . shape [ 1 ] # Now we have a 3x3 tiles - do the reflections . # All those on the sides need to be flipped left - to - right . for i in range ( 3 ) : # Left hand side tiles tiled_input [ i * rows : ( i + 1 ) * rows , 0 : cols ] = ...
def _add_custom_headers ( self , dct ) : """Add the Client - ID header required by Cloud Queues"""
if self . client_id is None : self . client_id = os . environ . get ( "CLOUD_QUEUES_ID" ) if self . client_id : dct [ "Client-ID" ] = self . client_id
def get_task_quota ( self , task_name ) : """Get queueing info of the task . Note that time between two calls should larger than 30 seconds , otherwise empty dict is returned . : param task _ name : name of the task : return : quota info in dict format"""
params = OrderedDict ( [ ( 'instancequota' , '' ) , ( 'taskname' , task_name ) ] ) resp = self . _client . get ( self . resource ( ) , params = params ) return json . loads ( resp . text )
def assertJsonContains ( jsonStr = None , key = None , message = None ) : """Assert that jsonStr contains key . : param jsonStr : Json as string : param key : Key to look for : param message : Failure message : raises : TestStepFail if key is not in jsonStr or if loading jsonStr to a dictionary fails or i...
if jsonStr is not None : try : data = json . loads ( jsonStr ) if key not in data : raise TestStepFail ( format_message ( message ) if message is not None else "Assert: " "Key : %s is not " "in : %s" % ( str ( key ) , str ( jsonStr ) ) ) except ( TypeError , ValueError ) as e : ...
def database_set_properties ( object_id , input_params = { } , always_retry = True , ** kwargs ) : """Invokes the / database - xxxx / setProperties API method . For more info , see : https : / / wiki . dnanexus . com / API - Specification - v1.0.0 / Properties # API - method % 3A - % 2Fclass - xxxx % 2FsetPropert...
return DXHTTPRequest ( '/%s/setProperties' % object_id , input_params , always_retry = always_retry , ** kwargs )
def get_atoms ( self , inc_alt_states = False ) : """Returns all atoms in the ` Monomer ` . Parameters inc _ alt _ states : bool , optional If ` True ` , will return ` Atoms ` for alternate states ."""
if inc_alt_states : return itertools . chain ( * [ x [ 1 ] . values ( ) for x in sorted ( list ( self . states . items ( ) ) ) ] ) return self . atoms . values ( )
def _get_bottom_line_color ( self ) : """Returns color rgb tuple of bottom line"""
color = self . cell_attributes [ self . key ] [ "bordercolor_bottom" ] return tuple ( c / 255.0 for c in color_pack2rgb ( color ) )
def _parse_message ( self , data ) : """Interpret each message datagram from device and do the needful . This function receives datagrams from _ assemble _ buffer and inerprets what they mean . It ' s responsible for maintaining the internal state table for each device attribute and also for firing the update...
recognized = False newdata = False if data . startswith ( '!I' ) : self . log . warning ( 'Invalid command: %s' , data [ 2 : ] ) recognized = True elif data . startswith ( '!R' ) : self . log . warning ( 'Out-of-range command: %s' , data [ 2 : ] ) recognized = True elif data . startswith ( '!E' ) : ...
def get ( self , session , discount_id = None , ext_fields = None ) : '''taobao . fenxiao . discounts . get 获取折扣信息 查询折扣信息'''
request = TOPRequest ( 'taobao.fenxiao.discounts.get' ) if discount_id != None : request [ 'discount_id' ] = discount_id if ext_fields != None : request [ 'ext_fields' ] = ext_fields self . create ( self . execute ( request , session ) ) return self . discounts
def denoise ( self , bitthresh = 0.5 ) : """m . denoise ( bitthresh = 0.5 ) - - Set low - information positions ( below bitthresh ) to Ns"""
for i in range ( self . width ) : tot = 0 for letter in ACGT : if self . logP : Pij = pow ( 2.0 , self . logP [ i ] [ letter ] ) else : Pij = pow ( 2.0 , self . ll [ i ] [ letter ] ) * self . background [ letter ] if Pij > 0.01 : bit = Pij * self . ll ...
def transitive_subgraph_of_addresses_bfs ( self , addresses , predicate = None , dep_predicate = None ) : """Returns the transitive dependency closure of ` addresses ` using BFS . : API : public : param list < Address > addresses : The closure of ` addresses ` will be walked . : param function predicate : If ...
walk = self . _walk_factory ( dep_predicate ) ordered_closure = OrderedSet ( ) to_walk = deque ( ( 0 , addr ) for addr in addresses ) while len ( to_walk ) > 0 : level , address = to_walk . popleft ( ) if not walk . expand_once ( address , level ) : continue target = self . _target_by_address [ addr...
def update_node ( self , char , node , patch ) : """Change a node ' s stats according to a dictionary . The ` ` patch ` ` dictionary should hold the new values of stats , keyed by the stats ' names ; a value of ` ` None ` ` deletes the stat ."""
character = self . _real . character [ char ] if patch is None : del character . node [ node ] elif node not in character . node : character . node [ node ] = patch return else : character . node [ node ] . update ( patch )
def _filter_index_pages ( docnames , base_dir ) : """Filter docnames to only yield paths of the form ` ` < base _ dir > / < name > / index ` ` Parameters docnames : ` list ` of ` str ` List of document names ( ` ` env . found _ docs ` ` ) . base _ dir : ` str ` Base directory of all sub - directories co...
for docname in docnames : parts = docname . split ( '/' ) if len ( parts ) == 3 and parts [ 0 ] == base_dir and parts [ 2 ] == 'index' : yield docname
def set_runtime_value_bool ( self , resourceid : int , value : bool ) -> bool : """Set a boolean runtime value"""
if value : boolvalue = "true" else : boolvalue = "false" payload = """ <setResourceValue1 xmlns=\"utcs\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"> <value i:type=\"a:WSBooleanValue\" xmlns:a=\"utcs.values\"> <a:value>{value}</a:value></value> ...
def filter ( self , datax , datay ) : """Filter a set of datax and datay according to ` self . points `"""
f = np . ones ( datax . shape , dtype = bool ) for i , p in enumerate ( zip ( datax , datay ) ) : f [ i ] = PolygonFilter . point_in_poly ( p , self . points ) if self . inverted : np . invert ( f , f ) return f
def add ( self , name , obj = None ) : """Add the view named ` name ` to the report text"""
if obj : text = '\n::\n\n' + indent ( str ( obj ) ) else : text = views . view ( name , self . dstore ) if text : title = self . title [ name ] line = '-' * len ( title ) self . text += '\n' . join ( [ '\n\n' + title , line , text ] )
def linearize_data_types ( self ) : # type : ( ) - > typing . List [ UserDefined ] """Returns a list of all data types used in the namespace . Because the inheritance of data types can be modeled as a DAG , the list will be a linearization of the DAG . It ' s ideal to generate data types in this order so that...
linearized_data_types = [ ] seen_data_types = set ( ) # type : typing . Set [ UserDefined ] def add_data_type ( data_type ) : # type : ( UserDefined ) - > None if data_type in seen_data_types : return elif data_type . namespace != self : # We ' re only concerned with types defined in this namespace . ...
def scan2 ( self , tablename , expr_values = None , alias = None , attributes = None , consistent = False , select = None , index = None , limit = None , return_capacity = None , filter = False , segment = None , total_segments = None , exclusive_start_key = None , ** kwargs ) : """Perform a full - table scan For...
keywords = { 'TableName' : tablename , 'ReturnConsumedCapacity' : self . _default_capacity ( return_capacity ) , 'ConsistentRead' : consistent , } values = build_expression_values ( self . dynamizer , expr_values , kwargs ) if values : keywords [ 'ExpressionAttributeValues' ] = values if attributes is not None : ...
def inject_func_as_unbound_method ( class_ , func , method_name = None ) : """This is actually quite simple"""
if method_name is None : method_name = get_funcname ( func ) setattr ( class_ , method_name , func )
def _set_traffic_class_dscp ( self , v , load = False ) : """Setter method for traffic _ class _ dscp , mapped from YANG variable / qos / map / traffic _ class _ dscp ( list ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ traffic _ class _ dscp is considered as a priv...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = YANGListType ( "name" , traffic_class_dscp . traffic_class_dscp , yang_name = "traffic-class-dscp" , rest_name = "traffic-class-dscp" , parent = self , is_container = 'list' , user_ordered = False , path_helper = self . _path...
def sign ( self , keys ) : """Sign the current document . Warning : current signatures will be replaced with the new ones ."""
key = keys [ 0 ] signed = self . raw ( ) [ - 2 : ] signing = base64 . b64encode ( key . signature ( bytes ( signed , 'ascii' ) ) ) self . signatures = [ signing . decode ( "ascii" ) ]
def parse_route_attr_filter ( route_attr_filter , debug = False ) : """Args : route _ attr _ filter ( str ) : The raw command - line input of the route filter . Returns : Tuple [ FilterExpr , List [ str ] ] : The second element is a list of errors ."""
assert isinstance ( route_attr_filter , six . text_type ) , type ( route_attr_filter ) parser = FilterExprParser ( debug ) return parser . parse ( route_attr_filter )
def run ( self ) : """Start and supervise services workers This method will start and supervise all children processes until the master process asked to shutdown by a SIGTERM . All spawned processes are part of the same unix process group ."""
self . _systemd_notify_once ( ) self . _child_supervisor = _utils . spawn ( self . _child_supervisor_thread ) self . _wait_forever ( )
def insert_query ( connection , publicId , aead , keyhandle , aeadobj ) : """this functions read the response fields and creates sql query . then inserts everything inside the database"""
# turn the keyhandle into an integer keyhandle = key_handle_to_int ( keyhandle ) if not keyhandle == aead . key_handle : print ( "WARNING: keyhandle does not match aead.key_handle" ) return None # creates the query object try : sql = aeadobj . insert ( ) . values ( public_id = publicId , keyhandle = aead . ...
def rejectionOptionsList ( self ) : "Return a sorted list with the options defined in bikasetup"
plone = getSite ( ) settings = plone . bika_setup # RejectionReasons will return something like : # [ { ' checkbox ' : u ' on ' , ' textfield - 2 ' : u ' b ' , ' textfield - 1 ' : u ' c ' , ' textfield - 0 ' : u ' a ' } ] if len ( settings . RejectionReasons ) > 0 : reject_reasons = settings . RejectionReasons [ 0 ...
def export_to_tf_tensor ( self , x , laid_out_x ) : """Turn a Tensor into a tf . Tensor . Args : x : a Tensor laid _ out _ x : a LaidOutTensor Returns : a tf . Tensor"""
return self . combine_slices ( laid_out_x . all_slices , x . shape )
async def digital_write ( self , command ) : """This method writes a zero or one to a digital pin . : param command : { " method " : " digital _ write " , " params " : [ PIN , DIGITAL _ DATA _ VALUE ] } : returns : No return message . ."""
pin = int ( command [ 0 ] ) value = int ( command [ 1 ] ) await self . core . digital_write ( pin , value )
def _match ( self , kind ) : """The ' match ' primitive of RD parsers . * Verifies that the current token is of the given kind ( kind can be a tuple , in which the kind must match one of its members ) . * Returns the value of the current token * Reads in the next token"""
if ( isinstance ( kind , tuple ) and self . cur_token . kind in kind or self . cur_token . kind == kind ) : value = self . cur_token . value self . _advance ( ) return value else : raise ASDLSyntaxError ( 'Unmatched {} (found {})' . format ( kind , self . cur_token . kind ) , self . cur_token . lineno )
def current ( ) : """Returns the current environment manager for the projex system . : return < EnvManager >"""
if not EnvManager . _current : path = os . environ . get ( 'PROJEX_ENVMGR_PATH' ) module = os . environ . get ( 'PROJEX_ENVMGR_MODULE' ) clsname = os . environ . get ( 'PROJEX_ENVMGR_CLASS' ) cls = EnvManager if module and clsname : # check if the user specified an import path if path : ...
def scheme_specification ( cls ) : """: meth : ` . WSchemeHandler . scheme _ specification ` method implementation"""
return WSchemeSpecification ( 'file' , WURIComponentVerifier ( WURI . Component . path , WURIComponentVerifier . Requirement . optional ) )
def move_users ( self , user_id_list , group_id ) : """批量移动用户分组 。 : param user _ id _ list : 用户 ID 的列表 ( 长度不能超过50) : param group _ id : 分组 ID : return : 返回的 JSON 数据包"""
return self . post ( url = "https://api.weixin.qq.com/cgi-bin/groups/members/batchupdate" , data = { "openid_list" : user_id_list , "to_groupid" : group_id } )
def parse_version ( ver , pre = False ) : """Parse version into a comparable Version tuple ."""
m = RE_VER . match ( ver ) # Handle major , minor , micro major = int ( m . group ( 'major' ) ) minor = int ( m . group ( 'minor' ) ) if m . group ( 'minor' ) else 0 micro = int ( m . group ( 'micro' ) ) if m . group ( 'micro' ) else 0 # Handle pre releases if m . group ( 'type' ) : release = PRE_REL_MAP [ m . grou...
def patch_namespaced_horizontal_pod_autoscaler_status ( self , name , namespace , body , ** kwargs ) : """partially update status of the specified HorizontalPodAutoscaler This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > threa...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . patch_namespaced_horizontal_pod_autoscaler_status_with_http_info ( name , namespace , body , ** kwargs ) else : ( data ) = self . patch_namespaced_horizontal_pod_autoscaler_status_with_http_info ( name , namespace , body ...
def vb_list_machines ( ** kwargs ) : '''Which machines does the hypervisor have @ param kwargs : Passed to vb _ xpcom _ to _ attribute _ dict to filter the attributes @ type kwargs : dict @ return : Untreated dicts of the machines known to the hypervisor @ rtype : [ { } ]'''
manager = vb_get_manager ( ) machines = manager . getArray ( vb_get_box ( ) , 'machines' ) return [ vb_xpcom_to_attribute_dict ( machine , 'IMachine' , ** kwargs ) for machine in machines ]
def libvlc_video_get_track_description ( p_mi ) : '''Get the description of available video tracks . @ param p _ mi : media player . @ return : list with description of available video tracks , or NULL on error .'''
f = _Cfunctions . get ( 'libvlc_video_get_track_description' , None ) or _Cfunction ( 'libvlc_video_get_track_description' , ( ( 1 , ) , ) , None , ctypes . POINTER ( TrackDescription ) , MediaPlayer ) return f ( p_mi )
def trace_method ( cls , method , tracer = tracer ) : """Traces given class method using given tracer . : param cls : Class of the method . : type cls : object : param method : Method to trace . : type method : object : param tracer : Tracer . : type tracer : object : return : Definition success . :...
if is_traced ( method ) : return False name = get_method_name ( method ) if is_untracable ( method ) or name in UNTRACABLE_NAMES : return False if is_class_method ( method ) : setattr ( cls , name , classmethod ( tracer ( method . im_func ) ) ) elif is_static_method ( method ) : setattr ( cls , name , s...
def add_load_constant ( self , name , output_name , constant_value , shape ) : """Add a load constant layer . Parameters name : str The name of this layer . output _ name : str The output blob name of this layer . constant _ value : numpy . array value of the constant as a numpy array . shape : [ in...
spec = self . spec nn_spec = self . nn_spec # Add a new layer spec_layer = nn_spec . layers . add ( ) spec_layer . name = name spec_layer . output . append ( output_name ) spec_layer_params = spec_layer . loadConstant data = spec_layer_params . data data . floatValue . extend ( map ( float , constant_value . flatten ( ...
def extract_queries ( self , args , kwargs ) : '''This function normalizes the config block into a set of queries we can use . The return is a list of consistently laid out dicts .'''
return super ( POSTGRESExtPillar , self ) . extract_queries ( args , kwargs )
def _valid ( m , comment = VALID_RESPONSE , out = None ) : '''Return valid status .'''
return _set_status ( m , status = True , comment = comment , out = out )
def update_tags ( self , idlist , tags_add = None , tags_remove = None ) : """Updates the ' tags ' field for a bug ."""
tags = { } if tags_add : tags [ "add" ] = self . _listify ( tags_add ) if tags_remove : tags [ "remove" ] = self . _listify ( tags_remove ) d = { "ids" : self . _listify ( idlist ) , "tags" : tags , } return self . _proxy . Bug . update_tags ( d )
def circular_references ( self ) -> Set [ str ] : """Return the set of recursive ( circular ) references : return :"""
rval = set ( ) for k in self . grammarelts . keys ( ) : if k in self . dependency_closure ( k ) : rval . add ( k ) return rval
def param_logx_diagram ( run_list , ** kwargs ) : """Creates diagrams of a nested sampling run ' s evolution as it iterates towards higher likelihoods , expressed as a function of log X , where X ( L ) is the fraction of the prior volume with likelihood greater than some value L . For a more detailed descript...
fthetas = kwargs . pop ( 'fthetas' , [ lambda theta : theta [ : , 0 ] , lambda theta : theta [ : , 1 ] ] ) labels = kwargs . pop ( 'labels' , [ r'$\theta_' + str ( i + 1 ) + '$' for i in range ( len ( fthetas ) ) ] ) ftheta_lims = kwargs . pop ( 'ftheta_lims' , [ [ - 1 , 1 ] ] * len ( fthetas ) ) threads_to_plot = kwar...
def parse_task ( self , task ) : '''Parses a WDL task AST subtree . Currently looks at and parses 4 sections : 1 . Declarations ( e . g . string x = ' helloworld ' ) 2 . Commandline ( a bash command with dynamic variables inserted ) 3 . Runtime ( docker image ; disk ; CPU ; RAM ; etc . ) 4 . Outputs ( exp...
task_name = task . attributes [ "name" ] . source_string # task declarations declaration_array = [ ] for declaration_subAST in task . attr ( "declarations" ) : declaration_array . append ( self . parse_task_declaration ( declaration_subAST ) ) self . tasks_dictionary . setdefault ( task_name , OrderedDict ( ) )...
def cwd ( self , new_path ) : '''Sets the cwd during reads and writes'''
old_cwd = self . _cwd self . _cwd = new_path return old_cwd
def get_cmd_help ( self ) : """Get the single - line help of this command . : returns : ` ` self . help ` ` , if defined : returns : The first line of the docstring , without the trailing dot , if present . : returns : None , otherwise"""
try : return self . help except AttributeError : pass try : return get_localized_docstring ( self , self . get_gettext_domain ( ) ) . splitlines ( ) [ 0 ] . rstrip ( '.' ) . lower ( ) except ( AttributeError , IndexError , ValueError ) : pass